text:
Q: Insert SumIfs formula into cell I am trying to insert a SumIfs formula into a cell with defined and locked ranges. The code itself,
Dim wb_stg As Workbook
Dim ws_stg As Worksheet
Dim ws_fwd As Worksheet

Dim ws_stg_daterng As Range
Dim ws_stg_stgrng As Range

Dim ws_fwd_sumrng As Range
Dim ws_fwd_daterng As Range
Dim ws_fwd_stgrng As Range

Dim fwd_stg As String
Dim fwd_date As String

' Locked references
fwd_date = "'Fwd Planning'!J$3" ' Locked row
fwd_stg = "'Fwd Planning'!$A4" ' Locked column

Set wb_stg = ThisWorkbook
Set ws_stg = wb_stg.Sheets("Fwd Planning")
Set ws_fwd = wb_stg.Sheets("FwdPlan_Access")

ws_stg.Activate
' Reference ranges
Set ws_stg_stgrng = ws_stg.Range("A4:A30") ' Row references
Set ws_stg_daterng = ws_stg.Range("J3:AG3") ' Column references

' Data table
ws_fwd.Activate
Set ws_fwd_sumrng = ws_fwd.Range("E:E") ' Sum column
Set ws_fwd_stgrng = ws_fwd.Range("C:C") ' Storage name column
Set ws_fwd_daterng = ws_fwd.Range("D:D") ' Date name column
ws_stg.Activate

' Inserting the SumIfs formula into the wanted cell
ws_stg.Range("J4").Formula = "=SUMIFS(" & ws_fwd_sumrng & "," & ws_fwd_stgrng & ", " = " &" & fwd_date & "," & ws_fwd_daterng & ", " = "" & fwd_date & ")"

Then the error that is given,

Ultimately I am trying to insert this formula in this cell J4 and then PasteSpecial it into the rest of the wanted range. If there is a simpler well, please let me know. Thank you!


text:
Q: PHP replace variables in Word document I have a word document that contains certain variables (for example the string $$title$$). Now I want to open this word document in PHP and replace the string $$title$$ with a string I read out of the database. Final step would be to save this word document and give it to the user for download.
Replacing the string and start the download is no problem. But I don't know how I can get the word content into a variable in php, work with that variable and then save it to a new word document.
Does any one of you know a good PHP class that provides support for editing the contents of a word document? (I'm fine with OpenXML formats if it has to be)

A: Have you tried PHPWord? I've been using PHPExcel from the same site and it is great library.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to retrieve files in Domino Web documents to embed them instead of showing them as links? I have a Notes app that was designed for the browser, not the client. It allowed upload of files into the documents, so nearly all the documents have files. The files are stored in the NSF as $FILE and displayed in the documents as links.
I am using Adobe Acrobat Pro to create PDFs from the documents and need to include the file attachments within the PDFs, however the PDFs just include links to the files, not the attachments. Can I write an agent to run against the documents to get those files and embed them within the documents? When I view those documents through the client, I see all of the HTML etc. and then at the bottom of the document, the file attachments appear. When I view these same documents in the browser, the file attachments do not appear. If I could merely ensure that they are there, then when running the PDF generator in Acrobat Pro, they would be included in the PDFs and executable.
I am really stuck here, with no other way to 'archive' this notes database with all the data intact.
Thanks in advance for any insights!!
Ginni

A: There is a commercial product from Swing Software that does this. I hear that it's quite good, but I've never used it. Let me explain why...
The way I usually end up doing this is just quick-and-dirty. I write an agent to export the files, using the document UNID as part of the filename. The same agent exports all the data fields from the document into a CSV file, and I add a column with the filename of the extracted attachment. In your case, I would add two columns -- one for the extracted attachment(s), and one for the generated PDF. The CSV serves as an index for the exported data. It can be imported into something more friendly, or just left as-is and brought up in Excel, depending on the customer's usage requirements and available systems. I've recommended Swing Software's product and offered to explore other ideas for developing code (e.g., using wkhtmltopdf for Domino web apps to capture a WYSIWYG rendering based on an HTML crawl) for PDF rendering of Notes documents for a couple of clients, but none of them have justified the cost that would be involved in buying licenses and/or writing the code. Quick and dirty always seems to win, even when there are retention and eDiscovery considerations taken into account.


text:
Q: Header shows gradient border My header doesnt show fixed can anyone tell me how to remove this black/and/white on the header here is the

here is the link too  WEB LINK
Here is the code for header gradient
    .enable_fixhead .bliccaThemes-header.off-sticky {

background: transparent;
    background: -moz-linear-gradient(top, rgba(0,0,0,1) 0%, rgba(255,255,255,0) 78%);
    background: -webkit-linear-gradient(top, rgba(0,0,0,1) 0%,rgba(255,255,255,0) 78%);
    background: linear-gradient(to bottom, rgba(0,0,0,1) 0%,rgba(255,255,255,0) 78%);

}

A: Replace:
background: transparent;
    background: -moz-linear-gradient(top, rgba(0,0,0,1) 0%, rgba(255,255,255,0) 78%);
    background: -webkit-linear-gradient(top, rgba(0,0,0,1) 0%,rgba(255,255,255,0) 78%);
    background: linear-gradient(to bottom, rgba(0,0,0,1) 0%,rgba(255,255,255,0) 78%);

with solid color e.g. black:
    background: #000;

So your new code will be:
.enable_fixhead .bliccaThemes-header.off-sticky {
    background: #000; /* use your preferred color */
}

File:
  http://scottstaverna-ks.com/wp-content/themes/sevill/css/main.css
Line: 239

Edit:
You would also like to tweak Sticky header code as follows:
.disable-sticky .bliccaThemes-header.on-sticky,
.enable_fixhead.disable_sticky .bliccaThemes-header.on-sticky {
    position: fixed;
    opacity: 0.8; /* changed from 0 to 0.8 */
    pointer-events: none;
    -webkit-transition: all 800ms cubic-bezier(0.215, 0.610, 0.355, 1.000);
    -moz-transition: all 800ms cubic-bezier(0.215, 0.610, 0.355, 1.000);
    -o-transition: all 800ms cubic-bezier(0.215, 0.610, 0.355, 1.000);
    transition: all 800ms cubic-bezier(0.215, 0.610, 0.355, 1.000);
    background: #000;  /* added solid black color */
}

File:
  http://scottstaverna-ks.com/wp-content/themes/sevill/css/main.css
Line: 238


text:
Q: How to create backorder from python in Odoo? I am odoo newbie. My goal is to create a method in python that will create backorder from unfinished delivery order and will allow me to skip the user input in wizard.
Basically it should have the same functionality as when user clicks on Validate button and then chooses Create Backorder in wizard, but without the user input in wizard.

A: It's easy to use the method inside of stock.picking
Try this:
backorders = your_picking_id._create_backorder()

It'll generate and return backorder for remaining quantity from your current delivery order.

A: You can inherit stock.picking and override the _pre_action_done_hook method to create the backorders instead of returning the confirmation wizard.
class StockPicking(models.Model):
_inherit = 'stock.picking'

def _pre_action_done_hook(self):
    vals = super(StockPicking, self)._pre_action_done_hook()
    if isinstance(vals, dict):
        if (
            vals.get('type') == 'ir.actions.act_window' and
            vals.get('res_model') == 'stock.backorder.confirmation'
        ):
            pickings_to_validate = self.env.context.get(
                'button_validate_picking_ids')
            if pickings_to_validate:
                pickings_to_validate = self.env['stock.picking'].browse(
                    pickings_to_validate).with_context(skip_backorder=True)
                return pickings_to_validate.button_validate()
    return vals

The code block inside above if statement, is taken from process method of stock.backorder.confirmation which is the method linked to the Create Backorder button on the wizard. You can read the method in stock/wizard/stock_backorder_confirmation.py.


text:
Q: Spring Mvc Returning raw Json in treeview treeController.java
@Controller
public class TreeController {

    @RequestMapping(value="/mytree",method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
        return "tree";
    }
    @RequestMapping(value = "/getTechList", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
     public @ResponseBody List<FlatObject.Technology> getTechList(){
        FlatObject ensureCapacity = new FlatObject();
        List<FlatObject.Technology> techList = ensureCapacity.getTechList();
         return techList;

        }

    }

modelclass which generates treenode
public class FlatObject {

    List<Technology> techList = new ArrayList<Technology>(1000);
    private boolean child;
    private Technology root;

    public List<Technology> getTechList() {
        if(techList.isEmpty()){
            ((ArrayList<Technology>) techList).ensureCapacity(1000);
             techList.add(new Technology("Root",1,0));
            techList.add(new Technology("Node 1",2,1));
            techList.add(new Technology("Node 1.1",3,2));
            techList.add(new Technology("Node 1.2",4,2));

            techList.add(new Technology("Node 2",5,1));
            techList.add(new Technology("Node 2.1",6,5));
            techList.add(new Technology("Node 2.2",7,5));
            techList.add(new Technology("Node 2.3",8,5));
        }
        return techList;
    }

    public void setTechList(List<Technology> techList) {
        this.techList = techList;
    }

    public class Technology {

        private int id;
        private int Parentid ;
        private String techName;

        public int getid() {
            return id;
        }

        public void setid(int id) {
            this.id = id;
        }

        public int getParentid() {
            return Parentid;
        }

        public void setParentid(int Parentid) {
            this.Parentid = Parentid;
        }

        public String getTechName() {
            return techName;
        }

        public void setTechName(String techName) {
            this.techName = techName;
        }

        public Technology(String techName,int id, int Parentid) {
            this.id = id;
            this.Parentid = Parentid;
            this.techName = techName;
        }
    }
}

output:
{
id: 1,
techName: "Root",
parentid: 0
},
{
id: 2,
techName: "Node 1",
parentid: 1
},
{
id: 3,
techName: "Node 1.1",
parentid: 2
},
{
id: 4,
techName: "Node 1.2",
parentid: 2
},
{
id: 5,
techName: "Node 2",
parentid: 1
},
{
id: 6,
techName: "Node 2.1",
parentid: 5
},

I am creating tree strucutre using java and springmvc and returning to view in json object .The json not in tree format.so
i want json format like nodes in different level, these all are in same level.how to do this ,please help
i want output like this:
{
data: "Node 3",
state: "open",
children: [
{
data: "Node 3.1",
attr: {
techname: "Node 3.1"
}
},
{
data: "Node 3.2",
attr: {
techname: "Node 3.2"
}
}
],
attr: {
techname: "Node 3"
}
},
{
data: "Node 4",
state: "open",
children: [
{
data: "Node 4.2",
attr: {
techname: "Node 4.2"
}
},
{
data: "Node 4.3",
attr: {
techname: "Node 4.3"
}
},
{
data: "Node 4.4",
attr: {
techname: "Node 4.4"
}
}
],
attr: {
techname: "Node 4"
}
},

I am using HashMap and list to Produce output like Json What i pasted but its not working,Please help how to achieve this, have to write code in spring controller side
@Controller
public class HomeController {

    @RequestMapping(value = "/mytree", method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
        return "tree";
    }

    @RequestMapping(value = "/getTechList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Map<String, String> getTTechList() {

        try {
              DataClass dataClass = new DataClass();
              List<DataClass.Technology> listCPV = dataClass.getTechList();

            Map<String, String> map1 = new HashMap<String, String>();
            ObjectMapper mapper = new ObjectMapper();
            for (int i = 0; i < listCPV.size();) {
                Map<String,String> map2 = new HashMap<String, String>();

                map2.put("state", "open");
                map2.put("data", listCPV.get(i).getTechName());

                Map<String, String> map3 = new HashMap<String, String>();
                map3.put("techname", listCPV.get(i).getTechName());
                String jsonAttr = null;
                map2.put("attr", jsonAttr);
                map3 = null;

                if (listCPV.get(i + 1).getId() == 0) {
                    Map<String, String> map4 = new HashMap<String, String>();

                    while (listCPV.get(i + 1).getId() == 0) {
                        i++;
                        Map<String, String> map5 = new HashMap<String, String>();
                        map5.put("data", listCPV.get(i).getTechName());

                        Map<String, String> map6 = new HashMap<String, String>();
                        map6.put("techname", listCPV.get(i).getTechName());
                        String jsonChildAttr = null;
                        map5.put("attr",jsonChildAttr);
                        map6 = null;

                        map4.putAll(map5);
                        map5 = null;

                        if (listCPV.size() == (i + 1)) {
                            break;
                        }
                    }

                }
                i++;
            }

        } catch (Exception e) {
            System.out.println(e);
        }
        return null;

    }
}

A: I think you need something like this
{
id: 1,
techName: "Root",
parentid: 0,
child: [{
        id: 2,
        techName: "Node 1",
        parentid: 1,
        child:[ {
            id: 3,
            techName: "Node 1.1",
            parentid: 2,
            child:
            },{
            id: 4,
            techName: "Node 1.2",
            parentid: 2,
            child:
            } ]
        },{
        id: 5,
        techName: "Node 2",
        parentid: 1,
        child: [{
            id: 6,
            techName: "Node 2.1",
            parentid: 5,
            child:
            }]
        }]
}

And if yes then there has to be changes to your java code. From from my exp it should be more a combination of a list and a map.
Kindly let me know if you still cant do it but do share your efforts applied to achieve the same.

A: Maybe it will be helpfull
public class FlatObject {

    private int parentId;
    private String techName;
    List<Technology> childList = new ArrayList<Technology>(1000);

    public FlatObject() {
        this.parentId = 1;
        this.techName = "Root";
        if(this.childList.isEmpty()){
            ((ArrayList<Technology>) this.childList).ensureCapacity(1000);
            this.childList.add(new Technology("Node 1",2,1));
            this.childList.add(new Technology("Node 1.1",3,2));
            this.childList.add(new Technology("Node 1.2",4,2));

            this.childList.add(new Technology("Node 2",5,1));
            this.childList.add(new Technology("Node 2.1",6,5));
            this.childList.add(new Technology("Node 2.2",7,5));
            this.childList.add(new Technology("Node 2.3",8,5));
        }
    }

public @ResponseBody List<FlatObject> getTechList() {
FlatObject ensureCapacity = new FlatObject();
        FlatObject ensureCapacity1 = new FlatObject();
        List<FlatObject> techList = new ArrayList<>();
        techList.add(ensureCapacity);
        techList.add(ensureCapacity1);
        return techList;
}

[
  {
    "techName": "Root",
    "parentId": 1,
    "childList": [
      {
        "id": 2,
        "parentid": 1,
        "techName": "Node 1"
      },
      {
        "id": 3,
        "parentid": 2,
        "techName": "Node 1.1"
      },
      {
        "id": 4,
        "parentid": 2,
        "techName": "Node 1.2"
      },
      {
        "id": 5,
        "parentid": 1,
        "techName": "Node 2"
      },
      {
        "id": 6,
        "parentid": 5,
        "techName": "Node 2.1"
      },
      {
        "id": 7,
        "parentid": 5,
        "techName": "Node 2.2"
      },
      {
        "id": 8,
        "parentid": 5,
        "techName": "Node 2.3"
      }
    ]
  },
  {
    "techName": "Root",
    "parentId": 1,
    "childList": [
      {
        "id": 2,
        "parentid": 1,
        "techName": "Node 1"
      },
      {
        "id": 3,
        "parentid": 2,
        "techName": "Node 1.1"
      },
      {
        "id": 4,
        "parentid": 2,
        "techName": "Node 1.2"
      },
      {
        "id": 5,
        "parentid": 1,
        "techName": "Node 2"
      },
      {
        "id": 6,
        "parentid": 5,
        "techName": "Node 2.1"
      },
      {
        "id": 7,
        "parentid": 5,
        "techName": "Node 2.2"
      },
      {
        "id": 8,
        "parentid": 5,
        "techName": "Node 2.3"
      }
    ]
  }
]


text:
Q: processing multiple files in a folder and placing in a different folder with same file name using vba I have made a code for reading a txt file and delete a set of lines in that file and save it in another location. Can you help me out in modifying the code for reading multiple files present in a particular folder and then do the process on all files and save those files with the same name in a different folder .I have attached the code herewith.
Sub cleantext()
Dim lineOfText As String
Dim skipLines As Boolean
'Open files for writing
Open "C:\Users\INNAR1\Desktop\input_static_files\ebb_htr01h.UCBG" For Input As #1
Open "C:\Users\INNAR1\Desktop\output_static_files\ebb_htr01h.UCBG" For Output As #2

skipLine = False
Do Until EOF(1)
Line Input #1, lineOfText
If lineOfText = "dynamics" Then skipLines = True
If lineOfText = "end dynamics" Then skipLines = False
If Not skipLines And Not lineOfText = "end dynamics" Then Print #2, lineOfText
Loop
Close #1
Close #2
End Sub

Thanks in advance

A: You can use Scott's suggestion to loop over files and call the following version to process any given file. You should add error handling.
Sub cleantext(ByVal InputFileName As String, ByVal OutputFileName As String)
    Dim lineOfText As String
    Dim skipLines As Boolean

    Dim iInput As Integer
    Dim iOutput As Integer

    'Open files for writing
    Open InputFileName For Input As #iInput
    Open OutputFileName For Output As #iOutput

    skipLine = False
    Do Until EOF(1)
        Line Input #iInput, lineOfText
        If lineOfText = "dynamics" Then skipLines = True
        If lineOfText = "end dynamics" Then skipLines = False
        If Not skipLines And Not lineOfText = "end dynamics" Then Print #iOutput, lineOfText
    Loop

    Close #iInput
    Close #iOutput
End Sub


text:
Q: Start menu will cover the Window when not open in Visual Studio I have create a Window use WPF, I want to my Window always display on the top, So I just create a thread for it:
System.Threading.Tasks.Task.Factory.StartNew(() =>
{
      for (;;)
      {
         System.Threading.Thread.Sleep(3000);

         this.Dispatcher.BeginInvoke(new Action(() =>
         {
               this.Activate();
               this.Topmost = true;
         }));
      }

   });
}

This will make sure my window go to front in every 3 seconds.
And when I open it under Visual Studio 2015, all fine, even when I open the Start Menu, it will close start menu and bring the window on top.But when I'm not use Visual studio open the application(just double click open the application), when I open start menu, the Window just flickering, not display on the top. What I miss? and how do I let it work as like open the application under Visual Studio 2015(I'm tested on Win10)?

A: EDIT: I somehow missed the point covered in the title. The point I make later of "Do not do it" still holds true though. It could cause problems for users of your application.
If you really need to though, this answer may be the one you are looking for. It discusses how to keep a window in front of everything. It is still a work around (just like most answers to your question).
Old Answer
I understand your problem as: you want your window to stay on top of all other windows. Similar functionality can be found in Ubuntu and The Google Play Music desktop application for Window's (see below).

To accomplish this, all you need to do is add Topmost="True" to your Window as demonstrated below (look at the last property).
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Topmost="True">
</Window>

Unless your actual problem "is what happens when two windows have that property set?" Then I would suggest reading this article (the same article that was referenced in the comments). It states the following:

"How do I create a window that is never covered by any other windows, not even other topmost windows?"
Imagine if this were possible and imagine if two programs did this.
  Program A creates a window that is "super-topmost" and so does Program
  B. Now the user drags the two windows so that they overlap. What
  happens? You've created yourself a logical impossibility. One of those
  two windows must be above the other, contradicting the imaginary
  "super-topmost" feature.

If that functionality is really what you are after, I would suggest: do not do it. All other solutions are a workaround and could cause problems for consumers of your application.

A: I would have used interop to do this.
public class Interop
{
    [DllImport("user32.dll")]
    public static extern bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hwind, int cmd);

    [DllImport("user32.dll")]
    public static extern IntPtr GetForegroundWindow();

    public static IntPtr GetWindowHandle(Window window)
    {
        return new WindowInteropHelper(window).Handle;
    }
}

then use a timer:
private void Tick(object state)
    {

        this.Dispatcher.Invoke(() =>
        {
             IntPtr window = Interop.GetWindowHandle(this);
             IntPtr focused = Interop.GetForegroundWindow();
            if (window != focused)
            {
                Interop.SetForegroundWindow(window);
                                      // Command 5 for show
                Interop.ShowWindow(window, 5);
            }
        });
    }

Code from
And for the part of your problem regarding the startmenu, just add a group policy.
Or you can make a interop to ´FindWindowEx´ to find the startbutton and disable it.

A: I agree with Jonas's answer but would modify it to use an event instead of a timer.
    /// Get the topmost window handle
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    /// Trigger event when topmost window changed
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, TopmostWindowChangedDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);

    /// Set the topmost window
    [DllImport("user32.dll")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);

    /// Show a window
    [DllImport("user32.dll")]
    private static extern bool ShowWindow(IntPtr hwind, int cmd);

    // Constant variables for topmost window changed event
    private const uint WINEVENT_OUTOFCONTEXT = 0;
    private const uint EVENT_SYSTEM_FOREGROUND = 3;

    /// Keep track of the last topmost window with a name
    private static IntPtr topWinHandle { get; set; }

    /// Implementation of topmost window changed delegate
    private TopmostWindowChangedDelegate TopmostWindowChanged { get; set; }

Then set up the handlers in one of your startup methods
    // Set topmost window changed event handler
    TopmostWindowChanged = new TopmostWindowChangedDelegate(WinEventProc);

    // Set event hook for topmost window changed
    IntPtr hook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, TopmostWindowChanged, 0, 0, WINEVENT_OUTOFCONTEXT);

And then move your window to topmost when the other topmost changes
    /// Make sure this window stays on top
    public void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
    {
        // Get current window name from handle
        IntPtr handle = GetForegroundWindow();

        if(handle != YOUR_WINDOW'S_HANDLE)
        {
             // Move your window back to the top
             SetForegroundWindow(YOUR_WINDOW'S_HANDLE);
             ShowWindow(YOUR_WINDOW'S_HANDLE, 5);
        }
    }


text:
Q: How to use SSL on only half of the site? My Site is half ecommerce store and half community blog. I've enabled SSL throughout the site, but the moment a community member posts a non-HTTPs link, the entire site becomes "insecure" according to the SSL certificate.
How do I require SSL on ONLY the ecommerce portion of the site?
I was told I may have to run my community Blog and ecommerce site as separate Joomla! installations. Surely there is a better way?
So that you can see the site it's www.DetourJournal.com

A: It doesn't make sense to me why you would get warnings just because you have some links to http sites.
But I have a similar setup but I went with only enabling SSL for the eCommerce part only. Simple to do with this plug-in.


text:
Q: Why line 27 is executed before line 24? I m beginner with javascript and try to build a clean object to use the Dockerode library in my use Case. I have an async problem here my line 27 executes before 24 and I don't understand why and how to fix it!
Also if it's easier for you, please visit this public gist: https://gist.github.com/msitruk/2cdb655a0bebdb29c61d8bc5606a2695
const Docker = require('dockerode');
const docker = new Docker({
    socketPath: '/var/run/docker.sock'
});

// CONSTRUCTOR
function SearchUtils() {
    this.listContainersPromise = docker.listContainers({all: true});
    this.scraperListId = [];
}

// "METHODS"
SearchUtils.prototype.run = function() {
    this.getScraperContainersListPromise()
        .then((containers) => {
            for (let i = 0; i < containers.length; i++) {
                if (containers[i].Names.toString().indexOf("scraper") !== -1) {
                    this.addToScraperList(containers[i].Id, "wait");
                }
            }
        }, (err)=>{console.log(err)})
        .then(()=>{
            this.checkReadyScraper();
        },(err)=>{console.log(err)})
        .then(() => {
            this.scrap();
        }, (err)=>{console.log(err)});
};

SearchUtils.prototype.checkReadyScraper = function() {
    for (let i = 0; i < this.scraperListId.length; i++) {
        this.exec("getStatus", this.scraperListId[i].id);
    }
};

SearchUtils.prototype.getScraperContainersListPromise = function() {
    return this.listContainersPromise; // <- Not working
};

SearchUtils.prototype.exec = function(type, containerId){
    let container = docker.getContainer(containerId);
    if (type === "getStatus"){
        this.runExec(container, 'cat /home/immobot/status');
    }
    else if (type === "scrap") {
        this.runExec(container, 'torify scrapy crawl seloger -o seloger.json');
    }
};

SearchUtils.prototype.scrap = function() {
    let localRdyScraperList = [];
    for (let i = 0; i < this.scraperListId.length; i++) {
        if(this.scraperListId[i].status.toString('utf8').indexOf("ready") !== -1){
            localRdyScraperList.push(this.scraperListId[i].id);
        }
    }
    console.log("test de localRdyScraperList : "+localRdyScraperList);
    // this.exec("scrap", this.scraperListId[i].id);
};

SearchUtils.prototype.addToScraperList = function(containerId,status) {
    this.scraperListId.push({id: containerId, status: status});
};

SearchUtils.prototype.getScraperList = function() {
    return this.scraperListId;
};

SearchUtils.prototype.getScraperList = function() {
    return this.scraperListId;
};

SearchUtils.prototype.runExec = function (container, cmd) {
    let options = {
        Cmd: [ '/bin/bash', '-c', cmd ],
        AttachStdout: true,
        AttachStderr: true
    };

    container.exec(options, (err, exec) => {
        if (err) return;
        exec.start((err, stream) => {
            if (err){
                console.log("error : "+err);
                return;
            }

            // container.modem.demuxStream(stream, process.stdout, process.stderr)

            if (cmd === "cat /home/immobot/status"){
                let newStream = require('stream');
                let logStream = new newStream.PassThrough();
                logStream.on('data', (chunk) => {
                    // console.log(chunk.toString('utf8'));
                    if (chunk.toString('utf8').indexOf("ready") !== -1){
                        console.log("CONTAINER READY !!");
                        //EDIT CONTAINER STATUS IN SCRAPERLIST TO READY
                        this.changeStatusToReady(container.id);
                    }
                });
                container.modem.demuxStream(stream, logStream, process.stderr);

            }
            else if (cmd === "torify scrapy crawl seloger -o seloger.json"){
                console.log("on lance le scrape sur un des scraper rdy");
                container.modem.demuxStream(stream, process.stdout, process.stderr)
            }

            // container.modem.demuxStream(stream, logStream, process.stderr);

            exec.inspect(function(err, data) {
                if (err){
                    console.log("error : "+err);
                    return;
                }
            });
        });
    });
};

SearchUtils.prototype.changeStatusToReady = function (containerId){
    for (let i = 0; i < this.scraperListId.length; i++) {
        if(this.scraperListId[i].id === containerId){
            this.scraperListId[i].status = "ready";
        }
    }
    // console.log(this.getScraperList());
};

module.exports = SearchUtils;

A: If your chaining promises, don't forget to return your next promise..
eg..
.then(()=>{
  this.checkReadyScraper();
}

If checkReadyScraper() is a promise, then you will want to return it.
eg.
.then(()=>{
  return this.checkReadyScraper();
}

Otherwise all your doing is running checkReadyScraper() and totally ignoring the returned Promise.
Here is how I think your runExec should look.  I'm assuming the exec.inspect is what you want to resolve on.

SearchUtils.prototype.runExec = function (container, cmd) {
    return new Promise ((resolve, reject)=>{
        let options = {
            Cmd: [ '/bin/bash', '-c', cmd ],
            AttachStdout: true,
            AttachStderr: true
        };

        container.exec(options, (err, exec) => {
            if (err) return reject(err); //return error
            exec.start((err, stream) => {
                if (err){
                    console.log("error : "+err);
                    return reject(err); //return error
                }

                // container.modem.demuxStream(stream, process.stdout, process.stderr)

                if (cmd === "cat /home/immobot/status"){
                    let newStream = require('stream');
                    let logStream = new newStream.PassThrough();
                    logStream.on('data', (chunk) => {
                        // console.log(chunk.toString('utf8'));
                        if (chunk.toString('utf8').indexOf("ready") !== -1){
                            console.log("CONTAINER READY !!");
                            //EDIT CONTAINER STATUS IN SCRAPERLIST TO READY
                            this.changeStatusToReady(container.id);
                        }
                    });
                    container.modem.demuxStream(stream, logStream, process.stderr);

                }
                else if (cmd === "torify scrapy crawl seloger -o seloger.json"){
                    console.log("on lance le scrape sur un des scraper rdy");
                    container.modem.demuxStream(stream, process.stdout, process.stderr)
                }

                // container.modem.demuxStream(stream, logStream, process.stderr);

                exec.inspect(function(err, data) {
                    if (err){
                        console.log("error : "+err);
                        //don't forget to return the rejection
                        return reject(err);
                    }
                    //looks like everything was ok, lets resolve
                    resolve(data);
                });
            });
        });
        //resolve("ok"); too early
        // TODO ADD EROR STRATEGY
        //reject("error"), pointless
    });
};

A: Executing a task (with container.exec, on line 81 in your code), runs asynchronious from the rest of your steps, having a callback when they are done.
You would have to make sure all the checks for scrapers are finished before running the scrap command if order matters.

A: First - there is no need to handle errors in every then() call.
You can implement a single error catch, which will catch error in any then() item in a sequence:
.then(()=> {
  this.checkReadyScraper();
})
.then(() => {
  this.scrap();
})
.catch(e => console.log(e))

Also note, that arrow function like catch(e => console.log(e)) doesn't require {} and ;
Your problem is that your task is Async. If you want to chain tasks - you should make a task to return a Promise
This is a rough exaple what you should refactor:
//Should return Promise
SearchUtils.prototype.exec = function(type, containerId){
  let container = docker.getContainer(containerId);
  if (type === "getStatus"){
    //runExec should return us a Promise
    return this.runExec(container, 'cat /home/immobot/status');
  }
  else if (type === "scrap") {
    return this.runExec(container, 'torify scrapy crawl seloger -o seloger.json');
  }
};

SearchUtils.prototype.runExec = function (container, cmd) {
  return new Promise(function(resolve, reject) {
     //do some stuff
     //then call resolve(result)
     //or call reject(error)
  });
}

After this, you will be able to chain Promises (which is quite awesome actually and helps to solve callback hell):
.then(()=> {
  //this not returns Promise, and it will be correctly chained
  return this.checkReadyScraper();
})
.then(() => {
  //this not returns Promise, and it will be correctly chained
  return this.scrap();
})
.catch(e => console.log(e))

Also, to make this looks cleaner I even recommend to do some small refactoring, which will finally give you oneliner:
.then(this.checkReadyScraper).then(this.scrap).catch(console.log)


text:
Q: How to implement CCMotionStreak After CCsprite move? hello friend i want to implement MotionStreak after Sprite move from one to another point.when it move then its display shadow (MotionStreak). how can i implement it.

A: First you take a sprite in init method which move on Screen
torpedoOne = [CCSprite spriteWithFile:@"Button1.png"];
        torpedoOne.position = ccp(0,0);
        [self addChild:torpedoOne z:2];

Now take CCMotionStreak in init method
 streak = [CCMotionStreak streakWithFade:1.7f minSeg:5 width:10 color:ccWHITE textureFilename:@"Button1.png"];
    streak.position =torpedoOne.position;
[self addChild:streak z:2];

Action of SpriteMove
   id actionMove = [CCMoveTo actionWithDuration:2.0
                                        position:ccp(320, 320)];
    [torpedoOne runAction:[CCSequence actions:actionMove, nil]];

Update sprite position
[self schedule:@selector(doStep:)];

Update Method
- (void)doStep:(ccTime)delta
{
    //update the position
    [streak setPosition:torpedoOne.position];
}


text:
Q: Duration of tasks with Windows Task scheduler Is it possible to know the duration of a certain task to calculate from "Created Task Process" to "Task completed"?
Task scheduler only show the Last Run Time but not the duration of all execution.

A: You can do something like the following:
$TaskName = '\Task Name'
$StartTime = (Get-Date).Adddays(-7)
$EndTime = Get-Date
$filter = @{ LogName = 'Microsoft-Windows-TaskScheduler/Operational'
             ID = 129,102
             StartTime = $StartTime
             EndTime = $EndTime
             Data = $TaskName
          }

Get-WinEvent -FilterHashTable $filter | Select-Object TimeCreated,@{n='Action';e={$_.TaskDisplayName}}

Explanation:
For $TaskName, you must enter the task name exactly as it would show in (Get-WinEvent).Properties. You can also see this exact name in the task history messages. It will likely contain the backslash in the name.
You can set $StartTime and $EndTime to whatever you like here. Having a time interval speeds up the query retrieval time.
$filter is where the magic happens. It will ultimately be pushed into the parameter -FilterHashTable. Since the ID key can accept an array of [int], we can just comma separate the values. 129 is Created Task Process. 102 is Task Completed. Data does not accept wildcards so we must be exact with the task name as it would show in a System.Diagnostics.Eventing.Reader.EventProperty property. If you do not use Data, you will have to rely on Where-Object to further filter your task data by the task name, which will be significantly slower.


text:
Q: Functions containing parameter 'yourtheme' I had a colleague create a new theme and while doing so he copied an old theme and made the changes necessary. Now, in many of the files, there are functions that contain the old theme name in the function call instead of the new theme name. Is this parameter used in WordPress for anything and I should therefore change it, or is it OK to leave it with the old theme name?

A: You can leave it or change it, it doesn't matter as long as the theme files use the correct handle for the function. I would choose one name and convert the second version so all use the same name to keep it simple.

A: I believe you're referring to the text domain used for internationalization. It should be safe to leave as-is.


text:
Q: How to extract a value and use it in a future xpath query? I'm extracting the value of a node into a variable:
<xsl:variable name="UPC" select="//x:input[@name='field-keywords']/@value"/>
<xsl:value-of select="$UPC" />  <!-- This works! -->

Then I want to query another XML document for a node with the same value:
<xsl:value-of select="document('price_list.xml')/im_prices/row/UPC_Code[text()='$UPC']"/>

When I substitute $UPC for the actual value I find the node just fine, but when I use $UPC it doesn't work.
I haven't been able to work out how to extract the value to a variable and use it in a future xpath query.

A: Just remove the apostrophes -- in your expression you compare to the literal "$UPC":
 <xsl:value-of select=
   "document('price_list.xml')
        /im_prices/row/UPC_Code[text()=$UPC]"/>

There is something more to be said about this question:

I'm extracting the value of a node into a variable:
 <xsl:variable name="UPC" select="//x:input[@name='field-keywords']/@value"/>

No, this doesn't "extract the value" -- the variable's value is a set of nodes, aka nodeset.
Also, do note that this nodeset in general has more than one node.

 <xsl:value-of select="$UPC"/>  <!-- This works! -->

This outputs the string value of the first node contained in the variable $UPC.
Then I want to query another XML document for a node with the same value:

     <xsl:value-of select="document('price_list.xml')/im_prices/row/UPC_Code[text()='$UPC']"/>

Even if the apostrophes are removed, the above outputs the string value of the first of the document('price_list.xml')/im_prices/row/UPC_Code elements that has a text node child whose string value is equal to the string value of one of the nodes contained in the variable $UPC.


text:
Q: golang.org/x/crypto/bcrypt which error case when generating hash This is the function to generate hashed password using bcrypt
func GenerateFromPassword(password []byte, cost int) ([]byte, error)

GenerateFromPassword returns the bcrypt hash of the password at the given cost. If the cost given is less than MinCost, the cost will be set to DefaultCost, instead. Use CompareHashAndPassword, as defined in this package, to compare the returned hashed password with its cleartext version.

In which case this function returns an error other than the cost out of range (4, 31)? and the weird thing is they set cost to default when below minimum cost but return an error when the cost is above maximum cost, any reason behind this?

A: In addition to returning an error for bad parameters, the function returns an error if it cannot read from the secure random number generator.


text:
Q: Edit visibility of TextView on button click I have two Activities (MainActivity and SecondActivity). My MainActivity has two buttons and my SecondActivity has a TextView. That two buttons will lead to the second activity. What I want to do is, when I click the first button, the TextView visibility will be gone. Is that possible?
public void hi(View v) {

        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
}

public void hello(View v) {

        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
}

A: Yes, that is possible.
A simple way to achieve this effect is adding an extra to your Intent.
public void hi(View v) {
        Intent intent = new Intent(this, SecondActivity.class);
        intent.putExtra("textViewVisible", true);
        startActivity(intent);
}

public void hello(View v) {
        Intent intent = new Intent(this, SecondActivity.class);
        intent.putExtra("textViewVisible", false);
        startActivity(intent);
}

In your SecondActivities onCreate() method you get your boolean value and set the visible depending on it.
public void onCreate() {
     ...
  if(getIntent().getBooleanExtra("textViewVisible", true)) {
       textView.setVisibility(View.VISIBLE);
  } else {
       textView.setVisibility(View.INVISIBLE);
  }
}

A: You can send a boolean value
   Intent intent = new Intent(this, SecondActivity.class);
   intent.putExtra("key",true);
   startActivity(intent);

On second button click you can use intent.putExtra("key",false);
Then in SecondActivity
    boolean value = getIntent().getBooleanExtra("key",false);

Based on value set the visibilty of textview in SecondActivity.
     if(value==true)
      {
           textView.setVisibility(View.INVISIBLE);
      }

http://developer.android.com/reference/android/content/Intent.html
public boolean getBooleanExtra (String name, boolean defaultValue)

Added in API level 1
Retrieve extended data from the intent.

Parameters
name    The name of the desired item.
defaultValue    the value to be returned if no value of the desired type is stored with the given name.
Returns
the value of an item that previously added with putExtra() or the default value if none was found.

A: Yes, its possible. You can do this by passing a boolean value to the SecondActivity...if that is true than hide the TextView.
public void hi(View v) {

        Intent intent = new Intent(this, SecondActivity.class);
        intent.putExtra("isDismiss", true);
        startActivity(intent);
}

In SecondActivity...
boolean isDismiss = getIntent().getBooleanExtra("isDismiss", false);

if (isDismiss) {
    textView.setVisibility(View.GONE);
}


text:
Q: Two-way Data binding is not working using index with ngModel I am displaying countries using ngFor along with input boxes. I used input boxes for giving cost to particular product and country. My question is how to display entered value using ngModel, Here i bind [index] with ngModel.
Suppose if i entered 100 for country India, it saves into database fine. But two way dataBinding is not working.
How to use two way databinding with ngModel using index in angular5 stackblitz
Can anyone please help.

A: You don't really need to bind to (keyup) if you're using [(ngModel)]
Just doing this would do:

              {{x.name}}

            <input
              type="text"
              class="form-control"
              [name]="'name_'+i"
              [(ngModel)]="countries[i].value">

    {{ countries | json }}

Here's a Working Sample StackBlitz for your ref.


text:
Q: How to get FQL Stream with full names I would like to show stream data from FQL
fql?q=SELECT post_id, app_id, source_id, updated_time, created_time, filter_key,
      attribution, actor_id, target_id, message, app_data, action_links,
      attachment, impressions, comments, likes, place, privacy, permalink, xid,
      tagged_ids, message_tags, description, description_tags, type
      FROM stream WHERE filter_key in (
            SELECT filter_key FROM stream_filter WHERE uid=me()
            AND type='newsfeed')

but the problem is that that table doesn't have name of the users/pages, only ids.
Is there any way to get names to those results too? And not only actor_id, but also name for the people who has made comments.
Do I need to make multiquery and search against all those ids in the stream, and then fetch from user and page tables. And then loop those results for every single stream result, seems kind of heavy. Any easier way?

A: I'm not sure if there is a way to get all the users and pages in one go  but you could run two separate queries that will return the users/pages and then performance an array merge with both sets of results.
Users
SELECT uid,name from user where uid in (SELECT source_id FROM stream WHERE filter_key in (SELECT filter_key FROM stream_filter WHERE uid=me() AND type='newsfeed'))
Pages
SELECT page_id,name from page where page_id in (SELECT source_id FROM stream WHERE filter_key in (SELECT filter_key FROM stream_filter WHERE uid=me() AND type='newsfeed'))

A: You can do it in following way :
 NSString *query =
    @"{"
    @"'friends':'SELECT post_id,actor_id,target_id,message,created_time, likes, comment_info FROM stream WHERE source_id IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND created_time > 1  ORDER BY created_time DESC LIMIT 50',"
    @"'friendinfo':'SELECT uid, name, pic_square FROM user WHERE uid IN (SELECT actor_id FROM #friends)',"
    @"}";

Once you will get result, store it into two arrays like this :
FBFriendsNewsArray =(NSArray *) [[[result objectForKey:@"data"]objectAtIndex:0]objectForKey:@"fql_result_set"];

                              FBFriendsInfoArray=(NSArray *) [[[result objectForKey:@"data"]objectAtIndex:1]objectForKey:@"fql_result_set"];

And while displaying Feed search for that user id (actor_id) in Friends info array. hope this will help.


text:
Q: How to use env on Github pages? we're calling a third-party API on github pages.
right now if you view source of our page you can see the API secret.
How can we use env or a similar solution with github pages to hide the secret from view source?

A: There is no secure way to store a secret on GitHub Pages.  GitHub Pages is for static sites only.  With a static site, only HTML, CSS, JavaScript, and images are available, and there is no backend.  As a result, you cannot use a static site host for anything where you require secure secret storage.
You'll need to find a different hosting platform and provide a suitable backend that can perform privileged operations for you.


text:
Q: Exception thrown: 'System.ArgumentException' in Microsoft.VisualBasic.dll When trying to delete empty folders I'm writing a program that scans for empty folders and deletes them. I have a question about my code. When I run the debugger it throws an error when it's going to scan for folders and the error it throws is. 'System.ArgumentException' in Microsoft.VisualBasic.dll. I cannot really find anything online about this error. Here's my code.
Private Sub RemoveEmptyFolders(ByVal path As String)

    Try
        For Each fname As String In Directory.GetDirectories(Dir)
            Dim fn As New DirectoryInfo(fname)
            If fn.GetFiles.Length = 0 AndAlso fn.GetDirectories.Length = 0 Then
                fn.Delete()
                Console.WriteLine("Deleted " + fname + "!")
            End If
        Next
        For Each subdir As String In Directory.GetDirectories(Dir)
            RemoveEmptyFolders(subdir)
        Next
    Catch
    End Try

End Sub

I have no idea why I'm getting this error in the debugger and I have no idea what I'm missing here. The code looks just about right from my perspective. Can anyone tell me what the problem is?

A: when you call the second loop the directory is already been deleted and that is why you are getting the System.ArgumentException. if you want to use two loops, put the second inside the first and execute the fn.Delete() after you removed all the sub-directories.


text:
Q: Could an observer in time determine whether time had no beginning or had a beginning infinitely long ago? I don't know if this is more a question for mathematicians or physicists (or even philosophers), but what would be the difference between time having a beginning infinitely long ago and time having no beginning (apart from the obvious, one had a beginning and the other didn't)? How could we tell whether it has always existed or began infinitely long ago?
In other words, did time have a beginning or did it begin an infinitely long time ago? How could we tell?
It appears, from Ryder Rude's answer and the embedded link, that the problem is addressed in questions about the shape of the universe.

A: According to general relativity, spacetime is a four dimensional manifold. The most trivial topology of spacetime would be that of an infinite $R^4$ space. This sort of universe has no beginning. The geodesics can be extended in the past infinitely far. There are other interesting topologies too. You can read about them here in the Global Universe Structure section.
"Having a beginning infinitely long ago" is an oxymoron. There can be no beginning if something has existed for infinitely long.
About the space dimensions, it is hypothesized that they might be compact, like some 3D equivalent of the 2D surface of a cylinder or a torus. I don't know if a similar claim can be taken seriously for the time dimension. Nevertheless, if you hypothetically consider that time is like that, then time doesn't have a beginning but it didn't exist infinitely far back.


text:
Q: Vagrant + vbox on server 16.04 - how to get it working? I am trying to setup vagrant with virtual box on my ubuntu server 16.04.
Atm I think that the error I get is due to I miss a GUI.
0x80004005 is the error it spits out.
First I thought is was a permissons error but no, after a while I reinstalled all software packages. Still no luck.
Anyone has any suggestions what I am dong wrong?
This is my output:
vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
==> default: Forwarding ports...
default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
There was an error while executing `VBoxManage`, a CLI used by Vagrant for controlling VirtualBox. The command and stderr is shown below.
Command: ["startvm", "bd4ed1d2-8ddc-4faa-b993-9ab4526e80ab", "--type", "headless"]
Stderr: VBoxManage: error: The virtual machine 'admin_default_1496300210785_96841' has terminated unexpectedly during startup with exit code 1 (0x1)
VBoxManage: error: Details: code NS_ERROR_FAILURE (0x80004005), component MachineWrap, interface IMachine


text:
Q: Blueprism Spying Problems I am trying to spy a pop-up. But I couldn't recognize any element using any spy mode(Even I tried region mode)on the pop-up. It was throwing an error "Can't perform any spying operation". When I inspect the popup it was created using JQuery Event Handlers. Does anyone know how to solve the spying operation?

A: There are two reasons why this might be occurring:

*

*Your system's OLEACC.DLL file is not properly registered - More information is available here on how to resolve this, but the solution boils down to the following:

*

*Open a Command Prompt (CMD.EXE) with Administrator privileges

*Navigate within that to the location of your OLEACC.DLL file (usually 'C:\Windows\System32' directory)

*Run the following command to re-register the DLL file:
  regsvr32 OLEACC.DLL

*The window is created in the window hierarchy in such a way that it technically doesn't reside within the application you're attached to - Popups generated by certain web applications are not spyable using HTML mode. Instead, you'll have to create an entirely new object with new attaching logic to be able to spy this particular window. More information on this issue is available at the following resources:

*

*Blue Prism Knowledge Base Article - 'The window spied was not found in the model' error when spying

*Blue Prism Browser Automation Guide


text:
Q: Access GitVersion variable in azure pipeline for javascript build I've got the following pipeline:
steps:

- task: GitVersion@4

- script: |
    echo '##vso[task.setvariable variable=buildVersion]$(GitVersion.FullSemVer")'

- task: NodeTool@0
  inputs:
    versionSpec: '10.x'
  displayName: 'Install Node.js'

- task: Npm@1
  inputs:
    command: 'install'
    workingDir: '$(Build.SourcesDirectory)'
  displayName: "NPM Install"

- task: Npm@1
  inputs:
    command: 'custom'
    workingDir: '$(Build.SourcesDirectory)'
    customCommand: 'run-script build'
  displayName: "NPM Build"

- task: Npm@1
  inputs:
    command: 'custom'
    workingDir: '$(Build.SourcesDirectory)'
    customCommand: 'npm version $(buildVersion)'
  displayName: "Add version"

But I can't get access to the GitVersion output. I've tried with simply referencing $(GitVersion.FullSemVer) as well, but it gives the same result. The output from npm version is:
[command]C:\windows\system32\cmd.exe /D /S /C "C:\hostedtoolcache\windows\node\10.16.0\x64\npm.cmd npm version "$(GitVersion.FullSemVer)'""
Usage: npm <command>

If I write out the actual variables it looks fine.
Edit: It seems the problem at hand is that the version number is quoted, which npm doesn't like. So the question is more how to make that not happen.

A: You have an extra " in $(GitVersion.FullSemVer"), just remove it and it will be fine:
echo '##vso[task.setvariable variable=buildVersion]$(GitVersion.FullSemRev)'

For example:
- task: GitVersion@4

- script: 'echo ##vso[setvariable variable=buildVersion]$(GitVersion.FullSemRev)'

- script: 'echo $(buildVersion)'

Results:


text:
Q: Spark on Bluemix : !pip install --user shapely == Could not find library geos_c or load any of its variants !pip install --user shapely

results in
Collecting shapely
  Using cached Shapely-1.5.16.tar.gz
    Complete output from command python setup.py egg_info:
    Failed `CDLL(libgeos_c.so.1)`
    Failed `CDLL(libgeos_c.so)`
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/gpfs/global_fs01/sym_shared/YPProdSpark/user/s390-a2b719b24f799b-80b3d8dd92c1/notebook/tmp/pip-build-PYROZS/shapely/setup.py", line 38, in <module>
        from shapely._buildcfg import geos_version_string, geos_version, \
      File "shapely/_buildcfg.py", line 167, in <module>
        fallbacks=['libgeos_c.so.1', 'libgeos_c.so'])
      File "shapely/_buildcfg.py", line 161, in load_dll
        libname, fallbacks or []))
    OSError: Could not find library geos_c or load any of its variants ['libgeos_c.so.1', 'libgeos_c.so']

How can I overcome this issue on Bluemix Spark service where I don't have admin permission to install libraries.
There are lots of similar questions, but none of them are about the Bluemix Spark service.

A: This worked for me:
!wget http://download.osgeo.org/geos/geos-3.5.0.tar.bz2
!tar jxf geos-3.5.0.tar.bz2
!cd geos-3.5.0 && ./configure --prefix=$HOME/geos-bin && make && make install
!GEOS_CONFIG=$HOME/geos-bin/bin/geos-config pip install --user shapely
...
output omitted for brevity
...
Collecting shapely
  Using cached Shapely-1.5.16.tar.gz
Installing collected packages: shapely
  Running setup.py install for shapely ... [?25l- \ | / - \ | / - done
[?25hSuccessfully installed shapely-1.5.16


text:
Q: Setting registry values in HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System The Administrator user account I am running my compiled program in has Special (Full is allow'd, amongst all other permissions listed also allow'd, in the Permission Entry dialog) permission access to the above registry key.
I can alter the values in this key manually via regedit without issue.
However, when running the program in a Windows Vista Home Premium SP2 32-bit install, an attempt by this program to do a RegSetValue to the above registry value, is ACCESS DENIED.
Does anyone know why (Can provide a procmon trace, if helpful)?


text:
Q: Selenium Script executes very slow in IE10 in a 64 bit machine,while entering text in text boxes Selenium Script executes very slow in IE10 in a 64 bit machine, while entering text in text boxes, takes 3 to 4 secs between each character. Works fine in IE 10 in a 32 bit machine,also works fine in IE 9 in 64 bit machine. So the issue is specific with IE 10 in 64 bit OS.
Can someone help me out on this, also please share your views who has come across the same situation
http://code.google.com/p/selenium/issues/detail?id=5116

A: To be even more specific, the issue is unique to 64-bit IE 10 or higher. Running 32-bit IE, even on a 64-bit OS, does not exhibit the problem. Additionally, it should be noted that the vast majority of your users will be using 32-bit IE, even if they're using 64-bit Windows.
The root cause of the issue is clearly spelled out in one of the issue comments. It's an interaction problem between IE and the driver. Absent someone debugging the issue and submitting a patch/pull request, how, exactly, would you expect someone to be able to "help [you] out with this?"
As a workaround, you could try two things. You could turn off native events, or you could set the requireWindowFocus capability. Both of these use different methods to simulate user input. More information can be found in this blog post.


text:
Q: Looping an Python list while appending and iterating over fresh/new values I'm currently building an image pixel iterator, and I'm picking a point on the 2D grid and iterating outwards (up, down, left, right, etc...). As I was developing, I wrote a for-loop like this to see how it would function:
expanding = [1, 2]
# Expected functionality: continues to iterate "3" forever.
for expand in expanding:
  expanding.append(3)

I would expect this to continue in an infinite loop, with the iterating sequence looking like: 1, 2, 3, 3, 3, 3,... so forth. Though it only seems to close on 2 due to the structure of my outputs.
This part of my algorithm is tasked with breaking an image into its colour groups by picking random coordinates and expanding outwards, checking if the colour range is too far out of the parent colour, hence the requirement of a continuous iterator till it finalizes at nothing.
The use would be being able to simply append to the array for it to be iterated in the future, without needing to finish the array and remove specific elements before continuing, as a "live for loop".

A: I've just tried this myself by using the 'enumerate' method to wrap the list and below code does what you're asking:
my_list = [1,2]

for i, element in enumerate(my_list):
   my_list.append(3)

A: Here's a post talking about the reasons not to change the container you're iterating over, even though you can.
How about using a while loop and breaking out when your done instead:
my_list = [1,2]

while True:
    my_list.append(3)
    if #(check if out of range):
        break

A: You might want to look at another data structure for this, like a queue or stack.
As a very very poor example, there are graph algorithms that are not too far from the logic below:
seen = set()
stack = [1]
while stack:
    current = stack.pop()
    if current in seen or abs(current) > 5:
        continue
    seen.add(current)
    print 'Processed %s' % current
    stack.append(current + 1)
    stack.append(current - 1)

would provide
Processed 1
Processed 0
Processed -1
Processed -2
Processed -3
Processed -4
Processed -5
Processed 2
Processed 3
Processed 4
Processed 5


text:
Q: key map: combined keys to combined keys In short, I want to map Ctrl+H/L to Ctrl+Left/Right without autokey, and xbindkeys+xdotool/xvkbd does not work. Details are as follows:
I am now using autokey to achieve the mapping, it works very good, but in some application it fails to work because autokey is a high-level application. So I want to achieve a low-level key map.
Application such as xmodmap and xkb cannot do this because Ctrl+Left/Right is not a keysym. I have tried xbindkeys+xdotool. The following configuration script for xbindkeys does not work:(to simplify the question, I map the keys to 'a' instead Ctrl+Left/Right)
#.xbindkeys
"xdotool key a"
Control+h

I think it is because the pressed keys influence the execution of xdotool, because the following works:
#.xbindkeys
"xdotool key --clearmodifier a"
Control+h+Release

But I just do not want to trigger the command when I release the key, I want it to take into effect immediately when I press the key, so I change the configuration to:
#.xbindkeys
"xdotool keyup h; xdotool key --clearmodifier a"
Control+h

This configuration still works, but it cannot achieve autorepeat, that is when I press the key board without release for a long time, the command only execute one time. I have also tried xvkbd but is does now work:
#.xbindkeys
"xvkbd -text 'a'"
Control+h

Can anyone give me some help to achieve my key map?

A: Sorry, I underestimated the power of xkb, it can do much more than I thought. It is the most basic and overall keyboard manager of X-server. I have met my requirement using xkb. A very useful tutorial can be found at here on the Arch Linux Wiki, if you are also interested in how to do that. It is also welcomed to post on this topic.
Here are the details for my case (though I strongly recommend reading the linked page because it is very useful and not too long):
First, get your present keyboard layout:
xkbcomp $DISPLAY ~/.config.xkb

Then open the .config.xkb file with some editor, say vscode. You can see the file consists of 5 blocks(keycodes, types, compatibility, symbols, geometry):
xkb_keymap {
xkb_keycodes "..." {...};
xkb_types "..." {...};
xkb_compatibility "..." {...};
xkb_symbols "..." {...};
xkb_geometry "..." {...};
}

In the xkb_types block, add:
type "newType" {
    modifiers= Shift+Control;
    map[Shift]= Level2;
    map[Control]= Level3;
    map[Shift+Control]= Level3;
    level_name[Level1]= "Base";
    level_name[Level2]= "Shift";
    level_name[Level3]= "Control";
};

In the xkb_symbols block, find the following two sub-blocks:
key <AC06> {
    type= "ALPHABETIC",
    symbols[Group1]= [               h,               H ]
};
key <AC09> {
    type= "ALPHABETIC",
    symbols[Group1]= [               l,               L ]
};

And change these two sub-blocks to:
key <AC06> {
    type= "newType",
    symbols[Group1]= [               h,               H,            Left ],
    actions[Group1]= [      NoAction(),      NoAction(),   RedirectKey(keycode=<LEFT>) ]
};
key <AC09> {
    type= "newType",
    symbols[Group1]= [               l,               L,            Right ],
    actions[Group1]= [      NoAction(),      NoAction(),   RedirectKey(keycode=<RGHT>) ]
};

Finally, reset the keyboard layout to the modified one:
xkbcomp ~/.config.xkb $DISPLAY

Appendix
In case that one will want to know how to map to Left/Right instead of Control+Left/Right, I add the appendix.
The only change is to replace the sub-blocks in xkb_symbols block with
key <AC06> {
    type= "newType",
    symbols[Group1]= [               h,               H,            Left ],
    actions[Group1]= [      NoAction(),      NoAction(),   RedirectKey(keycode=<LEFT>, clearmods=Control) ]
}


text:
Q: Is it possible to capture the bitstream of post-interpreted code? (pre-execution) eg. speedup calls I make often I've wondered this many times and in many cases, and I like to learn so general or close-but-more needed answers are acceptable to me.
I'll get specific, to help explain the question. Please remember that this question is more about accelerating common interpreted language calls  (yes, exactly the same arguments), than it is about the specific programs I'm calling in this case.
Here we go:
Using i3WM I use i3lock-fancy to lock my workspace with a key-combo mapped to the command:
i3lock-fancy -p -f /usr/share/fonts/fantasque_mono.ttf
So here is why I think this is possible, though my google-fu has failed me:

*

*i3lock-fancy is a bash script, and bash is an interpreted language

*each time I run the command I call it with the same arguments

*

*Theoretically the interpreter is spitting out the same bitstream to be executed, right?

Please don't complain about portability, I understand it, the captured bitstream, would not be
For visual people:
When I call the above command > bash interpreter converts bash-code to byte-code > CPU executes byte-code
I want to:
execute command > bash interpreter converts to byte-code > save to file
so that I can effectively skip interpretation (since it's EXACTLY the same every time):
call file > CPU executes byte-code
What I tried:
Looking around on SO before asking the question lead me shc which is similar in some ways to what I'm asking for.
But this is not what shc is for (thanks @stefan)
is there a way to do this which is more like what I've described?
Simply put, is there a way to interpret bash, and save the result without actually running it?


text:
Q: Coded Webtests in Visual Studio: Testing first link on page I'm using visual studio's web testing capabilities. I've recorded a web test and converted it to a coded web test.
I'd like to test the first link on the page (well, in a section of the page, but for discussion's sake let's say the first link).
For example, let's say that I have a div on my page that has links to the 3 most recent posts.  When recording the web test, and I click on the first link, what's recorded is the request to that post. I'd like to test that the "3 most recent posts" function is working properly when I run my test later. The way it's currently being recorded will just test if a request to the particular post that I clicked on works.
In the coded web test, can I build a request by getting an element by id?
Thanks

A: I figured it out. It's using Validation and Extraction rules.

*

*http://msdn.microsoft.com/en-us/library/ms243183.aspx

*bb385904.aspx (I don't have enough reputation points yet to post more than one link ;-) )
You can do this either before or after you convert a webtest to a coded web test.


text:
Q: MobileFirst Platform adapter invocation fails in simulator I have a sample project "Invoking  adapter Procedures" in MobileFirst Platform. It receives feed and shows value while previewing in the MFP Console, but after  adding the iPad environment and running it in Xcode it does not fetch any feed and instead shows an error in the Xcode console:

Cannot fetch feed

and in the iOS Simulator:

service not available

Adapter code

<displayName>RSSReader</displayName>
<description>RSSReader</description>
<connectivity>
    <connectionPolicy xsi:type="http:HTTPConnectionPolicyType">
        <protocol>http</protocol>
        <domain>rss.cnn.com</domain>
        <port>80</port>
        <connectionTimeoutInMilliseconds>30000</connectionTimeoutInMilliseconds>
        <socketTimeoutInMilliseconds>30000</socketTimeoutInMilliseconds>
        <maxConcurrentConnectionsPerNode>50</maxConcurrentConnectionsPerNode>
        <!-- Following properties used by adapter's key manager for choosing specific certificate from key store
        <sslCertificateAlias></sslCertificateAlias>
        <sslCertificatePassword></sslCertificatePassword>
        -->
    </connectionPolicy>
</connectivity>

<procedure name="getFeeds"/>
<procedure name="getFeedsFiltered"/>

JS Code
var busyIndicator = null;

function wlCommonInit(){
busyIndicator = new WL.BusyIndicator();
loadFeeds();
}

function loadFeeds(){
busyIndicator.show();

/*
 * The REST API works with all adapters and external resources, and is supported on the following hybrid environments:
 * iOS, Android, Windows Phone 8, Windows 8.
 * If your application supports other hybrid environments, see the tutorial for MobileFirst 6.3.
 */
var resourceRequest = new WLResourceRequest("/adapters/RSSReader/getFeedsFiltered", WLResourceRequest.GET);
resourceRequest.setQueryParameter("params", "['technology']");
resourceRequest.send().then(
        loadFeedsSuccess,
        loadFeedsFailure
);
}

function loadFeedsSuccess(result){
WL.Logger.debug("Feed retrieve success");
busyIndicator.hide();
if (result.responseJSON.Items.length>0)
    displayFeeds(result.responseJSON.Items);
else
    loadFeedsFailure();
}

function loadFeedsFailure(result){
WL.Logger.error("Feed retrieve failure");
busyIndicator.hide();
WL.SimpleDialog.show("Engadget Reader", "Service not available. Try again later.",
        [{
            text : 'Reload',
            handler : WL.Client.reloadApp
        },
        {
            text: 'Close',
            handler : function() {}
        }]
    );
}

function displayFeeds(items){
var ul = $('#itemsList');
for (var i = 0; i < items.length; i++) {
    var li = $('<li/>').text(items[i].title);
    var pubDate = $('<div/>', {
        'class': 'pubDate'
    }).text(items[i].pubDate);

    li.append(pubDate);

    ul.append(li);
}

Xcode Console log

I had used the code give in the sample app.

A: I am unable to recreate this error.
Make sure these are the steps you've taken:

*

*Import into MobileFirst Platform Studio 7.0 the "Invoking adapter procedures in hybrid applications" sample project

*Right-click on the adapter folder and select Run As > Deploy MobileFirst Adapter

*Right-click on the project folder and select New > MobileFirst Environment, add iPad environment

*Right-click on the iPad folder and select Run As > Xcode project

*Click Run in Xcode

For me, by following the above steps I was able to successfully run the sample application in the iOS Simulator = the app was displayed and feeds were retrieved.


text:
Q: Prove that $\sum_{n=1}^\infty\frac{n}{n^2+1}$ is divergent
I'm trying to show that the series $\sum_{n=1}^\infty\frac{n}{n^2+1}$ is divergent.

I'm trying to use a comparison test to do so. To do so, I first can see that $\sum_{n=1}^\infty\frac{n}{n^2+1} \geq \sum_{n=1}^\infty\frac{n}{n^2+n} = \sum_{n=1}^\infty\frac{1}{n+1}$ And I can use a change of variable $k = n+1$, so show $\sum_{n=1}^\infty\frac{1}{n+1} = \sum_{k=2}^\infty\frac{1}{k} = \infty$. Then since $\sum_{n=1}^\infty\frac{n}{n^2+1} \geq \sum_{k=2}^\infty\frac{1}{k}$ it must be that $\sum_{k=2}^\infty\frac{1}{k}$ also diverges to infinity. Is this a valid way to show it?

A: Well, I will improve your solution by saying that
$$\frac{n}{n^2+\color\red1}\geq\frac{n}{n^2+\color\red{n^2}}=\frac{1}{2}\cdot\frac{1}{n}\qquad\forall n\in\Bbb N.$$
We know that series (called as harmomic series)
$$\sum_{n=1}^\infty\frac{1}{n}$$
is divergent and so multiplying it by $\frac{1}{2}$, it follows that the series $$\sum_{n=1}^\infty\bigg(\frac{1}{2}\cdot\frac{1}{n}\bigg)$$ is also divergent and hence, it follows from Comparison Test that the series
$$\sum_{n=1}^\infty\frac{n}{n^2+1}$$
 is divergent.


text:
Q: Cannot use assign-op operators with overloaded objects nor string offsets I have this portion of code and it gives me the error in the title.
I have a count $k from 1 to 5 for each table.
$myarray consists of at least 3 to 4 names.
The error occurs in the line with $qu .= ...
What i tried so far: changing the variablename $i to $v{$i} in the $qu .= line.
So is there any possibility to iterate the query?  So that it has as many ANDs in the WHERE clause as the count of the array is?
while ($k<=5) {
  $queryname = "SELECT Name FROM description";
  $qname = mysql_query($queryname,$link);

  while ($reihe = mysql_fetch_object($qname)) {
    {
      $unse = unserialize($reihe->Name);
      {
        foreach ($unse as $j=>$h)
          foreach ($h as $m) {
            $myarray = preg_split('/ |\s| /',$m);
            {
              echo "
";
              $array_empty = $myarray;
              $empty_elements = array("");
              $myarray = array_diff($array_empty,$empty_elements);
              var_dump($myarray);
              for ($i=1; $i<=count($myarray); $i++) {
                $v{$i} = $myarray[$i];
                echo $v{$i};
                $esc{$i} = strtolower(mysql_escape_string($v{$i}));
                echo "
" . $esc{$i} . "
";
                $qu = "SELECT * FROM `table ID=$k` WHERE";
                $qu{$i} .= "AND `table ID=$k`.`name` LIKE '%$esc{$i}%'";
              }
            }
          }
        {
          $test_a = mysql_query($qu,$link) or die (mysql_error());
          echo "
";
          var_dump($test_a);
          for ($x=0; $x<mysql_num_rows($test_a); $x++) {
            $row = mysql_result($test_a,$x,'data1');
            $namee = mysql_result($test_a,$x,'data2');
            echo 'data1' . $row . '
';
            echo 'data2' . $namee . '
';
          }
        }
      }
    }
  }
  $k++;
}

A: You appear to have misunderstood some basic PHP syntax.
As mentioned in the manual:

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.

Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose.

Therefore your use of curly braces throughout your code (except for those defining the scope of the for control structure) are wholly erroneous and do not accomplish what you intend.
Secondly, from your code it appears that you are storing relational data in serialised PHP objects; this defeats many of the benefits of using an RDBMS like MySQL.  Unless you have compelling reasons for doing otherwise, you should probably store your PHP objects in a normalised form.  For example, rather than each description record having a Name field that contains a serialised PHP object whose properties are arrays that hold imploded strings of names, just store each such name in a new descriptionNames table that references the related record in the description table:
CREATE TABLE descriptionNames (
  descriptionID INT NOT NULL,
  name VARCHAR(50),
  PRIMARY KEY (descriptionId, name),
  FOREIGN KEY (descriptionId) REFERENCES description (descriptionId)
);

It also appears that you have five (schematically) identical tables named Table ID=1, Table ID=2, etc.?  If so, you should probably combine your five tables into one, with a column (if so desired) to indicate from which table the record originated; I would also suggest changing your table names so that they avoid using special characters like whitespace and = as they will likely only cause trouble and confusion further down the road if you forget to properly quote them.  For example:
ALTER TABLE `Table ID=1`
  RENAME TO CombiTable,
  ADD COLUMN FromTableID TINYINT NOT NULL;

UPDATE CombiTable SET FromTableID = 1;

INSERT INTO CombiTable
  SELECT *, 2 FROM `Table ID=2` UNION ALL
  SELECT *, 3 FROM `Table ID=3` UNION ALL
  SELECT *, 4 FROM `Table ID=4` UNION ALL
  SELECT *, 5 FROM `Table ID=5`;

SELECT * FROM CombiTable;  -- check everything is okay

DROP TABLE `Table ID=2`, `Table ID=3`, `Table ID=4`, `Table ID=5`;

In any event, you shouldn't use the ancient mysql_* functions. They are no longer maintained and the community has begun the deprecation process. Instead you should learn about prepared statements and use either the PDO abstraction layer or else the improved MySQLi extension.
If you need to maintain your existing data structure, with PDO you could do something like:
$dbh = new PDO("mysql:dbname=$dbname;charset=utf8", $user, $password);

$qry = $dbh->query("SELECT Name FROM description");
$myarray = array();
while ($reihe = $dbh->fetchColumn())
  foreach (unserialize($reihe) as $h)
    foreach ($h as $m)
      array_merge($myarray, preg_split("/\s+/", $m, -1, PREG_SPLIT_NO_EMPTY));

for ($k = 1; $k <= 5; $k++) {
  $qry = $dbh->prepare("SELECT * FROM `table ID=$k` WHERE " . implode(" OR ",
    array_pad(array(), count($myarray), "name LIKE CONCAT('%', ?, '%')")
  ));

  $qry->execute($myarray);
  while($row = $qry->fetch()) {
    echo "data1:$row[data1]
";
    echo "data2:$row[data2]
";
  }
}

However, using my proposed new data structure, you would only need do:
$dbh = new PDO("mysql:dbname=$dbname;charset=utf8", $user, $password);

$qry = $dbh->query("
  SELECT   *
  FROM     CombiTable JOIN descriptionNames USING (name)
  WHERE    FromTableID BETWEEN 1 AND 5   -- in case you have others?
  ORDER BY FromTableID
");

while ($row = $qry->fetch()) {
  echo "data1:$row[data1]
";
  echo "data2:$row[data2]
";
}


text:
Q: How to load and merge multiple .csv files in r? So I'm very new at R and right now I'm trying to load multiple .csv files (~60 or so) and then merge them together. They all have similar columns and their files are named like this: dem_file_30, dem_file_31.
I've been trying to use scripts online but keep getting some errors. I'm sure I can do it by hand but that would be really tedious.
Example:
file_list <- list.files("/home/sjclark/demographics/")
list_of_files <- lapply(file_list, read.csv)
m1 <- merge_all(list_of_files, all=TRUE)
Error: merge_all doesn't exist

This one seems to read them into R, but then I'm not how to do after that... help?
setwd("/home/sjclark/demographics/")
filenames <- list.files(full.names=TRUE)
All <- lapply(filenames,function(i){
read.csv(i, header=TRUE)
})

A: It appears as if you might be trying to use the nice function shared on R-bloggers (credit to Tony Cookson):
multMerge = function(mypath){
  filenames = list.files(path = mypath, full.names = TRUE)
  datalist = lapply(filenames,
                    function(x){read.csv(file = x,
                                         header = TRUE,
                                         stringsAsFactors = FALSE)})
  Reduce(function(x,y) {merge(x, y, all = TRUE)}, datalist)
}

Or perhaps you have pieced things together from difference sources? In any event, merge is the crucial base R function that you were missing. merge_all doesn't exist in any package.
Since you're new to R (and maybe all programming) it's worth noting that you'll need to define this function before you use it. Once you've done that you can call it like any other function:
my_data <- multMerge("/home/sjclark/demographics/")

A: I have just been doing a very similar task and was also wondering if there is a faster/better way to do it using dplyr and bind_rows.
My code for this task is uses ldply from plyr:
library(plyr)
filenames <- list.files(path = "mypath", pattern = "*", full.names=TRUE)
import.list <- ldply(filenames, read.csv)

Hope that helps
Rory


text:
Q: ValueError: Cannot assign "2": "Model.field" must be a "Model" instance I have a registration system that works on otp.
I have a custom user model
class User(AbstractUser):
  password = models.CharField(max_length=128, blank=True, null=True)
  email = models.EmailField(max_length=254, unique=True)
  dial_code_id = models.CharField(max_length=100)
  mobile_number = models.CharField(max_length=100, blank=True, null=True)
  username = models.CharField(max_length=150, unique=True, blank=True, null=True)
  is_resource = models.BooleanField(default=False)
  is_customer = models.BooleanField(default=False)
  is_active = models.BooleanField(default=True)
  skills = models.ManyToManyField(Skills)

  class Meta:
      db_table = "my_user"

  def __str__(self):
      return self.mobile_number

I have created an 'otp' model to save otp.
class Otp(models.Model):
  user = models.ForeignKey(User, on_delete=models.CASCADE)
  otp = models.IntegerField()
  created_on = models.DateTimeField(default=django.utils.timezone.now)

  class Meta:
      db_table = "otp"

My views looks like this
class UserCreateResponseModelViewSet(viewsets.ModelViewSet):
  def create(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    if serializer.is_valid():
        serializer.save()

        custom_data = {
            "status": True,
            "message": 'Successfully registered your account.',
            "data": serializer.data
        }
        generate_otp(serializer.data['id'])
        return Response(custom_data, status=status.HTTP_201_CREATED)
    else:
        custom_data = {
            "status": False,
            "message": serializer.errors,
        }
        return Response(custom_data, status=status.HTTP_200_OK)

class UserCreateViewSet(UserCreateResponseModelViewSet):
  queryset = User.objects.all()
  serializer_class = UserSerializer

I have a function to generate and save otp
def generate_otp(user_id):
  try:
    otp_obj = Otp.objects.get(user_id=user_id)
  except Otp.DoesNotExist:
    otp_obj = None
  if otp_obj is None:
    otp = random.randrange(1000, 9999)
    otp_obj = Otp(user=user_id, otp=otp)
    otp_obj.save()

Serializer looks like
class UserSerializer(serializers.ModelSerializer):
  mobile_number = serializers.CharField(
    required=True,
    validators=[UniqueValidator(queryset=User.objects.all())]
  )

  class Meta:
    model = User
    fields = ['id', 'first_name', 'last_name', 'email', 'dial_code_id','mobile_number', 'is_resource', 'is_customer']

The user is being registered successfully, but when it comes to saving otp in 'generate_otp()' I'm getting an error like
raise ValueError(ValueError: Cannot assign "2": "Otp.user" must be a "User" instance.

How can I overcome this?
Is this the right way to do it?

A: It looks like the problem is here:
otp_obj = Otp(user=user_id, otp=otp)

you're assigning an id (int) to the user field. not the user_id field


text:
Q: Split Encoder and Decoder part in AUTOENCODER with skip connections - KERAS I am trying to implement AUTOENCODER with skip connections and split the Encoder and Decoder parts. So, I can work on latent space and Decoder part.
Below is the architecture in keras I used:
## ENCODER
inputs_encoder = Input(shape = (256, 642))
C1 = Conv1D(filters=512, kernel_size=5,  padding='same', activation='relu', name='C1')(inputs_encoder)
D1 = AvgPool1D(pool_size=2)(C1)
C2 = Conv1D(filters=256, kernel_size=5,  padding='same', activation='relu', name='C2')(D1)
D2 = AvgPool1D(pool_size=2)(C2)
C3 = Conv1D(filters=128, kernel_size=5,  padding='same', activation='relu', name='C3')(D2)
D3 = AvgPool1D(pool_size=2)(C3)
C4 = Conv1D(filters=64,  kernel_size=5,  padding='same', activation='relu', name='C4')(D3)
F = Flatten()(C4)
outputs = Dense(32, activation="relu")(F)
UNet_encoder = Model(inputs_encoder, [outputs, C1, C2, C3, C4], name='UNet_encoder')

## DECODER
inputs_decoder = Input(shape=(32))
C1             = Input(shape=(256, 512))
C2             = Input(shape=(128, 256))
C3             = Input(shape=(64, 128))
C4             = Input(shape=(32, 64))
X = Dense(2048, activation='relu')(inputs_decoder)
X = Reshape(target_shape=(32, 64))(X)
C5 = Conv1D(filters=64, kernel_size=5,  padding='same', activation='relu', name='C5')(X)
C5 = Concatenate(axis=-1)([C4, C5])
U  = UpSampling1D(size = 2)(C5)
C6 = Conv1D(filters=128, kernel_size=5,  padding='same', activation='relu', name='C6')(U)
C6 = Concatenate(axis=-1)([C3, C6])
U  = UpSampling1D(size = 2)(C6)
C7 = Conv1D(filters=128, kernel_size=5,  padding='same', activation='relu', name='C7')(U)
C7 = Concatenate(axis=-1)([C2, C7])
U  = UpSampling1D(size = 2)(C7)
C8 = Conv1D(filters=128, kernel_size=5,  padding='same', activation='relu', name='C8')(U)
C8 = Concatenate(axis=-1)([C1, C8])
outputs = Conv1D(filters=642, kernel_size=5,  padding='same', activation='linear')(C8)
UNet_decoder = Model([inputs_decoder, C1, C2, C3, C4], outputs, name='UNet_decoder')

## AUTOENCODER with skip conncetions
Autoencoder_input = Input(shape = (256,642))
encoder           = UNet_encoder(Autoencoder_input)
decoder           = UNet_decoder(encoder)
Autoencoder = Model(Autoencoder_input, decoder)
Autoencoder.compile(optimizer=keras.optimizers.Adam(learning_rate=0.001), loss='mse')

Now, I want to make predictions for latent size input (i.e. 32 here). But Decoder part asks for skip connections C1, C2, C3 and C4. How to get rid of this issue?
decoder_input = (100,32) # samples, latent_size
pred_results  = UNet_decoder.predict([decoder_input, C1, C2, C3, C4])

But I am getting followint error:
ValueError: Data cardinality is ambiguous:
  x sizes: 100, 2000, 2000, 2000, 2000
Please provide data which shares the same first dimension.

Here 2000 are number of samples used in training.


text:
Q: How to Add Comma seperated Object types into NgFor loop? I want to bind the currency codes and Values seperatly
"rates": {
        "USD": 1,
        "AED": 3.672057,
        "ARS": 56.01249,
        "AUD": 1.46368,
        "BGN": 1.77167,
        "BRL": 4.087588,
        "BSD": 1,
        "CAD": 1.320503,
        "CHF": 0.987394,
        "CLP": 716.341326,
        "CNY": 7.13045,
        "COP": 3416.761905,
        "CZK": 23.407844,
        "DKK": 6.757576,
        "DOP": 51.214847,
        "EGP": 16.42298,
        "EUR": 0.906246,
        "FJD": 2.190098,
        "GBP": 0.812305,
        "GTQ": 7.682227,
        "HKD": 7.838661,
        "HRK": 6.706097,
        "HUF": 298.791592,
        "IDR": 14146.297846,
        "ILS": 3.517842,
        "INR": 71.751368,
        "ISK": 126.170061,
        "JPY": 106.936393,
        "KRW": 1194.541725,
        "KZT": 387.848649,
        "MXN": 19.613284,
        "MYR": 4.184189,
        "NOK": 8.99096,
        "NZD": 1.561619,
        "PAB": 1,
        "PEN": 3.352305,
        "PHP": 51.899054,
        "PKR": 156.32244,
        "PLN": 3.930302,
        "PYG": 6522.909091,
        "RON": 4.285713,
        "RUB": 65.941596,
        "SAR": 3.75059,
        "SEK": 9.657741,
        "SGD": 1.382595,
        "THB": 30.646268,
        "TRY": 5.701489,
        "TWD": 31.23947,
        "UAH": 24.982101,
        "UYU": 36.570846,
        "VND": 23112.280702,
        "ZAR": 14.803694
    }

this is on my view :
 {{cur}}

error :

Cannot find a differ supporting object '[object Object]' of type
  'object'. NgFor only supports binding to Iterables such as Arrays.

A: you can try to use keyvalue pipe:

{{cur.key}}:{{cur.value}}

demo

A: To use ngFor, you need to conver your Object to an array of Object. Do it as follows on the .TS

let curr = {
  "rates": {
    "USD": 1,
    "AED": 3.672057,
    "ARS": 56.01249,
    "AUD": 1.46368,
    "BGN": 1.77167,
    "BRL": 4.087588,
    "BSD": 1,
    "CAD": 1.320503,
    "CHF": 0.987394,
    "CLP": 716.341326,
    "CNY": 7.13045,
    "COP": 3416.761905,
    "CZK": 23.407844,
    "DKK": 6.757576,
    "DOP": 51.214847,
    "EGP": 16.42298,
    "EUR": 0.906246,
    "FJD": 2.190098,
    "GBP": 0.812305,
    "GTQ": 7.682227,
    "HKD": 7.838661,
    "HRK": 6.706097,
    "HUF": 298.791592,
    "IDR": 14146.297846,
    "ILS": 3.517842,
    "INR": 71.751368,
    "ISK": 126.170061,
    "JPY": 106.936393,
    "KRW": 1194.541725,
    "KZT": 387.848649,
    "MXN": 19.613284,
    "MYR": 4.184189,
    "NOK": 8.99096,
    "NZD": 1.561619,
    "PAB": 1,
    "PEN": 3.352305,
    "PHP": 51.899054,
    "PKR": 156.32244,
    "PLN": 3.930302,
    "PYG": 6522.909091,
    "RON": 4.285713,
    "RUB": 65.941596,
    "SAR": 3.75059,
    "SEK": 9.657741,
    "SGD": 1.382595,
    "THB": 30.646268,
    "TRY": 5.701489,
    "TWD": 31.23947,
    "UAH": 24.982101,
    "UYU": 36.570846,
    "VND": 23112.280702,
    "ZAR": 14.803694
  }
};

const mapped = Object.keys(curr.rates).map(key => ({type: key, value: curr.rates[key]}));

console.log(mapped);

A: What I have understand from you is that you are trying to show all data in json by iterating with ngFor
I suggest you to parse that json in code behind and iterate in "result" object
like :

*

*parse your json in your code behind

*create getter for result attribute keys
get Resultkeys(){ return Object.keys(result); }

*create function that gets value of a given key
getResultKeyValue(key){ return result[key]; }

*iterate in ResultKeys in your html code usign ngFor

*display {{getResultKeyValue(key)}}

A: Use Object.entries
Object.entries(obj) – returns an array of [key, value] pairs.

var cur = { "USD": 1, "AED": 3.672057, "ARS": 56.01249, "AUD": 1.46368, "BGN": 1.77167, "BRL": 4.087588, "BSD": 1, "CAD": 1.320503, "CHF": 0.987394, "CLP": 716.341326, "CNY": 7.13045, "COP": 3416.761905, "CZK": 23.407844, "DKK": 6.757576, "DOP": 51.214847, "EGP": 16.42298, "EUR": 0.906246, "FJD": 2.190098, "GBP": 0.812305, "GTQ": 7.682227, "HKD": 7.838661, "HRK": 6.706097, "HUF": 298.791592, "IDR": 14146.297846, "ILS": 3.517842, "INR": 71.751368, "ISK": 126.170061, "JPY": 106.936393, "KRW": 1194.541725, "KZT": 387.848649, "MXN": 19.613284, "MYR": 4.184189, "NOK": 8.99096, "NZD": 1.561619, "PAB": 1, "PEN": 3.352305, "PHP": 51.899054, "PKR": 156.32244, "PLN": 3.930302, "PYG": 6522.909091, "RON": 4.285713, "RUB": 65.941596, "SAR": 3.75059, "SEK": 9.657741, "SGD": 1.382595, "THB": 30.646268, "TRY": 5.701489, "TWD": 31.23947, "UAH": 24.982101, "UYU": 36.570846, "VND": 23112.280702, "ZAR": 14.803694 }

Object.entries(cur).forEach(obj => console.log(`${obj[0]} ${obj[1]}`));


text:
Q: Misunderstanding the proper use of Input Text value Property function I am working my way through a small learning exercise in Javascript that gets the value of text in a text area and replaces the single quotes with double quotes as indicated by the regex.   What I am confused about is why I can't/don't/ shouldn't include the "value" property" in the argument passed to the replaceQuote() function.
In the code below i pass document.form1.textarea1, and all works well.   If I modify the function to pass the argument as document.form1.textarea1.value, the code doesn't work.
My question is this, what am I clearly misunderstanding about value property and how it functions.   I am pretty sure it's something very fundamental that I am just too obtuse to "get"
This version of the function works
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
 <script type="text/javascript">
     function replaceQuote(textarea) {
         var myText = textarea.value;
         var myRegExp = /\B'|'\B/g;
         myText = myText.replace(myRegExp,'"')
         textarea.value = myText;
     }

 </script>
</head>
<body>
<form name = "form1">
    <textarea rows="20" cols="40" name="textarea1">
        'Hello World' said Mr O'Connerly.
He then said 'My Name is O'Connerly, yes that's right, O'Connerly'.
    </textarea>
    <input type="button" value="replace single quote" onclick="replaceQuote(document.form1.textarea1)">
</form>

</body>
</html>

This version of the function does not work.  Function is modified to accept replaceQuote(document.form1.textarea1.value)
<!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
     <script type="text/javascript">
         function replaceQuote(textarea) {
             var myText = textarea;
             var myRegExp = /\B'|'\B/g;
             myText = myText.replace(myRegExp,'"')
             textarea = myText;
         }

     </script>
    </head>
    <body>
    <form name = "form1">
        <textarea rows="20" cols="40" name="textarea1">
            'Hello World' said Mr O'Connerly.
    He then said 'My Name is O'Connerly, yes that's right, O'Connerly'.
        </textarea>
        <input type="button" value="replace single quote" onclick="replaceQuote(document.form1.textarea1.value)">
    </form>

    </body>
    </html>

A: In the first version, a reference to the actual textarea object is being passed in.  That means you can both read and write the .value property of the textarea.
In the second version, just the value of the .value property is being passed in - ie the actual contents of the text area.  Within the function, it's just a local variable containing text, so assigning myText to it has no effect outside of the function.

A: The reason the second version of your code does not work is because in the replaceQuotes function when you wrote
textarea = myText;
textarea is a local variable that has the value of the text in the textarea.


text:
Q: Separating list into divs to show only one at a time My question is on seperating a list of Questions into seperate divs (using javascript/html/c#). How the program works at the moment is there is a main view for the quiz, which displays the content section and once completed hides that partial and shows the quiz partial view.
Currently this displays all the questions in order formatted like so
(imagine a quiz with only 2 questions)
Q#1
-(multiple choice)
-
Previousbtn      NextBtn
Q#2
-(multiple choice)
-
Previousbtn      Finish
What i'm trying to do is display only one question at a time by (presumably) seperating each question into its own div and showing/hiding them as needed (on btn click of Next or previous).
I've hit a wall yesterday afternoon and today so anygeneral guidance would be appreciated.
Thanks

A: This is just a sample code, you can get some knowledge and add your extra logic to achieve

$(function(){
 var index = 0;
 $(".quiz-container").addClass("inactive");
 $(".quiz-container:first").addClass("active");
 $("#next").on("click", function(){
  index++;
  $(".quiz-container.active").removeClass("active").addClass("inactive");
  $(".quiz-container").eq(index).removeClass("inactive").addClass(active);
 })
 $("#prev").on("click", function(){
  index--;
  $(".quiz-container.active").removeClass("active").addClass("inactive");
  $(".quiz-container").eq(index).removeClass("inactive").addClass(active);
 })
});
.active {
 display: block;
}
.inactive {
 display: none;
}

Q: Question?

choice1

choice2

choice3

choice4

Q: Question?

choice1

choice2

choice3

choice4

Q: Question?

choice1

choice2

choice3

choice4

A: For the Previous Next functions you can use the same as Aren, but to answer the question posted, about separating a list use the following
You would have the same script as mentioned

    var index = 0;
    var n = $("div.quiz-container").length;
    var a = n - 1

     $(".quiz-container:first").addClass("active").show();
    if (index == 0) {
      $("#prev").prop("disabled", true);
    }
    $("#next").on("click", function() {
      index++;
      $(".quiz-container.active").removeClass('active').hide();
      $(".quiz-container").eq(index).addClass('active').show();
      if (index == 0) {
        $("#prev").prop("disabled", true);
      } else if (index != 0) {
        $("#prev").prop("disabled", false);
      }
      if (index != a) {
        $("#next").prop("disabled", false);
      } else if (index == a) {
        $("#next").prop("disabled", true);
      }
    });
    $("#prev").on("click", function() {
      index--;
      $(".quiz-container.active").removeClass('active').hide();
      $(".quiz-container").eq(index).addClass('active').show();
      if (index == 0) {
        $("#prev").prop("disabled", true);
      } else if (index != 0) {
        $("#prev").prop("disabled", false);
      }
      if (index != a) {
        $("#next").prop("disabled", false);
      }
    })

Q: Question 1?

choice1

choice2

choice3

choice4

Q: Question 2?

choice1

choice2

choice3

choice4

Q: Question 3?

choice1

choice2

choice3

choice4

<button id="prev">Previous</button>
<button id="next">Next</button>

But in your view's foreach loop you would have:
foreach (var question in model.quiz) {

@question.QuestionTitle

           foreach (var answer in question.Answers) {

@answer

           }

 }

<button id="next">Next</button>
<button id="prev">Previous</button>

So you can have a varied amount of answers and varied amount of question. Hope this helps.
P.S you need to edit the code according to your model


text:
Q: looking for hosted vcs for visual studio I travel a bit and I'm looking for a hosted vcs with good support for Visual Studio.  My projects aren't open source so I need security as well.  Any recommendations or suggestions?

A: Assuming VCS means Version Control System in this context, try www.codesion.com? They have a free plan or you can pay... if security is an issue I'd probably prefer a professional place.


text:
Q: Toggle post expansion in the mod queue Posts in the mod queue are shown in an abbreviated form, which is great for keeping the list as short as possible.  If a mod needs to view the post to make a judgement, they can click on the post's abbreviated body to expand it with the full content (sans tags).
The problem is that, once expanded, you cannot collapse it.  Most of the time its fine, as the post isn't that long.
But sometimes you get a real long one.  And you have to scroll down to find the mod tools at the bottom of the post.  And then, once the post is dealt with, you have to hunt back up the queue to find the place where you left off.  It can be very annoying.
Can we simply have the ability to toggle expansion of the post?  As I click on the abbreviated post to expand it, can I also click on the expanded post to hide all but the first four or five lines?

A: Sure, I can see that it would be nice to hide away some huge mammoth of a post without reloading. Next deploy.