text:
Q: How do I trace an intermittent crash that occurs only under the debugger, but is not caught by it? I have an odd intermittent crash that only occurs under some circumstances that I am having trouble solving, and I'm seeking SO's advice for how to tackle it.
The bug
At apparently random points, Windows shows the "[App] has stopped working" dialog.  It is an APPCRASH in ntdll.dll, exception code 4000001f, exception offset 000a2562.  Here's where it gets tricky: this only occurs when running the application under the debugger.  However, the debugger does not catch this exception, and at the point where Windows shows this dialog, the IDE is not responding.  This bug does not occur when running normally, i.e. not within the IDE debugger.

I can't reproduce it outside the debugger, so I can't run the program and attach when it's already crashed.  I can't pause execution when Windows shows this dialog, since the IDE isn't responding.  I can manually trace through lines of code to see where it occurs.  There are several, and where it occurs is apparently random.  For a while it occurred when showing a window (or new form), for a while when creating a thread.
Edit: I have tracked it down to the IDE: if I pause on a breakpoint and click the Thread Status tab, the program will crash immediately with the above dialog even though it is, theoretically, paused.  In this situation, the IDE remains responsive.  This is really weird.
More information
I have just moved my development environment to VMWare Fusion.  The bug also occurs running a build from my old (native Windows) computer on my new computer; it did not occur with the same EXE file on that old computer.  This makes me wonder if it is related to Fusion or something in my new setup.
I am running:

*

*Windows 7 Pro x64 on WMWare Fusion 3.1.3 on OSX Lion 10.7.1, all fully updated.  Fusion is running in "Full screen" mode on one of my screens.

*A colleague running Windows 7 natively (not in a VM) does not encounter this issue.  Nor did I on my old Vista computer.

*Embarcadero RAD Studio 2010, fully updated (I hope; there are about five updates and getting them all in order is tricky.)  I have DDevExtensions 2.4.1 installed, and the latest IDE Fix Pack too: uninstalling both these has no effect.

*The application is written mostly in C++, with snippets of Delphi.  It is 32-bit.

*We use EurekaLog, but the exception is not caught by it either.  (Normally, an exception would be caught first by the debugger, then by EurekaLog.)

*Running a debug build (no EurekaLog, extra debug info etc, debug DCUs set to true) also reproduces it.  However, the "Debug DCUs" option on The Delphi Linking page of the C++Builder project settings dialog seems to have no effect - I can't step into the VCL code and find the line that actually triggers the error.

*Codeguard (which detects memory access errors, double frees, access in freed memory, buffer overruns, etc) reports nothing.

A: This has all the hallmarks of a memory corruption. It only appears when you run under a one particular environment, and occurs at a different location each time. Both classic symptoms.
The best way I know to debug this is to download the full FastMM and run with full debugging options enabled.
If that doesn't help then you are reduced to removing parts of code, one by one, until you can isolate the problem.
Another problem I have seen in D2010 is a problem when mixing local class definitions (i.e. class inside class) with generics. The code generated is fine but the debug DCUs are wrong and when stepping through the code the debugger jumps to the wrong file and dies shortly after. You don't seem to have quite the same problem but there are similarities in the IDE deaths.
Finally I would advise you to suspect your own code rather than VMware. It's always tempting to blame something else but in my experience, whenever I have done so, it was always my code in the end!

A: I hit a quite similar problem. I've also been developing a .dll and when I've set a breakpoint anywhere in my code, Delphi stopped at the source code line and the host-application crashed immediately.
Closing the "Thread Status Window" in debug layout "fixed" the problem.
I'm working on Windows 7 64-bit and Delphi XE3.

A: 4000001F is STATUS_WX86_BREAKPOINT
In other words, it is INT 3, which was not handled by IDE.
Since it is raised in NTDLL - I would guess that this is indication of memory corruption in system heap. Remember, some Windows code would switch to debugger version when running under debugger. That's why you can not reproduce this when application is running as standalone outside of the debugger - because breakpoint is not generated.
You may try FastMM in full debug mode, but I do not think that it will help you. The corruption does not happen in your memory, it happens in system memory. Yes, perhaps memory allocation scheme will be changed - and your corruption will reveal itself in your code/memory... may be. Try use top-down allocations, try use SafeMM...
Another possible approach would be using Application Verifier.
See also:

*

*Windows has generated a breakpoint

*C++ error on Ms Visual Studio: "Windows has triggered a breakpoint in javaw.exe"

*http://blogs.msdn.com/b/oldnewthing/archive/2012/01/25/10260334.aspx

*http://blogs.msdn.com/b/oldnewthing/archive/2013/12/27/10484882.aspx

A: Check the  The projects dsk file and make sure it does not have a reference pointing to the wrong unit.  The fix is to open the dsk in an editor and change the file location to the correct location.


text:
Q: Unexpected identifier with ejs Lately I feel like I have been fighting with the Ejs templating engine. I am getting and unexpected identifier that I cant seem to figure out why that's the case.
Error
SyntaxError: path\views\main.ejs:34

which is the following line of code from main.ejs
<%- include('partials/comments'); %>

Then the error message continues as follows,
Unexpected identifier in path\views\partials\comments.ejs while compiling ejs

Relevant lines from main.ejs

    <%- include('partials/stats'); %>
    <%- include('partials/popular'); %>
    <%- include('partials/comments'); %>

partials/comments.ejs

        <% for(int i = 0; i < sidebar.comments.length; i++){ %>

                <a class="pull-left" href="/images/<%- sidebar.comments[i].image.uniqueId %>">
                    <img class="media-object" width="45" height="45" src="/public/upload/ <%- sidebar.comments[i].image.filename  %>">

<%- sidebar.comments[i].comment %>

                     <%- sidebar.comments[i].name %>
                     <%- timeago(sidebar.comments[i].timestamp) %>

        <% } %>

What causes this error and how do I solve it?
I Think that the problem is with ejs and not the Viewmodel being sent to the comments.ejs template. Just in case, I have listed these functions below.
What the viewModel looks like
const ViewModel = {
    image:{
        uniqueId: 1,
        title: 'Sample Image 1',
        description: 'This is a sample.',
        filename: 'sample1.jpg',
        Views: 0,
        likes: 0,
        timestamp: Date.now()
    },
    comments: [
        {
            image_id: 1,
            email: 'test@testing.com',
            name: 'Test Tester',
            gravatar: 'http://lorempixel.com/75/75/animals/1',
            comment: 'This is a test comment...',
            timestamp: Date.now()
        }, {
            image_id: 1,
            email: 'test@testing.com',
            name: 'Test Tester',
            gravatar: 'http://lorempixel.com/75/75/animals/2',
            comment: 'Another followup comment!',
            timestamp: Date.now()
        }
    ],
    state:'Images',
};

image.js
const sidebar = require('../helpers/sidebar');
const path = require('path');

module.exports = {
    index(req, res) {
        sidebar(ViewModel, (ViewModel) => {
            res.render('main', ViewModel);
        });
    }
}

sidebar
const Stats = require('./stats')
const Images = require('./images')
const Comments = require('./comments');

module.exports = (ViewModel, callback) => {
    ViewModel.sidebar = {
        stats: Stats(),
        popular: Images.popular(),
        comments: Comments.newest()
    };
    callback(ViewModel);
};

comments.js
module.exports = {
    newest() {
        let comments = [
            {
                image_id: 1,
                email: 'test@testing.com',
                name: 'Test Tester',
                gravatar: 'http://lorempixel.com/75/75/animals/1',
                comment: 'This is a test comment...',
                timestamp: Date.now(),
                image: {
                    uniqueId: 1,
                    title: 'Sample Image 1',
                    description: '',
                    filename: 'sample1.jpg',
                    Views: 0,
                    likes: 0,
                    timestamp: Date.now
                }
            },
            {
                image_id: 1,
                email: 'test@testing.com',
                name: 'Test Tester ',
                gravatar: 'http: //lorempixel.com/75/75/animals/2',
                comment: 'Another followup comment!',
                timestamp: Date.now(),
                image: {
                     uniqueId: 1,
                     title: 'Sample Image 1',
                     description: '',
                     filename: 'sample1.jpg',
                     Views: 0,
                     likes: 0,
                     timestamp: Date.now
                }
            }
        ];
        return comments;
    }
};

A: The error message:
Unexpected identifier in partials/comments.ejs while compiling ejs

Tells us that the error is in comments.ejs, and sure enough:
<% for(int i = 0; i < sidebar.comments.length; i++){ %>

Specifically, int should be let or var.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UseMethod("type") error; no applicable method for 'type" applied to an object of class "c('double', 'numeric')" In a dataframe, I have a column that has numeric values and some mixed in character data for some rows. I want to remove all rows with the character data and keep those rows with a number value. The df I have is 6 million rows, so I simply made a small object to try to solve my issue and then implement at a larger scale.
Here is what I did:
a <- c("fruit", "love", 53)

b <- str_replace_all("^[:alpha:]", 0)

Reading answers to other UseMethod errors on here (about factors), I tried to change "a" to as.character(a) and attempt "b" again. But, I get the same error. I'm trying to simply make any alphabetic value into the number zero and I'm fairly new at all this.

A: There are several issues here, even in these two lines of code.  First, a is a character vector, because its first element is a character.  This means that your numeric 53 is coerced into a character.
> print(a)
[1] "fruit" "love"  "53"

You've got the wrong syntax for str_replace_all.  See the documentation for how to use it correctly.  But that's not what you want here, because you want numerics.
The first thing you need to do is convert a to a numeric.  A crude way of doing this is simply
>b <- as.numeric(a)
Warning message:
NAs introduced by coercion b
> b
[1] NA NA 53

And then subset to include only the numeric values in b:
> b <- b[!is.na(b)]
> b
[1] 53

But whether that's what you want to do with a 6 million row dataframe is another matter.  Please think about exactly what you would like to do, supply us with better test data, and ask your question again.

A: There's probably a more efficient way of doing this on a large data frame (e.g. something column-wise, instead of row-wise), but to answer your specific question about each row a:
as.numeric(stringr::str_replace_all(a, "[a-z]+", "0"))

Note that the replacing value must be a character (the last argument in the function call, "0"). (You can look up the documentation from your R-console by: ?stringr::str_replace_all)


text:
Q: Is the processorid per core? Can a processor whether a dual core or i3 or i5 or i7 have a processor id equals to number of core processor or number of logical processor?
I am using win32_processor to get processorid.
It returs a processorid but i am in stuck that whether it returns multiple processorid for each core processor or logical processor.
OR, it just return a processor id regardless of number of core processor and logical processor.

A: You will need to test this on your system as it depends on the type of CPU you have. It's likely to be one entry per logical (hyper-threaded) processor.
Here is what msdn says

On a multiprocessor computer, one instance of the Win32_Processor
class exists for each processor.
To determine the total number of
processor instances associated with a computer system object, use the
Win32_ComputerSystemProcessor association class.
To determine if
hyperthreading is enabled for the processor, compare
NumberOfLogicalProcessors and NumberOfCores. If hyperthreading is
enabled in the BIOS for the processor, then NumberOfCores is less than
NumberOfLogicalProcessors. For example, a dual-processor system that
contains two processors enabled for hyperthreading can run four
threads or programs[ or simultaneously]. In this case, NumberOfCores is
2 and NumberOfLogicalProcessors is 4.


text:
Q: How to pass in Streams Prev element result to next one I have List of items where on each item I need to create some calculation.
Each calculation is built by the preceding element.
So for example:
List<Object> Users=new ArrayList<>();
users.stream().filter(element->calculateSomething(<need-prev-element-input>).findFirst();

The calculateSomething will return true/false depends on the prev element calculation result in the stream
Any idea how can I do that?

A: Streams are not designed to be able to do any operation like this.  You might be able to hack something together to do that, but it'll be awful; you should go back to using normal loops instead.

A: If you really want to use streams, stream over indexes:
IntStream.range(1, users.size())
        .filter(i -> calculateSomething(users.get(i-1) , users.get(i)))
        .map(users::get)
        .findFirst();

There are also a number of non-standard libraries that let you stream over pairs from a list.

A: Here's the Java 8 way of doing it:
<T extends User> Optional<T> findUserSomehow(List<T> users) {
  for (int idx = 1; idx < users.size(); ++idx)
    if (calculateSomething(users.get(idx - 1)))
      return Optional.of(users.get(idx));
  return Optional.empty();
}


text:
Q: GCC compiling multiple files in different folders I am searching for gcc command that can compile multiple files in different folders at a time. prg1.c prg1.h are in C:\folder.
prg2.c which is in c:/folder/sub  includes "prg1.h"
So, I need to compile prg1.c and prg2.c at atime... and need to save generated .exe in c:/folder/sub
I am trying
cd C:\folder
gcc -o ../../sub/prg2.exe  prg1.c ../../sub/prg2.c

but getting no such file or directory error
I even tried with full path ...
Somebody help me with exact command

A: You are dropping off the top of the windows file system with ../../, perhaps that is the problem? try
gcc -o sub/prg2.exe  prg1.c sub/prg2.c


text:
Q: boost_python3 missing from ubuntu 16.04 I am trying to install boost.numpy in y Ubuntu 16.04. I tried these commnads to install boost.numpy
**git clone https://github.com/ndarray/Boost.NumPy.git
 cd Boost.NumPy && mkdir build && cd build
 cmake -DPYTHON_LIBRARY=$HOME/anaconda3/lib/libpython3.5m.so ../**

After doing cmake i am facing this error:
Detected architecture 'x86_64'
-- Using Python3

    CMake Error at /usr/share/cmake-3.5/Modules/FindBoost.cmake:1677 (message):
      Unable to find the requested Boost libraries.

  Boost version: 1.59.0
  Boost include path: /home/sumit/Documents/Software/boost_1_59_0
  Could not find the following static Boost libraries:

          boost_python3

  No Boost libraries were found.  You may need to set BOOST_LIBRARYDIR to the
  directory containing Boost libraries or BOOST_ROOT to the location of
  Boost.
Call Stack (most recent call first):
  CMakeLists.txt:48 (find_package)

 Boost Paths:
Include  : /home/sumit/Documents/Software/boost_1_59_0
 **Libraries**: /home/sumit/Documents/Software/boost_1_59_0/libs
Configuring incomplete, errors occurred!

See also "/home/sumit/Documents/Software/Boost.NumPy/build/CMakeFiles/CMakeOutput.log".
Previously it was not able to find the boost libraries sp i manualy changed the CmakeList.txt library path with the path of boost_1_59_0 lib path. This path comes up in library option when i do cmake. But still boost_python3 is missing. I am new into this what i tried is just the result of google.
Please help.

A: On Ubuntu the library names for boost are:
libboost_python, libboost_python-py35, or libboost_python-py27
This means that in cmake you'll need to refer to them as python-py35 instead of python3. Alternatively, if you don't control the CMakeLists.txt you can create a symlink:
/usr/lib/x86_64-linux-gnu/libboost_python-py35.so -> /usr/lib/x86_64-linux-gnu/libboost_python3.so
In my CMakeLists.txt file I have the following:
if(UNIX)
    set( BOOST_PYTHONLIB python-py35)
else()
    set( BOOST_PYTHONLIB python3)
endif()

find_package (Boost 1.58 REQUIRED COMPONENTS
    coroutine
    context
    filesystem
    program_options
    system
    thread
    ${BOOST_PYTHONLIB}
    chrono
    )

A: Simple answer for this is that wherever boost_python3 is specified,
you replace it with boost_python-py35.
I tried this when I was setting up caffe for python 3.5 . In the Makefile.config file, I only made the above changes and it worked fine for me.


text:
Q: How to refactor this code with static init variables? I have a static class like this:
class CDService {
 static var initVar:Type?
 static var var2:Type2? = {
    return initVar?.someProp
 }
 static func method() {
  var2?.doSomething()
 }
 //....a lot more methods all using var2?
}

Because initVar is optional (require the user to set it before using this service), now var2 has to be optional too.
And then all the methods in this class all of a sudden requires unwrapping. They are use a lot.
Is there a way to refactor this code to just not run if initVar is not yet? I could do a "if let" check in each method but its really tedious. If there is 50 methods?

A: You can use optional extensions to give default values , I've tried, it's comes really handy when using default datatype optionals.
    extension Optional where Wrapped == String { // same goes for other data types
    var orEmpty: String {
        return self ?? ""
    }

    var orDash: String {
        return self ?? "-"
    }

    var orZero: String {
        return self ?? "0"
    }
}

or in your case
    extension Optional where Wrapped == Type2 {
    var orEmpty: Type2 {
        return self ?? Type2()
    }
}


text:
Q: How to reload a page with combobox (select) value? I have a combobox - combo1. Everytime a change the combobox value, I should have a button that submits that value and reloads the page. I want to start at mysite/value?v=1 and end with mysite/value?v=2. This is what I have so far:
Javascript:
function nav() {
    var selObj = document.getElementById("combo1");
    valor = selObj.options[selObj.selectedIndex].value;
    // reload the page
}

HTML:
<input type="button" onclick="nav()" value="Ok" />

A: You are looking for window.location:
function nav(){
    var selObj = document.getElementById("combo1");

    valor = selObj.options[selObj.selectedIndex].value;
    window.location = 'mysite/value?v=' + valor;
}


text:
Q: Install Ubuntu dual boot with Windows 7 in a JBOD array Some weeks ago I decided to try ubuntu on a Virtual Machine, and I really like it! Then, some days ago, I tried to install it on my computer, together with Windows 7. But, now, I have a problem. My computer have 2 HD's (1Tb and 500Gb) in a JBOD array, and then, 2 partitions: 50gb for Windows 7, and the rest to my files. I've created another 30gb partition to install ubuntu, from the free space on my 2° partition, but, since I'm really new to ubuntu and linux, I really don't know what to do. Ubuntu doesn't recognize the Raid, and I already checked this, but, since it's a little old, and I can't loose my files, didn't helped too much, I think.
Some details:
The JBOD is configured on the motherboard controller, and windows is installed just with a special driver, with no programs at all.
RAID Controller vendor is AMD.
This kind of question probably are asked frequently, sorry for that, but I am really new to ubuntu. Also, sorry for my poor english, it isn't my native language.
Thanks in advance for your assistance.

A: There's one of two things going on here:

*

*The RAID used in Windows was built by Windows storage manager and is thus software RAID specific to that OS. It is not transferable to other operating systems.

*The RAID was configured in the BIOS, that's "fake RAID", and you simply haven't identified the proper RAID driver yet for Linux (or it doesn't exist) to be able to assemble the array.
It's up to you to drill down into the details and deploy the proper solution. Ideally, you would use a HW RAID controller that abstracted all this away for you.
Worst case, you use "Fake RAID", which is really just platform independent software RAID, to be able to share the RAID sets between Windows in Linux.
If it were me, and all I had was "Fake RAID", I wouldn't even bother. My data integrity is more important to me then sharing data between two OS. Furthermore, NTFS isn't fully supported on Linux, reading is OK, but if you start writing to that array you can destroy the data.


text:
Q: Minecraft Finding The Most Effective Direction To Get To A Yaw Value Recently I've been struck with an issue i've spent a couple hours trying to fix with no luck.
I am working on a forge mod for Minecraft where a part of it involves turning the player to a specific yaw and pitch camera angle.
My issue lies with figuring out which direction (adding or subtracting from the yaw) to turn the player on the yaw side to make the most effective path.
Side Note: The reason I cannot just set the yaw value is because i want to make it look smooth, rather than like the player is just snapped to look in that direction.
The reason this is such an issue is because of how the yaw values work, as you turn going from 0 to 180 then after 180 comes -180 which then goes from -180 to 0.
This way of handling the yaw messes up any math equations I try to find the most effective path, and I'm not sure what else to try.
The one other method i could think of is running a for loop testing going both ways (360 both ways) every single tick, which is pretty ineffective and hopefully not required. Although I will use it if it comes down to it.
Example:

*

*Input | Goal | Output

*45    | 90   | Right

*-10   | 180  | Left

*-89   | 180  | Left

*90    | -180 | Right


text:
Q: How can I detect non UTF-8 encoding in RStudio I have a script like
a <- 1
# A very long comment, perhaps copy paste from somewhere containing the word fit.

and I want to search for non UTF-8 encoding. How can I do this in RStudio?

A: I realized, the answer is really simple: Just go to Edit => Find (Strg + F) and search for [^\x00-\x7F] + with enabled Regex field in the search bar.


text:
Q: Angular password varify message The code now match very well the password but when I type in the field password, then below the input of confirm password immediately appears the message that the password does not match, when the user write down again the password the message disappear that is fine, but I would like to receive another message like: "Password match!"(in green color!), how can I do that? I read for options like dirty and touched but I could not fix it.
 @* PASSWORD CODE Below--------------<<<<<>>>>>>>>><<<<<<<<>>>>>>>>>>>>>>>>>>> *@

             *Password
             <input data-toggle="popover" data-trigger="focus" data-content="Minimum 8 characters long and should contain at least one (small- and capital letter, number and special character)." type="password" name="password" id="password" onkeypress="capLock(event)" class="form-control" ng-model="mAddEditView.User.Password" ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/" required />

Caps Lock is on.

             Password is required

         @* PASSWORD Confirm CODE Below--------------<<<<<>>>>>>>>><<<<<<<<>>>>>>>>>>>>>>>>>>> *@

                 *Confirm Password
                 <input data-toggle="popover" data-trigger="focus" data-content="The password should match." type="password" name="password1" id="password1" onkeypress="capLock(event)" class="form-control" ng-match="mAddEditView.User.Password" ng-model="mAddEditView.User.Password1" required />

Caps Lock is on.

                 Password is required
                 Password is not valid!

A: you can use form.field.$valid and $touched to display password match
Password Matched


text:
Q: Как поместить bootstrap popover у другого элемента? Как сделать так, чтобы при фокусе на input popover отображался не возле самого input-а, а возле иконки со знаком вопроса (id="q1")?

Дата начала страхования:
<input name="date_start" type="text" class="form-control" placeholder="ДД.ММ.ГГГГ" rel="popover" data-container="body" data-content="Укажите дату, с которой действует ваш страховой полис"  data-trigger="focus">

A: Переносим все необходимые data- в элемент q1

Дата начала страхования:
<input name="date_start" type="text" class="form-control" placeholder="ДД.ММ.ГГГГ">

и добавляем немного JS код на показ popoverа


text:
Q: How to convert a base64 dataUri to Uint8ClampedArray without using HTML5 Canvas? I am working on a project where I need to convert a base64 dataUri to Uint8ClampedArray without using HTML5 Canvas. This is what I have came up with but I think the Uint8ClampedArray doesn't represent the pixel table.
function dataUri2Array(uri){
    b64 = uri.slice(uri.indexOf(',')+1);
    str = atob(b64);
    arr = str.split('').map(function (e) {return e.charCodeAt(0);});
    u = new Uint8ClampedArray(arr);
    return u;
},

A: Since you don't want to use Canvas, you'll need to implement encoding/decoding for various image types yourself. Your code will look something like:
function dataUri2Array(uri){
    b64 = uri.slice(uri.indexOf(',')+1);
    type = getImageType(uri); // *
    data = atob(b64);
    switch (type) {
    case "jpeg":
         arr = decodeJpeg(data);
         break;
    case "gif":
         arr = decodeGif(data);
         break;
    case "png":
         arr = decodePng(data);
         break;
    default:
         break;
    }
    u = new Uint8ClampedArray(arr);
    return u;
}

The getImageType(uri) function and all the decodeX(data) functions need to be implemented. Here are some libraries that might help: jpeg-js, node-pngjs, bmp-js, etc. Getting the pixel arrays from arbitary data is nontrivial, especially when dealing with non-raw types (i.e. BMP).
If you want to write the decompressors yourself, the Wiki page may be a good introduction, but I also suggest reading up on Shannon-Fano and other kinds of encoding methods to familiarize yourself with the concept.
I hope you have a good reason for not using Canvas.


text:
Q: Calculus show that the function $F(x)$ has the value $(a+b)/2$ Show that the function $F(x)=(x-a)^2(x-b)^2+x$ has the value $(a+b)/2$ as some point $x$.
I have heard that $F(a)=a$ and $F(b)=b$ and that I should take some kind of average. But I do not understand why that is. I have also heard that $(a+b)/2$ is the average of the two values which is simple but I do not understand why that is important.

A: I suppose that $a<b$. Then $a <(a+b)/2<b$. Since $F(a)=a$ and $F(b)=b$ and $F$ is continuous, the intermediate value theorem says: there is $t \in (a,b)$ such that $F(t)=(a+b)/2$.
Its your turn to investigate the situations $b<a$ and $a=b$.


text:
Q: Azure Service bus to WCF I am running into issues while trying to run a WCF REST service that will connect to an Azure Service bus.  My web.config contains the following:
<system.serviceModel>
<services>
<service name="helloSB.SomeService">
<endpoint contract="helloSB.ISomeService"
binding="webHttpRelayBinding"
address = "" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:7200/mySB/helloSB.SomeService/" />
</baseAddresses>
</host>

Whenever I try to send a message to WCF, I receive:
    The service /mySB/SomeService.svc cannot be activated due to an exception during compilation.  The exception is : Unable to reach localhost via TCP (9351, 9352) or HTTP (80,443).
Why can't I use a non-standard port?

A: Looks like these are related to some port issues. The below link provides additional details on troubleshooting steps.
http://social.technet.microsoft.com/wiki/contents/articles/2055.troubleshooting-connectivity-issues-in-the-azure-appfabric-service-bus.aspx


text:
Q: Why the code below returns the same stuff? var_dump(implode(',', array('11','22')));

And
var_dump(implode(array('11','22'), ','));

Which is right?

A: According to the documentation on implode():

implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.

The documented description is:
string implode ( string $glue , array $pieces  )

implode(',', array('11','22')) (the documented order) is identical to implode(array('11','22'), ',')). Both create the string 11,22.

A: Read this:
implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.
Taken from http://php.net/manual/en/function.implode.php
Both are accepted, but as it says above - documented order of arguments should be used.


text:
Q: Best tool to do stress test for a Restful API protected with OAuth 2.0? I need to perform stress tests on a Restful API that uses OAuth 2.0 security. The authorization process involves a basic authentication followed by an authorization grant page.
Can someone direct me to the best tool to achieve this?

A: You can use RestAssured for that or Gattling.


text:
Q: Using Abel's test for negative coefficients For the power series representation of

$$\log(1-z)=\sum_{n=1}^{\infty}=\frac{-z^n}{n},$$

is Abel's test still valid to conclude that the $\log(1-z)$ will converge everywhere on the unit disk, except at $z=1$?
Abel's test requires the coefficients to be positive however in this case my coefficients are $a_n=\frac{-1}{n}$.

A: Abel's test really only requires that all the coefficients are the same sign eventually, not whether they're all positive or negative, and not depending on what the signs are for finitely many leading terms. To see this, consider $-f(x)$ instead of $f(x)$ if necessary, and subtract any leading terms in the series which have a different sign from the eventual sign.


text:
Q: Requirements for measuring PCIe 2.5GT eye diagram What is suitable equipment for measuring an eye diagram of PCIe differential pairs. I would like to evaluate the signal integrity of a PCI lane RX/TX/CLK 2.5GT. What is the recommended minimum sampling rate of a scope capable of such?
Also is it necessary to use active differential probes for this to get a good enough measurement quality, what constitutes an adequate setup for this ?

A: How you measure this depends on what your equipment can do.
Active differential probes could be a possibility, though I myself would prefer to use a scope with two channels that can internally subtract the two. This way, I can compare the performance of the individual lines of a differential pair, which can sometimes illustrate issues such as differential-to-common-mode performance of the link. It is important in that case to use phase-matched cables to connect the DUT to the source and scope, since you want to measure the line, and not the mismatch of your cables.
analogsystemsrf suggests at least 10x faster sample speed, which is a good rule-of-thumb, but unfortunately not always possible - the fastest scope ont he market samples at 256 gigasamples/second, which would mean you can only measure up to 25 Gbit/s with it. However, 25 gigasamples/s is much more reasonable and should be achieved by most scopes capable of measuring a 2.5 GT/s link.
It could be interesting to look at scopes that have built-in standard compliance tests. Many vendors sell options to have the scope measure a number of things automatically for you and compare it to the requirements set up by the standard used.


text:
Q: On proving continuity for fractional exponential functions I have a special problem here related to proving that a function is continuous.
We have:
$$f(x,y)=e^{\frac{x-1}{y}+\frac{y}{x-1}}\sqrt{1+\frac{x-y}{x+y}}$$
which shows that the function  does not exist at the line $y$ and not at the line $x=1$, nor on the plane $x=-y$.
How do I prove that this is nevertheless continuous on its domain?
The two factors are both containing forbidden regions, so how does one prove continuity for this hard nut?
Thanks!


text:
Q: Why do I need to @import my SCSS files more than once to prevent errors? I'm using some third party styles that is provided in SCSS format. I'm customizing it a good deal, so I'm using the SCSS as opposed to importing the CSS into my SCSS files.
Here is the architecture of my SCSS files.
> scss (folder)
> --third-party-code (folder)
> ----extras (folder)
> ------jquery.plugin.header.scss
> ------jquery.plugin.footer.scss
> ----third-party-code-main.scss (includes imports)
> --modules (folder)
> ----_header.scss
> ----_footer.scss
> ----_navigation.scss
> --_third-party-code.scss
> --_modules.scss (includes imports)
> --styles.scss (includes imports)

Can someone tell me why I keep getting these "mixin", "variable" or "sprite" not defined if I don't @import the SCSS files where I define my variables, mixins and sprites?
Doing this is causing two of the same sprite images to appear in my CSS which is breaking my images that use sprites on the page.
Why are the third party SCSS files being treated differently than SCSS files that I include in my "scss/modules" directory?
Let me know if I need to include any additional information.

A: Add underscore prefix to your third party files same as the files in modules, then import them. Glad it helped~


text:
Q: Typescript decorator order; get ClassDecorator information in MethodDecorator Since the decorator evaluation says that ClassDecorators come last, how to get information in a MethodDecorator which comes from the ClassDecorator?
An example would be a @Controller(prefix: string) decorator which prefixes all routes within this controller. Something like this:
const Controller = (prefix: string) : ClassDecorator => {
  return target => {
    Reflect.defineMetadata('prefix', prefix, target);
  };
};

const Get = (path: string) : MethodDecorator => {
  return (target, propertyKey, descriptor) => {
    // add this route to the router, prefixed with the `prefix` metadata from the controller
  };
};

@Controller('/foo')
class Foo {
  @Get('/bar')
  bar() {
  }
}

Using this code the prefix metadata from target in Get is undefined.

A: As I commented, you should define metadata for each call to Get where you store what you need (in general, you can store the property key and descriptor if you need them; otherwise, store only what you actually need).  Then, in the call to Controller, read in all that metadata and do what you want with it.   For example:
import "reflect-metadata";

// stuff to store with each call to Get
interface GetMethodInfo {
  propertyKey: string | symbol;
  descriptor: TypedPropertyDescriptor<any>
}

const Get = (path: string) : MethodDecorator => {
  return (target, propertyKey, descriptor) => {
    if (!Reflect.hasMetadata('get-methods',target)) {
      // store an array if it's not there already
      Reflect.defineMetadata('get-methods', [], target);
    }
    const getMethods: Array<GetMethodInfo> = Reflect.getMetadata('get-methods', target);
    // push the new information into that array
    getMethods.push({propertyKey: propertyKey, descriptor: descriptor})
  };
};

const Controller = (prefix: string) : ClassDecorator => {
  return target => {
    // read in the array from the metadata (may be undefined if no calls to Get)
    const getMethods: Array<GetMethodInfo> = Reflect.getMetadata('get-methods', target) || [];
    getMethods.forEach(getMethodInfo => {
      // add this route to the router, prefixed with the `prefix` metadata from the controller
    })
  };
};

@Controller('/foo')
class Foo {
  @Get('/bar')
  bar() {
  }
}

Hope that helps.  Good luck.


text:
Q: Search/Replace Headers with Start/End Tokens in Python I am new to Python and I have a task where I need to sanitize headers in files in a particular way because there is no standard for my headers right now and I am trying to come up with this script to reuse for multiple instances
Sample File:
*_____________________________
* This is header text
* For details, see foobar.txt.
*_____________________________
*
*

* Code goes here
Code = x

The way I have to do this is by defining starting and ending position for the header and then scrub everything in between (start/end point included), before adding a new header.
Currently I am trying to use my
start_pos = r"*_____________________________"
end_pos = r"""*_____________________________
    *
    *"""

and then search for everything in the middle. I want to then concat altogether and then delete/replace to have my new file look like this:
*
* Hello, world.
*

* Code goes here
Code = x

A: Here it comes:
\*_____________________________([\s\S]*?)\*_____________________________(?:\n\*){2}

Demo
To match the content in-between we can use a modified "dot" [\s\S] that matches everything across including newlines. The "dot" matches lazy to avoid matching too much.
Sample Code:
import re
regex = r"\*_____________________________([\s\S]*?)\*_____________________________(?:\n\*){2}"
test_str = ("*_____________________________\n"
    "* This is header text\n"
    "* For details, see foobar.txt.\n"
    "*_____________________________\n"
    "*\n"
    "*\n\n"
    "* Code goes here\n"
    "Code = x\n")
subst = "*\\n* Hello, world.\\n*"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)


text:
Q: Cannot read json in PHP, need newline at the end of the text So I have a json file inside my folder, but I cannot read it because it need an empty line at the end, how to solve that ?
I read my json in PHP using this :
$string = file_get_contents('ideb/NPWP.txt');
$json_a = json_decode($string, TRUE);
echo $json_a['header']['kodeReferensiPengguna'];

My json :
{
    "header": {
        "kodeReferensiPengguna": "",
        "tanggalHasil": "",
        "idPermintaan": "",
        "idPenggunaPermintaan": "",
        "dibuatOleh": "Dyta Alldilah",
        "kodeLJKPermintaan": "",
        "kodeCabangPermintaan": "",
        "kodeTujuanPermintaan": "",
        "tanggalPermintaan": "",
        "totalBagian": "1",
        "nomorBagian": "1"
    }
}

If I add newline at the bottom of the json there is no error
{
    "header": {
        "kodeReferensiPengguna": "",
        "tanggalHasil": "",
        "idPermintaan": "",
        "idPenggunaPermintaan": "",
        "dibuatOleh": "Dyta Alldilah",
        "kodeLJKPermintaan": "",
        "kodeCabangPermintaan": "",
        "kodeTujuanPermintaan": "",
        "tanggalPermintaan": "",
        "totalBagian": "1",
        "nomorBagian": "1"
    }
}

NOTE : My json file format is .txt

A: The key kodeReferensiPengguna has no value. print dibuatOleh key there is value. it is working.
$string = file_get_contents('ideb/NPWP.txt');
$json_a = json_decode($string, TRUE);
echo $json_a['header']['dibuatOleh'];

A: Solved thanks to @NikitaLeshchev..
Using :
$string = file_get_contents('ideb/NPWP.txt');
$json_a= mb_convert_encoding($string , 'UTF-8', 'UTF-8');
$json_a = json_decode($string, TRUE);
echo $json_a['header']['dibuatOleh'];


text:
Q: uiimage animation effect I'm trying to get a UIImage to have a slight bobbing effect.
[UIView setAnimationDelegate:self];
            [UIView setAnimationDidStopSelector:@selector(endSwipeAnimation)];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
            [UIView setAnimationRepeatCount:10];
            [myImage setAlpha:1.0];
            [myImage setAlpha:0.7];

            [UIView setAnimationRepeatAutoreverses:NO];

          [UIView commitAnimations];

any ideas how to accomplish this?
thanks in advance

A: In between animation write what new effect or change u want.
first set imageView alpha value to 1
and then change its alpha value to 0.5 or whatever u want in animation.

A: [UIView beginAnimations:animationID context:context];
[UIView setAnimationDuration:duration];

are missing... ?


text:
Q: How to undo double-click in Jupyter Notebook? Double-clicking on a cell in Jupyter Noterbook enters the Edit Mode for that cell.
How to revert this action? How to exit the Edit Mode?

A: The Edit area has a gray background. On the left of it there is an area with the white background, limited on the left with a vertical bar of green or blue color.
Click that white background and press <Shift+Enter>.


text:
Q: How do I update a generic class-view? I have a django app that stores information on different profiles of people. I want to be able to provide a downloadable spreadsheet and update a class-view(ListView) on the website using the same url. I don't fully understand class views yet and I'm struggling to figure out how to combine the two view functions below.
I tried this:
views.py
class ProfileList(ListView):
    model = Profile
    #template_name = 'search.html'
    def get(self, request):
        return export_profiles(request)

def export_profiles(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="profile_list.csv"'

    writer = csv.writer(response)
    writer.writerow(['Name','Title','Location','Phone','Email','Company Name','Company Size','Link'])
    data = Profile.objects.filter()
    for row in data:
        rowobj = [row.name,row.title,row.location,row.phone,row.email,row.GetCompany().companyName,row.GetCompany().companySize,row.url]
        writer.writerow(rowobj)
    #Clean up database
    return response

urls.py
urlpatterns = [
    path('search/', views.search, name='search'),
    path('profiles/', ProfileList.as_view()),
    path('accounts/', include('django.contrib.auth.urls')),
    url('session_security/', include('session_security.urls')),
]

This worked for downloading the file, but still didn't update the profile list with the django as_view() function. It just downloaded the csv file without erroring.
This is what I currently have:
views.py
#Post a view of profiles on the website when a search is initiated
class ProfileList(ListView):
    model = Profile
    template_name = 'search.html'

@login_required
def export_profiles(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="profile_list.csv"'

    writer = csv.writer(response)
    writer.writerow(['Name','Title','Location','Phone','Email','Company Name','Company Size','Link'])
    data = Profile.objects.filter()
    for row in data:
        rowobj = [row.name,row.title,row.location,row.phone,row.email,row.GetCompany().companyName,row.GetCompany().companySize,row.url]
        writer.writerow(rowobj)

    return response

urls.py
urlpatterns = [
    path('search/', views.search, name='search'),
    path('profiles/', views.export_profiles, name='profiles'),
    path('accounts/', include('django.contrib.auth.urls')),
    url('session_security/', include('session_security.urls')),
]

search.html

Profiles

The following list does not save after the next search you make! Please save the csv file placed in your browser downloads folder.

            {% for profile in object_list %}

Name: {{ profile.name }}

Title: {{ profile.title }}

Location: {{ profile.location }}

Phone: {{ profile.phone }}

Email: {{ profile.email }}

Company Name: {{ profile.GetCompany.companyName }}

Company Size: {{ profile.GetCompany.companySize }}

Link: {{ profile.url }}

            {% endfor %}

Am I right to be trying to combine a django class-view and another view function under one url? A full solution would be nice but a lot to ask for. I'm just asking for some pointers and links to further educate myself on this problem.


text:
Q: dynamic exclusion of files through grep matching I have a file source-push.sh which returns the list of files which I want to exclude from the results of find command.
It looks like this:
#!/usr/bin/env bash
find . -not \( -path './node_modules' -prune \) -name '*.js' | grep -vE $(echo $(./source-push.sh | xargs -I{} echo -n "{}|") | rev | cut -b2- | rev) | xargs -L1 standard --fix
find . -not \( -path './node_modules' -prune \) -name '*.css' | grep -vE $(echo $(./source-push.sh | xargs -I{} echo -n "{}|") | rev | cut -b2- | rev) | xargs -L1 stylelint --config stylelint.json

There are supposed to be a way to do the job better than that.  Any suggestions?

A: Instead of:
... | grep -vE $(echo $(./source-push.sh | xargs -I{} echo -n "{}|") | rev | cut -b2- | rev ) | ...

you can use the POSIX options -F and -f:
... | grep -v -F -f <( ./source-push.sh ) | ...

*

*-F tells grep that the patterns are fixed strings

*

*(avoiding the problem that your original code would break if the patterns contain characters that are special to grep -E)

*-f file tells grep to use a list of patterns from file

*<( ... ) is a bash way to present output of a program as a file (named pipe)


text:
Q: How to write filter for multiple conditions in html? enter image description hereI have the code given below.
I am using story owner and story state.
ng-repeat="item in IterationStories |
filter: {Story: {storyOwner: filterRequestor}} |
filter: {Story: {state: filterKey}} " //when I select state it is working

A: You find a good example on the official Angular filter documentation here.
So if your "item" object look like this:
{
   storyOwner: 'something',
   state: 'deleted',
}

You can implement the filter like this:
Story owner <input ng-model="search.storyOwner">
State <input ng-model="search.state">

A:

    //for third solution
    $scope.myFilter = function (item) {
        return (item.storyOwner == $scope.Story.storyOwner || item.state:$scope.Story.filterKey );
    }

    ng-repeat="item in IterationStories | filter:{storyOwner: filterRequestor, state: filterKey} "

    ng-repeat="item in IterationStories | filter: {Story: {storyOwner: filterRequestor, state: filterKey}}"

    ng-repeat="item in IterationStories | filter:myFilter"


text:
Q: Generate a table with interval of months in a year -Oracle I have to create a table in the below format:-
TS_RANGE_BEGIN      TS_RANGE_END
2019-01-01 17:00:00 2019-01-31 17:00:00
2019-02-01 17:00:00 2019-02-28 17:00:00
2019-03-01 17:00:00 2019-03-31 17:00:00

Could you please help on this?
Thanks,

A: Looks like a simple row generator:
SQL> alter session set nls_date_format = 'yyyy-mm-dd hh24:mi:ss';

Session altered.

SQL> with std (datum) as
  2    (select to_date('01.01.2019 17:00', 'dd.mm.yyyy hh24:mi') from dual)
  3  select add_months(datum, level - 1) ts_range_begin,
  4         add_months(datum, level) - 1 ts_range_end
  5  from std
  6  connect by level <= 12;

TS_RANGE_BEGIN      TS_RANGE_END
------------------- -------------------
2019-01-01 17:00:00 2019-01-31 17:00:00
2019-02-01 17:00:00 2019-02-28 17:00:00
2019-03-01 17:00:00 2019-03-31 17:00:00
2019-04-01 17:00:00 2019-04-30 17:00:00
2019-05-01 17:00:00 2019-05-31 17:00:00
2019-06-01 17:00:00 2019-06-30 17:00:00
2019-07-01 17:00:00 2019-07-31 17:00:00
2019-08-01 17:00:00 2019-08-31 17:00:00
2019-09-01 17:00:00 2019-09-30 17:00:00
2019-10-01 17:00:00 2019-10-31 17:00:00
2019-11-01 17:00:00 2019-11-30 17:00:00
2019-12-01 17:00:00 2019-12-31 17:00:00

12 rows selected.

SQL>

The STD CTE is used to set starting date.


text:
Q: Pass variables from one job to an other in an azure multi stage pipeline (YAML) I have a very basic YAML azure pipeline
jobs:
- job: Foo
  steps:
  - bash: |
      echo "Create variable xyz"
      echo "##vso[task.setvariable variable=xyz;]yes"
    displayName: 'Determine slot name'
  - bash: |
     echo "Var is: $(xyz)"
    displayName: 'Show variable'
- job: Bar
  dependsOn: Foo
  steps:
  - bash: |
      echo "Hello world $(Foo.xyz)"
    displayName: 'Show variable'

In the first JOB, named Foo, the variable xyz is set to yes. Which works, because I can display it in the seconds step with the line
echo "Var is: $(xyz)"

However, I would like to use that variable in the next job (named Bar). But whatever I do it does not exist. I tried things like
 echo "Hello world $(xyz)"

or
 echo "Hello world $(Foo.xyz)"

But both give the following error when I run the pipeline
 line 1: Foo.xyz: command not found

How can I share that variable between jobs? and sharing between stages would be nice too!!

A: So you have here actually two things.
Pass variables from job to job which is possible:
Did you try multi job output variable:
jobs:

# Set an output variable from job A
- job: A
  pool:
    vmImage: 'vs2017-win2016'
  steps:
  - powershell: echo "##vso[task.setvariable variable=myOutputVar;isOutput=true]this is the value"
    name: setvarStep
  - script: echo $(setvarStep.myOutputVar)
    name: echovar

# Map the variable into job B
- job: B
  dependsOn: A
  pool:
    vmImage: 'ubuntu-16.04'
  variables:
    myVarFromJobA: $[ dependencies.A.outputs['setvarStep.myOutputVar'] ]  # map in the variable
                                                                          # remember, expressions require single quotes
  steps:
  - script: echo $(myVarFromJobA)
    name: echovar

Please check this question.
Pass variable from stage to stage: which is not possible out of the box at the moment.
Please check this question. Merlin Liang - MSFT explained this there.
Workaround
You can try write down to some file your variables, publish it as pipelineartifact, download this artifact in another stage and load variables. Please check this link.


text:
Q: How many injective functions are there from {1 2 3} to {4 5 6 7 8)? My thoughts are that to find the number of injective functions, just multiply 3 and 5 together since there are 3 elements in the first set and 5 elements in the second. Is this the right way to approach this problem?

A: Hint:  In how many ways can you assign $f(1)$?  Once $f(1)$ has been assigned, in how many ways can you assign $f(2)$?  Once $f(1)$ and $f(2)$ have been assigned, in how many ways can you assign $f(3)$?

A: This is called a Permutation of $n$ things taken $k$ at a time:
$$
P(n,k)=\underbrace{n(n-1)(n-2)\cdots(n-k+1)}_{k\text{ terms}}
$$
This says that there are $n$ ways of placing the first of $k$ items, $n-1$ to place the second, $n-2$ to place the third, and so on, until there are $n-k+1$ ways to place the $k^\text{th}$.
In your case, $n=5$ and $k=3$.

As commented by anorton, and mentioned in the link above, $P(n,k)$ is also commonly denoted by the Pochhammer symbol, $(n)_k$, and sometimes by the $k^\text{th}$ falling factorial, $n^{\underline{k}}$.


text:
Q: JAXB Customizations and List I used JAXB to create some classes from an XSD. The result was not quite what I expected
and most probably it can be customized.
It created a generic list instead of 3 different lists. Can this be corrected somehow?
@XmlElements({
    @XmlElement(name = "M1", type = M1_Type.class),
    @XmlElement(name = "M2", type = M2_Type.class),
    @XmlElement(name = "M3", type = M3_Type.class)
})

protected List<Object> m1Orm2OrM3;

Is there a customization to fix this?

A: You probably have a repeatable choice, something like
<choice maxOccurs="unbounded">
  <element name="M1" .../>
  <element name="M2" .../>
  <element name="M3" .../>
</choice>

The answer is negative, there's no such customization. "Three list" is actually a very different data structure.


text:
Q: Does AWS cfn-init need a Profile/Role for DescribeStackResource? From this page:

To use the AWS CloudFormation bootstrap features, you need to provide AWS credentials to the
  bootstrap scripts. We strongly recommend that you assign an IAM role to on the EC2 instance
  when the instance is launched.

This seems pretty straightforward, but when I look at any example from all over the place in AWS documents, they never set up roles or profiles for this. For example, here.
What am I missing? Are there scenarios that cfn-init requires extra permissions while not in others?

A: No, you no longer need to add the cloudformation:DescribeStackResource to any policies of the role associated with the instance profile in order to access CloudFormation metadata. The scripts such as cfn-get-metadata and cfn-init are authorized using a special CFN header instead of the standard AWS Authorization header. A request from the CFN scripts looks like this:
# This command succeeds regardless of your instance profile
cfn-get-metadata --region us-west-1 --stack cftest --resource LaunchConfig  --key AWS::CloudFormation::Init

GET /?Action=DescribeStackResource&StackName=cftest&Version=2010-05-15&ContentType=JSON&LogicalResourceId=LaunchConfig HTTP/1.1
Host: cloudformation.us-west-1.amazonaws.com
Connection: keep-alive
Accept: application/json
Accept-Encoding: gzip, deflate
Authorization: CFN_V1 ewogICJwcml2YXRlSX(truncated)==:b9ZM3/EnzeX(truncated)=
User-Agent: CloudFormation Tools

The CFN Authorization header is a concatenation of http://169.254.169.254/latest/dynamic/instance-identity/document and http://169.254.169.254/latest/dynamic/instance-identity/signature and only allows the instance to view the CloudFormation metadata from its own stack.
In contrast, a request that uses the instance profile looks like this:
# This command fails if you don't have cloudformation:DescribeStackResource permission!
aws cloudformation --region us-west-1 describe-stack-resource --stack-name cftest --logical-resource-id LaunchConfig

POST / HTTP/1.1
Host: cloudformation.us-west-1.amazonaws.com
Accept-Encoding: identity
Content-Length: 95
X-Amz-Date: 20160630T010040Z
User-Agent: aws-cli/1.10.43 Python/2.7.11+ Linux/4.4.0-28-generic botocore/1.4.33
X-Amz-Security-Token: FQoDY(truncated-token)=
Content-Type: application/x-www-form-urlencoded
Authorization: AWS4-HMAC-SHA256 Credential=ASIA(truncated)/20160630/us-west-1/cloudformation/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=fbad7aeef75186cb18bbd44810c4d0379d7d1cf1b8a80be14ea1e3192d2ec531

Action=DescribeStackResource&StackName=cftest&Version=2010-05-15&LogicalResourceId=LaunchConfig

The instance profile temporary credentials are fetched from http://169.254.169.254/latest/meta-data/iam/security-credentials/ as described in IAM Roles for EC2.
(Note: to collect these requests, I ran nc -l 80 & and ran cfn-get-metadata --url http://localhost and aws --endpoint-url http://localhost.)
This CFNSigner functionality was added to the client between aws-cfn-bootstrap-1.1 (2012-03) and aws-cfn-bootstrap-1.3.6 (2012-09). Prior to 2012, you did need to use a role with cloudformation:DescribeStackResource permission, as described in this 2011 document Boostrapping Applications With AWS CloudFormation. Note that only the cfn-* scripts use the CFNSigner; if you want to use aws cloudformation, you need to make sure your roles allow it.

A: clou-init scripts need to connect to the AWS Services for retrieving the metadata that you provide in the CFN template.
In order to connect to the AWS Service, either you can pass on the access/secret key to the cfn-init scripts directly or attach an IAM role with necessary permissions to the EC2 instance so that the cfn-init script will connect to the AWS Services using IAM Role.
Read this further: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
All the samples provided by cfn-init presumes that you have IAM role attached to the instance so that access/secrete keys need not be passed directly to the cfn-init scripts.


text:
Q: scrolling up set of pictures up and down on hover function I have been working on a portfolio for a small firm that I have. I was planning to have the same function as this one from e-onetime http://eone-time.com/#team do you think this is possible with a gif image. The function that I would like to have is that on hover gif animated 1 time, or should I set multiple images like what they did on their portfolio and let it scroll up and down onclick.
This is a section from my TEAM section in which the static gif and animated gif is located:

TEAM

This is the javascript function I have for my team profiler:
</script>

A: just animate background-image using css keyframes for a .animated class, and then add this to your javascript:
$('#items a').mouseover(function(){
  $(this).toggleClass('animated');
});


text:
Q: Sorting bibliography and modifying apa-style of BibLaTeX properly I worked my way through the biblatex and apastyle documentation, but couldn't find a way to solve my problems. Maybe one of you can help me.
\documentclass[12pt,twoside]{report}
\usepackage[utf8]{inputenc}
\bibliographystyle{apalike}
\usepackage[style=apa, sorting=none,doi=false]{biblatex}
\addbibresource{Literature.bib}
\begin{document}
text with \cite{Example.2002} or \footcite{Example.2003}
\printbibliography
\end{document}

As shown above, I am using biblatex and the \footcite or \cite commands for my references. While using the apastyle in my preamble two main problems arise:

*

*Without sorting=none the bibliography remains empty. But I want an alphabetic order for which I would need to apply the nyt-option but then the bibliography is not attached.

*I want to put the year for both citations commands into parentheses. I tried to find a way through the authoryear-style which leads to broken references and even more problems. Is there a possibility to apply the parentheses in my example?

I read a lot of similar threads and I know that there are other approaches but I would to prefer to change as little as possible because it took a long time to get the current version in an acceptable form.
Thanks in advance!

A: The apa style for biblatex implements an exact version of the APA 7th edition style, and is not really designed to be modified. You certainly should not be using sorting=none with it.  Furthermore, the \bibliographystyle command is not used will biblatex and will be ignored. To use in-text citations with apa you should use the \textcite command. This will give you Author (Year) citations. Instead of using \footcite you can instead use \footnote{\textcite{...}} which will yield the same format inside footnotes.
When using an author/year scheme, the prenote is not very useful, since it appears inside the parenthesized year. The postnote can be used, and in the APA style, will appear with a comma after the year. Note that for the postnote, you should just provide a page number or a page range, and the style will add the p. or pp. automatically.
Here's a full example:
\documentclass[12pt,twoside]{report}
\usepackage[style=apa, doi=false]{biblatex}
\addbibresource{biblatex-examples.bib}
\begin{document}
See \textcite[529-531]{bertram} or\footnote{\textcite[579]{glashow}}
\printbibliography
\end{document}


text:
Q: Error starting Firefox on 18.04 I just installed Ubuntu using UserLAnd on my phone. I installed Firefox and tried to launch it via the terminal. I got the error
[18567, Main Thread] WARNING: failed to open shm: Permission denied: file /build/firefox-dnXMb4/firefox-70.0+build2/ipc/chromium/src/base/shared_memory_posix.cc, line 250
Segmentation fault
I used apt purge firefox then reinstalled it. I tried to launch Firefox from the terminal again and got the same error.
Additional info:
Root user,  Android,  UserLAnd w/ xsdl Ubuntu 18.04 lts

A: Did a bit of digging. I found this guide and it works flawlessly.
apt update
apt install software-properties-common
add-apt-repository ppa:mozillateam/ppa
apt update
apt install firefox-esr
firefox-esr


text:
Q: Windows 10 Text is to big. How to make text smaller please The icon pictures on the desktop are ok in size, but the text is big.  The word and outlook gui screens are very big and the text on google chrome bookmarks bar is big.  Scaling in windows 10 is set at 100% and cannot make it smaller. Everything on Google search is about making the text bigger, where this problem is to make it smaller

A: Problem solved.
Window 10 has a bug that causes this problem.
The fix is to type a number in the scaling, eg 140%, apply and reboot.
On start up go to scaling and type 100%, apply and reboot.  Problem fixed.  It appears that the 100% displayed is corrupted, and by changing it upwards and then back to 100% overwrites the corrupted entry.

A: Search up text size in the windows settings, what value is the slider at? You only mentioned about display scale, try lowering this value instead.


text:
Q: execute cshtml code on selection changed to retrieve items I have a cshtml page that has some selection that I'd like to execute some other C# code to fetch items when the selection is changed.
var choices= new List<string[]>();
<select name="student" onselect="">
            @foreach (var student in students)
            {
                <option value="@student[0]" onselect="@{
                                                           choices = choice.ReturnChoices(@student[0]);
                                                      }">@student[2] @student[3] @student[4]</option>
            }
        </select>

Now, I'd like to call the method that returns the student choices when the student value changes and populate another dropdown/select.
However, currently, on loading, the dropdown is showing all the choices.

A: You will have to register onselect (JavaScript) event, and on this give an ajax call to the controller along with the student name which will return the list of the choices. and on the success of ajax call fill the second drop down using jquery/javascript and you can show the progress bar while drop down is being populating.
<select name="student" onselect="onStudentSelect()">

function onStudentSelect(){
    $.ajax({
                    url: //Url to your action method along with the student name in query string,
                    type:get,
                    dataType: "json",
                    complete: function() {
                        //remove progress bar.
                    },
                    beforeSend: function() {
                        //Show progress bar.
                    },
                    success: function (data) {
                        //fill second drop down like:
                        //$("#secondDropDown").append('<option value="' + anyvalue + '">' + anyText + '</option>');
                    }
                });
}


text:
Q: split the sentence according to some criteria I have database FSTP. This db include 2 tables. dbo.CLIENTS and dbo.CLIENTS_address.
I should select column [address] from dbo.CLIENTS which looks like:

*

*Without phone number:
010010, c.Paris, Saint-Gilles,  st. Rue, b. 75003, of. 27

*With phone number:
516097, Capen-Hall, Buffalo, NY 14260, of. 1611. PHONE: (716) 645-3321
I want to divide this text to columns and write to dbo.CLIENTS_address
I write code. It is work good with zip and city.
But I can't divide Address and Phone
select
 case when CHARINDEX(' ',CLIENTS.adres)>0 then
     SUBSTRING(CLIENTS.adres,1,CHARINDEX(' ',CLIENTS.adres)-2)
 else
     adres
 end [ZIP],
 case when CHARINDEX(',',CLIENTS.adres)>0 then
     SUBSTRING(CLIENTS.adres,9,CHARINDEX(',',CLIENTS.adres,9)-9)
 else
     adres
 end [city],
 CASE WHEN CHARINDEX(', ',CLIENTS.adres)>0 THEN
 SUBSTRING(CLIENTS.adres,CHARINDEX(',',CLIENTS.adres,9)+1,len(CLIENTS.adres))
 ELSE
    NULL
 END as [Address],
 CASE WHEN CHARINDEX('Phone',CLIENTS.adres)>0 THEN
     SUBSTRING(CLIENTS.adres,CHARINDEX('Phone. ', CLIENTS.adres)+5,len(CLIENTS.adres))
 ELSE
     NULL
 END as [Phone]
  from [FSTP].[dbo].[CLIENTS]

The result what I expected is:
 SELECT * FROM CLIENTS_address;
+-------+-----------+-----------------------------------------+--------------+
| zip   | city      | Address                                 | Phone        |
+-------+-----------+-----------------------------------------+--------------+
| 010010| Paris     | Saint-Gilles,  st. Rue, b. 75003, of. 27|  NULL        |
| 516097| Capen-Hall| NY 14260, of. 1611.                     |(716) 645-3321|
+-------+-----------+------------+----------------------------+--------------+

but I get this:
 SELECT * FROM CLIENTS_address;
+-------+-----------+-----------------------------------------+--------------+
| zip   | city      | Address                                 | Phone        |
+-------+-----------+-----------------------------------------+--------------+
| 010010| Paris     | Saint-Gilles,  st. Rue, b. 75003, of. 27|  NULL        |
| 516097| Capen-Hall| NY 14260, of. 1611. (716) 645-3321      |(716) 645-3321|
+-------+-----------+------------+----------------------------+--------------+

A: SQLQuery:
SELECT CASE
           WHEN CHARINDEX(' ', CLIENTS.adres)>0 THEN SUBSTRING(CLIENTS.adres, 1, CHARINDEX(' ', CLIENTS.adres)-2)
           ELSE adres
       END [ZIP],
       CASE
           WHEN CHARINDEX(',', CLIENTS.adres)>0 THEN SUBSTRING(CLIENTS.adres, 9, CHARINDEX(',', CLIENTS.adres, 9)-9)
           ELSE adres
       END [city],
       CASE
           WHEN CHARINDEX(', ', CLIENTS.adres)>0
                AND CHARINDEX('Phone: ', CLIENTS.adres) > 0 THEN SUBSTRING(CLIENTS.adres, CHARINDEX(',', CLIENTS.adres, 9)+1, CHARINDEX('Phone: ', CLIENTS.adres)-CHARINDEX(',', CLIENTS.adres, 9)-2)
           WHEN CHARINDEX(', ', CLIENTS.adres)>0 THEN SUBSTRING(CLIENTS.adres, CHARINDEX(',', CLIENTS.adres, 9)+1, len(CLIENTS.adres))
           ELSE NULL
       END AS [Address],
       CASE
           WHEN CHARINDEX('Phone', CLIENTS.adres)>0 THEN SUBSTRING(CLIENTS.adres, CHARINDEX('Phone: ', CLIENTS.adres)+7, len(CLIENTS.adres))
           ELSE NULL
       END AS [Phone]
FROM Table1 CLIENTS

Results:
|    ZIP |       city |                                  Address |          Phone |
|--------|------------|------------------------------------------|----------------|
| 010010 |    c.Paris |  Saint-Gilles, st. Rue, b. 75003, of. 27 |         (null) |
| 516097 | Capen-Hall |             Buffalo, NY 14260, of. 1611. | (716) 645-3321 |

A: You may try this.
SELECT
CASE WHEN CHARINDEX(' ', CLIENTS.adres)>0 THEN
    SUBSTRING(CLIENTS.adres, 1, CHARINDEX(' ', CLIENTS.adres)-2)
ELSE
    adres
END [ZIP],
CASE WHEN CHARINDEX(',', CLIENTS.adres)>0 THEN
    SUBSTRING(CLIENTS.adres, 9, CHARINDEX(',', CLIENTS.adres, 9)-9)
ELSE
    adres
END [city],
CASE WHEN CHARINDEX(', ', CLIENTS.adres)>0 AND CHARINDEX('Phone: ', CLIENTS.adres) > 0 THEN
        SUBSTRING(CLIENTS.adres, CHARINDEX(',', CLIENTS.adres, 9)+1, CHARINDEX('Phone: ', CLIENTS.adres)-CHARINDEX(',', CLIENTS.adres, 9)-1)
    WHEN CHARINDEX(', ', CLIENTS.adres)>0 THEN
         SUBSTRING(CLIENTS.adres, CHARINDEX(',', CLIENTS.adres, 9)+1, len(CLIENTS.adres))
ELSE
    NULL
END AS [Address],
CASE WHEN CHARINDEX('Phone', CLIENTS.adres)>0 THEN
    SUBSTRING(CLIENTS.adres, CHARINDEX('Phone: ', CLIENTS.adres)+7, len(CLIENTS.adres))
ELSE
    NULL
END AS [Phone]
FROM Table1 CLIENTS

For testing you may try this
 declare @mychar nvarchar(max)
 set @mychar = '516097, Capen-Hall, Buffalo, NY 14260, of. 1611. PHONE: (716) 645-3321'
 select SUBSTRING(@mychar,CHARINDEX(',',@mychar,9)+1,len(@mychar))  ---- your query
 select SUBSTRING(@mychar,CHARINDEX(',',@mychar,9)+1,CHARINDEX('PHONE:', @mychar)-CHARINDEX(',',@mychar,9)-1)   --- porposed solution


text:
Q: Parsing json with duplicate keys I am trying to parse Json file which contains duplicate keys in java.I am using the method suggesteed in this answer Parsing a json which contains duplicate keys.
The approach works fine if I hard-code the Json but if I read it from a file,only the last duplicate key is read.Please Help as I want to read the Json from a file.Thanks in advance.
Code:
public class am {
    public static  void main(String args[]) throws Exception
    {
        JSONParser parser = new JSONParser();

        Object obj = parser.parse(new FileReader("sample.json"));

        JSONObject a=JSONObject.fromObject(obj);
        JSONObject jsonObject=JSONObject.fromObject("{\n" +
                "  \"Data\": {\n" +
                "    \"A\": {\n" +
                "      \"B\": {\n" +
                "        \"C\": \"c\",\n" +
                "        \"D\": {}\n" +
                "      },\n" +
                "      \"E\": {\n" +
                "        \"F\": \"f\"\n" +
                "      },\n" +
                "      \"G\": {\n" +
                "        \"H\": \"h\"\n" +
                "      }\n" +
                "    },\"A\": {\n" +
                "      \"B\": {\n" +
                "        \"C\": \"x\",\n" +
                "        \"D\": {}\n" +
                "      },\n" +
                "      \"E\": {\n" +
                "        \"F\": \"y\"\n" +
                "      },\n" +
                "      \"G\": {\n" +
                "        \"H\": \"z\"\n" +
                "      }\n" +
                "    },\n" +
                "
                "\n" +
                "  }\n" +
                "}");
        System.out.println("Json objects are:::"+a);
        System.out.println("Json objects are:::"+jsonObject);

    }
}

Json File:
{
  "Data": {
    "A": {
      "B": {
        "C": "c",
        "D": {}
      },
      "E": {
        "F": "f"
      },
      "G": {
        "H": "h"
      }
    },"A": {
      "B": {
        "C": "x",
        "D": {}
      },
      "E": {
        "F": "y"
      },
      "G": {
        "H": "z"
      }
    },

  }
}

Output:
Json objects are:::{"Data":{"A":{"B":{"C":"x","D":{}},"E":{"F":"y"},"G":{"H":"z"}}}}
Json objects are:::{"Data":{"A":[{"B":{"C":"c","D":{}},"E":{"F":"f"},"G":{"H":"h"}},{"B":{"C":"x","D":{}},"E":{"F":"y"},"G":{"H":"z"}}]}}

A: If you do not have a constraint to use external JSON library than you can use net.sf.json.JSONObject to parse your JSON string, It will accept JSON with the duplicate key. It will retain the duplicated values by storing them into arrays.
JSONObject jsonObject = JSONObject.fromObject( "{\"Data\": {\"A\": {\"B\": {\"C\": \"c\",\"D\": {}},\"E\": {\"F\": \"f\"},\"G\": {\"H\": \"h\"}},\"A\": {\"B\": {\"C\": \"x\",\"D\": {}},\"E\": {\"F\": \"y\"},\"G\": {\"H\": \"z\"}}}}" );
System.out.println( "net.sf.json.JSONObject: " + jsonObject );

A: You need to stringify your JSON object
a.toString()


text:
Q: While highlighting the text from a string using spans creating problems I am new to webDevelopment. I have a string , and I want to highlight some part of the strings like 10-15 things I want to highlight. Now I do have the offsets as well, like start and end of the text which I want to highlight from that string. SO, When in the loop first gets highlighted then it adds the span tag there with class mark, because of this the indexes are getting changed, then when it try to highlight the second then it does not get the perfect match because the offsets are now changed. So, How Can I match the exact text with the span tags or without that ?
$scope.highlight = function(content,startoffset,endoffset){return content.replace(content.substring(startoffset, endoffset), '$&');}

.mark {background-colour = yellow;}

Can any please help me with this, This is really getting messy for me.

A: Refer this https://plnkr.co/edit/j5VCCjCHN60l0QNSTtLo?p=preview. I replaced your mark up with "**" as it is easy to show sample example.
  function stringReplace(content, startoffset, endoffset, previousOffset) {
    _temp = _temp.concat(content.substring(previousOffset || 0, startoffset));
    _temp = _temp.concat('**');
  }


text:
Q: Android Bluetooth LE Masked UUID Filter I am playing around with an experimental Bluetooth LE program for Android and iOS, and right now I am having some trouble on the Android side filtering beacon advertisements sent out by the iOS side. Android has a feature to filter advertisements by UUID with a mask (I need this as I am trying to get UUIDs beginning with a specific value) but I can't get it to work. Here's what I am trying:
private void freshen() {
    // kill current scanner
    if (mLEScanner != null)
        mLEScanner.stopScan(mScanCallback);

    // set new one to be a match scanner
    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build();

    List<ScanFilter> filters = new ArrayList<>();

    // create data uuid starting with the value 1
    ParcelUuid data = ParcelUuid.fromString("10000000-0000-0000-0000-000000000000");
    // create a mask to ensure only that value is searched
    ParcelUuid mask = ParcelUuid.fromString("10000000-0000-0000-0000-000000000000");

    // build the filter
    ScanFilter.Builder builder = new ScanFilter.Builder();
    builder.setServiceUuid(data, mask);
    ScanFilter filter = builder.build();

    // add the filter to the scanner
    filters.add(filter);
    mLEScanner.startScan(filters, settings, mScanCallback);
}

It is producing zero results. Even if I set all mask values to 0 (which is the number for ignore) it still produces zero results. When I remove the filter, plenty of results beginning with 1 appear. Is this broken in the current version of Android?

A: Its not a fix for this problem, but I decided to filter by DeviceName instead, as this can be populated by both the Android and iOS sides. Right now I am focusing on iOS to Android communication =>
iOS:
func centralManager(_: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi: NSNumber){

    delegate?.didDiscoverPeripheral(peripheral)
    let splitUp : [String] = "\(advertisementData)".components(separatedBy: "\n")
    if (splitUp.count > 1)
    {
        var chop = splitUp[1]
        let counter = chop.characters.count - 2
        chop = chop[0..<counter]
        let chopSplit : [String] = "\(chop)".components(separatedBy: "\"")

        if !(chopSplit.count > 1 && chopSplit[1] == "Device Information" && !sending)
        {
            let hexString = chop[4..<7] + chop[12..<19] + chop[21..<26]
            let hexArray = [hexString[0..<1], hexString[2..<3], hexString[4..<5], hexString[6..<7], hexString[8..<9], hexString[10..<11], hexString[12..<13], hexString[14..<15], hexString[16..<17]]
            let charArray = hexArray.map { Character(hexToScalar(char: $0)) }
            let string = String(charArray) as String
            if (string == "GoTcHa" + stringify(number: writing))
            {
                writing += 1
                let messageUUID = StringToUUID(hex: String(writing) + "hello" + String(writing))
                peripheralManager.stopAdvertising()
                let name = String(writing) as NSString
                peripheralManager.startAdvertising([CBAdvertisementDataServiceUUIDsKey: [CBUUID(string: messageUUID)], CBAdvertisementDataLocalNameKey: name])
            }
        }
    }
}

func StringToUUID(hex: String) -> String
{
    var rev = String(hex.characters.reversed())
    let hexData: NSData! = rev.data(using: String.Encoding.utf8, allowLossyConversion: false) as NSData!
    rev = hexData.toHexString()
    while(rev.characters.count < 31) {
        rev = "0" + rev;
    }
    rev = String(writing % 10) + rev[0..<30]
    let finalString = rev[0..<7] + "-" + rev[8..<11] + "-" + rev[12..<15] + "-" + rev[16..<19] + "-" + rev[20..<31]
    return finalString
}

And more importantly the Android scanning method, which now ignores duplicate messages from iOS by always looking for the next message through the DeviceName:
private void freshen() {
    if (mLEScanner != null)
        mLEScanner.stopScan(mScanCallback);
    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
            .build();

    List<ScanFilter> filters = new ArrayList<>();

    ScanFilter filter = new ScanFilter.Builder()
            .setDeviceName("" + (reading % 10))
            .build();

    filters.add(filter);

    mLEScanner.startScan(filters, settings, mScanCallback);
}

I need to get the iOS side to filter Android's responses better now, but it is effective on the Android receiving side.


text:
Q: How to get records only if difference between them is 10 sec I need to be able to find all records with sql only if time between those less than 10 seconds.
Let me put a little example so you can see what I need:
id     method       db_add_date
1      5            2013-09-11 00:42:12
2      6            2013-09-11 00:42:25
3      4            2013-09-11 12:02:33
4      7            2013-09-11 12:02:35
5      1            2013-09-11 12:10:54
6      2            2013-09-11 12:10:57

And output like this:
id     method       db_add_date
3      4            2013-09-11 12:02:33
4      7            2013-09-11 12:02:35
5      1            2013-09-11 12:10:54
6      2            2013-09-11 12:10:57

because #3 & #4 has difference 2 seconds &
 #5 & #6 has difference 3 seconds
I am having difficulty in putting this into a SQL query form, I would appreciate any help on this!

A: Join the table to itself on a +/- 10 second timestamp range, making sure not to join to itself:
select distinct t1.*
from mytable t1
join mytable t2
  on t2.db_add_date between subdate(t1.db_add_date, interval 10 second)
    and adddate(t1.db_add_date, interval 10 second)
  and t2.id != t1.id

SQLFiddle demo
Points:

*

*this finds near rows by joining to itself

*if rows only come in pairs within 10 seconds (not more than two within 10 seconds) you can omit the distinct keyword

*if an index is on db_add_date this will perform well and scale well due to the way the look up time interval is determibant for the joined rows


text:
Q: how does django query work? my models are designed like so
class Warehouse:
    name = ...
    sublocation = FK(Sublocation)

class Sublocation:
    name = ...
    city = FK(City)

class City:
    name = ..
    state = Fk(State)

Now if i throw a query.
wh = Warehouse.objects.value_list(['name', 'sublocation__name',
    'sublocation__city__name']).first()

it returns correct result but internally how many query is it throwing? is django fetching the data in one request?

A: Django makes only one query to the database for getting the data you described.
When you do:
wh = Warehouse.objects.values_list(
    'name', 'sublocation__name', 'sublocation__city__name').first()

It translates in to this query:
SELECT "myapp_warehouse"."name", "myapp_sublocation"."name", "myapp_city"."name"
FROM "myapp_warehouse" INNER JOIN "myapp_sublocation"
ON ("myapp_warehouse"."sublocation_id" = "myapp_sublocation"."id")
INNER JOIN "myapp_city" ON ("myapp_sublocation"."city_id" = "myapp_city"."id")'

It gets the result in a single query. You can count number of queries in your shell like this:
from django.db import connection as c, reset_queries as rq

In [42]: rq()

In [43]: len(c.queries)
Out[43]: 0

In [44]: wh = Warehouse.objects.values_list('name', 'sublocation__name', 'sublocation__city__name').first()

In [45]: len(c.queries)
Out[45]: 1

A: My suggestion would be to write a test for this using assertNumQueries (docs here).
from django.test import TestCase

from yourproject.models import Warehouse

class TestQueries(TestCase):

    def test_query_num(self):
        """
        Assert values_list query executes 1 database query
        """
        values = ['name', 'sublocation__name', 'sublocation__city__name']
        with self.assertNumQueries(1):
            Warehouse.objects.value_list(values).first()

FYI I'm not sure how many queries are indeed sent to the database, 1 is my current best guess. Adjust the number of queries expected to get this to pass in your project and pin the requirement.

A: There is extensive documentation on how and when querysets are evaluated in Django docs: QuerySet API Reference.
The pretty much standard way to have a good insight of how many and which queries are taken place during a page render is to use the Django Debug Toolbar. This could tell you precisely how many times this recordset is evaluated.

A: You can use django-debug-toolbar to see real queries to db


text:
Q: Proof that convergent sequence in $\Bbb R$ is bounded. Convergent sequence in $\Bbb R$ is bounded. Proof:

In the definition of a convergent sequence:
$$(\forall \varepsilon>0), (\exists n_\varepsilon\in\Bbb N), (\forall n\in\Bbb N), ((n>n_\varepsilon)\Rightarrow(|a_n-a|<\varepsilon))$$
  let $\varepsilon=1$, then there exists $n_\varepsilon\in\Bbb N$ such
  that $(n>n_\varepsilon)\Rightarrow(|a_n-a|<1$). Now for
  $n>n_\varepsilon$ we have $|a_n|\leq|a_n-a|+|a|\leq 1+|a|$. Let
  $M=\max\{|a_1|,...,|a_{n_\varepsilon}|,1+|a|\}$ Then $\forall n\in\Bbb
> N, \ |a_n|\leq M$, i.e. the sequence is bounded.

What's the idea behind this proof? I understand the first part, but then when they define $M$ I'm lost. I don't see how is that related to the first part of the proof.

A: The idea behind this proof is to separate the values of the sequence into 2 parts : the ones that are close to the limit (within distance 1 of it) and the ones that are "far" from the limit.
By definition of convergent sequences, those last ones are in finite number, so the set of their absolute values is bounded, by a real $M$. And the set of the others is bounded by $|l|+1$.
So the whole set of absolute values is bounded by $\max(|l|+1,M)$.

A: The idea is that after a while (i.e., after $n_\epsilon$), the sequence is bounded by $1+|a|$, and before that, the sequence is finite so it is bounded by the largest element.
What you do is you split the sequence into two parts, a starting part and "the rest"

*

*The starting part, $a_1,a_2,\dots, a_{n_\epsilon}$, is clearly bounded by $M_1=\max\{a_1,a_2,\dots, a_{n_\epsilon}\}$. It's bounded by $M_1$ because $M_1$ is the largest element of a finite set, and so it must be larger than all elements of that set.

*The rest of the sequence, $a_{n_\epsilon+1}, a_{n_\epsilon+2},\dots$, is infinite, so we can't just take its max. However, we know and can show that this part must be bounded by $M_2=1+|a|$.

Now, the first part of the sequence is bounded by $M_1$, and the second by $M_2$, so both together must be bounded by $\max\{M_1,M_2\}$, since $M\geq M_1, M_2$.

For example, you need to define $M$ because $1+|a|$ may not be the upper limit of the entire sequence. For example, the sequence $\frac2n$ has a limit of $0$, but the sequence is not bounded by $1+|0|$ since $2$ is also a part of the sequence.
However, the sequence is bounded by $\max\{2, 0+1\}=2$.

A: We want some $M>0$ so that $|a_n|\leq M$ for all $n\in\Bbb N$ and if this happens, we say that the sequence $(a_n)$ is bounded. Now, you already mentioned that
$$|a_n|<1+|a|\quad\text{for  }n=n_{\epsilon}+1,n_{\epsilon}+2,n_{\epsilon}+3,\dots.\tag{$*$}$$
What we gonna do to the numbers $|a_1|,|a_2|,|a_3|\dots,|a_{n_{\epsilon}}|$? This give an idea of  taking
$$M=\max\{|a_1|,...,|a_{n_\varepsilon}|,1+|a|\}.$$ So, using the definition of our $M$ together with $(*)$, we get
$$\begin{align}
&|a_1|\leq M\\
&|a_2|\leq M\\
&|a_3|\leq M\\
&\quad\vdots\\
&|a_{n_{\epsilon}}|\leq M\\
&|a_{n_{\epsilon}+1}|< 1+|a|\leq M\\
&|a_{n_{\epsilon}+2}|< 1+|a|\leq M\\
&|a_{n_{\epsilon}+3}|< 1+|a|\leq M\\
&\quad\vdots\\
\end{align}$$
With the above, we conclude that $|a_n|\leq M$ for all $n\in\Bbb N$.

A: See the main idea is that ,, by the convergence  property , you get a bound of an infinite part of the sequence  i.e of all the $x_n$'s after some stage.
Now then the bound becomes easy to define , just take the maximum of all the $x_n$'s before that particular $N_0$  with the bound you have got for the infinite part. Hence the bound of the sequence gets defined.


text:
Q: Why constrain to interface in generic typing? What would be the point of making a constraint for an interface type on a generic in C#?  For example,
public interface IHandler<in T>
    where T : IProcessor
{
    void Handle(T command);
}

Wouldn't it be better to simply inherit IProcessor as a generic without any constraints?  What is the advantage of doing it this way?
For example,
public class FooProcessor : IProcessor<T>
{
    void Handle(T command)
    {
    }
}

A: If the interface is blank then it is a marker interface.
It can be used for applying restrict about the class, outside of the class. In keeping with the example below you can restrict a decorator to only be able to decorate Handlers of IProcessor.

A very valid reason is when applying a decorator:
Let's say the command parameter interface has a couple of properties:
public interface IProcessor
{
    int Id { get; }
    DateTime Date { get; }
}

We can define a decorator over all handlers of IProcessor commands that have the knowledge that all the command parameters have Id and Date:
public sealed class HandlerLogger<in T> where T : IProcessor
{
    private readonly ILogger logger;
    private readonly IHandlerLogger<T> decorated;

    public HandlerLogger(
        ILogger logger,
        IHandlerLogger<T> decorated)
    {
        this.logger = logger;
        this.decorated = decorated;
    }

    public void Handle(T command)
    {
        this.logger.Log(command.Id, command.Date, typeof(T).Name);
        this.decorated.Handle(command);
    }
}

A: There are different architectural patterns that can be used to pragmatically enforce types.
For example, if you were designing an API and you wanted to allow someone to extend it but you wanted to make sure that the class that was being created to extend your framework was a certain type and had a default parameterless constructor.  Using generic typed interfaces is a common way to do this.
I have created a quick example adhoc to give a relatively simple overview of why a typed interface is useful in some models / architectural design.
public class UnitOfWorkManager<T>
{
    private readonly IDataRepository _dataRepository;
    private List<T> _unitOfWorkItems;

    public UnitOfWorkManager(IDataRepository dataRepository)
    {
        _dataRepository = dataRepository;
    }

    public void AddUnitOfWork(IUnitOfWork<T> unitOfWork)
    {
        this._unitOfWorkItems.Add(unitOfWork);
    }

    public void Execute()
    {
        WorkerItem previous = null;
        foreach (var item in _unitOfWorkItems)
        {
            var repoItem = _dataRepository.Get(item.Id);
            var input = new WorkerItem(item.Id, repoItem.Name, previous);
            previous = input;
        }
    }
}

public interface IUnitOfWork<T>
    where T: WorkerItem, new()
{
    string Id { get; }
    void Execute(T input);
}

public class WorkerItem
{
    public WorkerItem(string id, string name, WorkerItem previous)
    {
        this.Name = name;
        this.Id = id;
        this.Previous = previous;
    }
    public string Id { get; private set; }
    public string Name { get; private set; }
    public WorkerItem Previous { get; private set; }
}

Hope this helps.


text:
Q: Navigation Controller between view controller and table view controller Any ideas on how to add a Navigation Controller in iOS7 between a Table View and View Controller?
As soon as I embed the Navigation Controller to the table view the app crashes.
Without the Navigation Controller it works fine. But then the Table View becomes a View Controller. This is the code I'm using:
[self.navigationController performSegueWithIdentifier:@"setup" sender:self];

Here is my storyboard: http://sv.tinypic.com/r/1ztdnb/8

A: Okay, giving the comments here is what I think you want:

*

*A LoginViewController which is a subclass of a UITableViewController. Should not display navigationBar.

*A ProfileViewController also a subclass of a UITableViewController. Should display a navigationBar.

*When a user taps LogIn button, ProfileViewController should be "pushed".

So the whole trick is to make navigation bar hidden for one view controller and visible for another. Well this is very easy to achieve - just use  setNavigationBarHidden:animated: in viewWillAppear: for each view controller
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self.navigationController setNavigationBarHidden:YES/NO animated:animated];
}


text:
Q: How to show different controls based on selection(s) I have a user control that has a list of items.
If an item is selected, I want to show/replace the view with a panel and some buttons and what not.
When the user has finished with this view by pressing a button or something, I want to revert back to the list again and continue the process.
Essentially, this is a wizard.
What to do?
Sorry, I forgot to mention that I am using MVVM.
Solution:
Thanks to all for the help.  My test application wasn't working which prompted me to ask SO.
My test application wasn't working because I had missed the {x:type} in the DataTemplate.
To simply:
I created different datatemplates in the resources with the {x:Type}
My viewmodel:
contained a compositecollection of IWizardPageViewModel.
contained a currentPage property.
contained NextCommand/BackCommand to change the currentPage
I bind the currentPage property to the control and the datatemplates take over.
Because of the {x:Type} it wasn't working.
I don't know whether this is right or wrong, but it works and is mostly controlled by the viewmodel rather than triggers on the view.

A: First thing that comes to my mind (and easiest) is to use Visibility property and bind it to some boolean flags in ViewModel that will indicate current UI state. Of course in this case you should apply a Converter to properly convert bool value to Visibility. There are dozens of examples of such kind of convertors.
But this is relevant only in for of small amount of such Controls. In case of really lots of UI elements that should be shown and replaced on a view it's better to use framework like Prism. From scratch it will be not so straightforward, but then you'll feel all power of flexibility.
In case you're not following MVVM culture (or you don't like having such backing properties) you can bind Visibility property of control A that should be shown to Booleaen property of element B which stands for show/hide logic. To make it clear:
<TextBlock x:Name="A" Visibility="{Binding IsChecked, ElementName=B, Converter={StaticResource boolToVisibilityConverter}}" Text="Some text."/>
<ToggleButton x:Name="B" IsChecked="False"/>

A: You can use Triggers and Selectors to update the view (DataTemplate) based on user actions.
Let me know if you need code snippet for the same.

A: Consider a list of usercontrols - one for each page of your wizard. The top level usercontrol (the wizard control) will own this list. For navigation, you can;

*

*Have buttons on the top level wizard usercontrol. When pressed, these notify the children of the navigation so that they can finish their work or cancel the navigation. You will want a common interface for the pages. IWizardPage perhaps?

*Use a routed commands to notify the wizard usercontrol http://msdn.microsoft.com/en-us/library/ms752308.aspx#Four_main_Concepts


text:
Q: Install dependency's extras if package's specific extras is requested My project has Celery as a dependency. It's a hard dependencies, ie. my project can't live without it. However, it can use Redis as its backend, which my app doesn't need specifically.
I want my package to be set up so if a user installs dependencies with poetry install -E redis, it would install the redis block of Celery (as if it were specified in pyproject.toml as celery = { version="^4.4.0", extras=["redis"] }).
However, if a user uses a plain poetry install (without -E redis), i don't want Celery's Redis dependencies (as if it were only specified as celery = "^4.4.0") to be installed.
Is there a way to put this into Poetry config? Or should I track the optional requirements of celery[redis] and manually add them to my pyproject.toml file?
I already checked the Poetry documentation on this matter, but it doesn't offer a way to specify the same dependency (celery in my case) with different options.

A: This should work by defining redis as an optional extra, e.g.:
[tool.poetry]
name = "mypackage"
version = "0.1.0"
description = ""
authors = ["finswimmer <finswimmer@example.org>"]

[tool.poetry.dependencies]
python = "^3.6"
celery = "^4.4.7"
redis = { version = "^3.5.3", optional = true }

[tool.poetry.dev-dependencies]

[tool.poetry.extras]
redis = ["redis"]

[build-system]
requires = ["poetry>=1.0"]
build-backend = "poetry.masonry.api"


text:
Q: Animate UIView using Core Animation? I am having a little trouble getting a UiView to animate properly using core animation. Here is my code:
CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"position"];
[animation setFromValue:[NSValue valueWithCGPoint:self.view.layer.position]];
[animation setToValue:[NSValue valueWithCGPoint:CGPointMake(250, self.view.layer.position.y)]]; //I want to move my UIView 250 pts to the right
[animation setDuration:1];
[animation setDelegate:self]; //where self is the view controller of the view I want to animate
[animation setRemovedOnCompletion:NO];
[self.view.layer addAnimation:animation forKey:@"toggleMenu"]; //where self.view returns the view I want to animate

I have also implemented the following delegate method:
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    if(flag)
        [self.view.layer setTransform:CATransform3DMakeTranslation(250, 0, 0)]; //set layer to its final position
}

I am trying to make it so that the UIView moves 250 points to the right. However, when the animation is triggered, my view starts to move but the animations seems to end before the view moves 250 points to the right, resulting in the UIView 'teleporting' to its final position. I can't seem to figure out what is causing this behavior.
I have also tried using the UIView method +(void)animateWithDuration:animations: and this approach works perfectly. However, I am trying to achieve a subtle 'bounce' effect and I'd much rather achieve it using the setTimingFunction:functionWithControlPoints: method rather than having multiple callbacks.
Any help and suggestions are appreciated.

A: *

*Try like this

CABasicAnimation *rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"position"];

    rotationAnimation.fromValue=[NSValue valueWithCGPoint:CGPointMake([view center].x, [view center].y)];
    rotationAnimation.toValue=[NSValue valueWithCGPoint:CGPointMake([view center].x+250, [view center].y)];

    rotationAnimation.duration = 1.0+i;
    rotationAnimation.speed = 3.0;

    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = 1.0;
    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];

    [view.layer addAnimation:rotationAnimation forKey:@"position"];

A: If you are aiming to move your view, your code should go like this:
CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"position"];
[animation setFromValue:[NSValue valueWithCGPoint:self.view.layer.position]];
CGPoint p = self.view.layer.position;
p.x += 250;
self.view.layer.position = p;
[animation setDuration:1];
[animation setRemovedOnCompletion:NO];
[self.view.layer addAnimation:animation forKey:@"toggleMenu"];

You should really change your view's(layer's) position. Otherwise, your view will stay still at its previous position when your animation removed. That's a difference between UIView Animation and Core Animation.

A: CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"position"];
[animation setFromValue:[NSValue valueWithCGPoint:view.layer.position]];
CGPoint newPosition = CGPointMake(200, 300);
view.layer.position = p;
[animation setDuration:0.5f];
[animation setRemovedOnCompletion:NO];
[group setFillMode:kCAFillModeForwards];
[[view layer] addAnimation:animation forKey:@"position"];