text:
Q: Simultaneous scanning of barcodes and text(OCR) in xamarin I have a scanner app where we scan the barcodes and Text on the same camera. I have done this in xamarin with the help of Xamarin.Firebase.IOS.MlKit.
In this when the camera is open, we do continous capturing of image frames, and send the captured image for barcode detection and OCR recognition seperately.
 public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection)
            {
                lastRunTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
                if (lastRunTime - lastAnalysisTime > scanIntervalInMs)
                {
                    lastAnalysisTime = lastRunTime;
                    try
                    {
                        var image = GetImageFromSampleBuffer(sampleBuffer);
                        if(image == null) return;
                        var visionImage = new VisionImage(image) {Metadata = metadata };
                        releaseSampleBuffer(sampleBuffer);
                        if(isScanningBarcode)
                        {
                            DetectBarcodeActionAsync(visionImage);
                            isScanningBarcode = false;
                        }
                        else
                        {
                            isScanningBarcode = true;
                            DetectTextActionAsync(visionImage);
                        }

                    }
                    catch (Exception exception)
                    {
                        System.Diagnostics.Debug.WriteLine(exception.Message);
                    }
                }
                releaseSampleBuffer(sampleBuffer);
            }

//Barcode detection
private async void DetectBarcodeActionAsync(VisionImage image)
 {
      VisionBarcode[] barcodes = await barcodeDetector.DetectAsync(image);
 }

//OCR
private async void DetectTextActionAsync(VisionImage image)
{
     VisionText txt = await textRecognizer.ProcessImageAsync(image);
}

This runs properly. But our app is used in package scanning to scan address labels (names of the recipient) and barcodes. So, when the barcodes are damaged or curved/skewed, this MLKit barcode fails to scan such barcodes, and this is quite frustrating for the clients.
Is there a way we can improve upon the MLKIt barcode scanner to scan such damaged barcodes.
I tried the same with some premium scanners like ScanBot and SCandit demo apps, which were able to scan the damaged barcodes quite easily. I had a talk with ScanBot customer service, but they do not provide SIMULTANEOUS barcode and OCR scanning. I am also looking in this ScanDit SDK to accomplish the same.
Can anyone suggest some premium scanners for xamarin app which scans barcodes and OCR in one go. OR any improvements which can be made to existing MLKit scanner so that it can scan damaged/skewed barcodes.


text:
Q: Infinite loop with 'char' type input I am learning binary search tree. Given below is the main function of a program to perform basic BST operations. The option variable chooses which operation to perform for switch
int main()
{
struct node* tree=NULL;
struct node* ptr=NULL;
struct node* ptrm=NULL;
int val;
int option;
do
{
    printf("\n1.Insert Node\n2.Preorder Traversal\n3.Postorder Traversal\n4.Inorder Traversal\n5.find_smallest_element\n6.find_largest_element\n7.Delete Element\n8.Total_nodes\n9.total_external_nodes\n10.total_internal_nodes\n11.Mirror image\n12.Exit\n");
    printf("\nEnter option");
    scanf("%d",&option);
    switch(option)
    {
        case 1:
            printf("\nEnter value to be inserted");
            scanf("%d",&val);
            tree=insert_element(&tree,val);
            printf("\n%d Inserted\n",val);
            break;
        case 2:
            preorder(&tree);
            break;
        case 3:
            postorder(&tree);
            break;
        case 4:
            inorder(&tree);
            break;
        case 5:
            ptr=find_smallest_element(&tree);
            printf("\nSmallest element:%d",ptr->data);
            break;
        case 6:
            ptr=find_largest_element(&tree);
            printf("\nLargest element:%d",ptr->data);
            break;
        case 7:
            printf("\nEnter value of element to be deleted");
            scanf("%d",&val);
            tree=delete_node(&tree,val);
            break;
        case 8:
            printf("\nTotal nodes%d",total_nodes(&tree));
            break;
        case 9:
            printf("\nTotal External nodes%d",total_external_nodes(&tree));
            break;
        case 10:
            printf("\nTotal Internal nodes%d",total_internal_nodes(&tree));
            break;
        case 11:
            ptrm=mirror_image(&tree);

    }
}while(option!=12);
return 0;

Everything works fine when i give int data as input for 'option'.However, when i give a char input the program goes into infinite loop and displays option list repeatedly.
Why does this happen?

A: Since you used %d format specifier in the scanf() format string,
scanf("%d",&val);

will successfully assign to val only if an integer was given as the input. If a char is given instead, scanf() (which returns the number of successful assignments) will return 0 here and will leave the char in the input buffer unconsumed.
During the next iteration of the loop, this char would still be in the input buffer and scanf() would end up trying to read the same thing and will won't assign to val once again.
This will go on and on resulting in an infinite loop.
To solve this, check the value returned by scanf(). If it is not 1, clear the input buffer till the next \n (newline) like
int t;
while( (t=getchar()) != `\n` );

This will consume the old data till a \n from the input buffer.
You could then use the continue statement to skip the rest of that iteration of the loop.
Read about getchar() here.

A:
Why does this happen?

The roots of this issue stem all the way back to how scanf indicates error codes to your code (not at all, because your code discards them), and what scanf("%d", &val) is expected to do when non-decimal input is encountered; it stops reading input, possibly returning an error code, but your code discards that and continues on merrily trying to delete the node indicated by the value which may not have been read, leading to possible use of an uninitialised variable later...
Some people take the guessing to an extreme, and think it's appropriate to use fflush(stdin) to solve this (it isn't; don't do that...). You've not gone that far, but I think it might be a good idea to start reading the manuals of the functions you're using. The scanf manual is here. Make note of that URL, and realise that you can look up other standard functions (both C99 and POSIX standard) by substituting the name of the function.
The first thing your code must do is check that return value, which your manual will document in the RETURN VALUES section; as with most standard library functions, scanf has a return value which your code should most likely contain critical logic regarding! From there, how you handle errors is your business. Perhaps it might be appropriate to use something simple yet user-unfriendly, like:
perror(scanf);
exit(EXIT_FAILURE);

You should seek the simpler solutions where possible, to avoid overcomplicating things. If your input doesn't come directly from the user, or you just want to prototype, you should use the solution above. You can always change exit(EXIT_FAILURE) to return EXIT_FAILURE; and return 0; on success, if necessary later.
If you choose to keep your program running, how much of the user input gets discarded due to the typo is up to you. By far the simplest option is to just read a single character (using getchar();)...
You could choose to discard a word of input, like so: scanf("%*s");. The * informs scanf to read and discard the input, rather than reading and assigning.
Neither of those options strike me as being particularly user-friendly. If you're going to the effort of making a user-friendly interface, you'll probably want to choose one of the following options.
Using the * assignment-suppression modifier, you can also discard a line of input, like so:
scanf("%*[^\n]");
getchar();

The getchar(); is necessary to discard the newline character, which we expect to be discarded when a line is discarded.
Using the command line arguments for your input, rather than using stdin (or other files/streams). Some surprisingly simple yet versatile menus have been produced this way, such as the ones your compiler presents to you. Your mode of input then changes to using friendlier functions such as sscanf, and developing your program not as a looping program that remains open, but as an instant program which gets executed every now and then, when necessary, to update records or what-not.
Using the graphical user interface instead of the console. Well, that one really makes the ol' noggin' flog, eh? You could use... a context menu such as the File/Edit/etc menus in Windows, or a listbox (which would be more touch-screen friendly) to prompt your user for a selection.
Suffice to say, this looks like homework, so you probably don't have the choice to design a more appropriate user interface... In this case, I suggest using the * assignment-suppression modifier as per above (the first bolded section).

redpajama_set_name: RedPajamaStackExchange


text:
Q: XPath: How to select script between other scripts with no attributes? I try to select a specific script on the adobe air download site
https://get.adobe.com/de/air/download/?installer=Adobe_AIR_30.0_for_Win32&stype=7645&standalone=1 (look out download should start)
Problem is the script I'm trying to get has no attributes and is between some other scripts.

  <script type="text/javascript" src="https://wwwimages2.adobe.com/uber/js/pdc_s_code.js"></script>
   <script src="//assets.adobedtm.com/659ec8ada5450db95675e43beaaae92399591a11/satelliteLib-7123a14bc11ffd1ad43be190a593a8932494dcb0.js"></script>

             <script>

     setTimeout("location.href = 'https://airdownload.adobe.com/air/win/download/30.0/AdobeAIRInstaller.exe';", 2000);

                $(function() {
                    $("#whats_new_panels").bxSlider({
                        controls: false,
                        auto: true,
                        pause: 15000
                    });
                });
                setTimeout(function(){
                    $("#download_messaging").hide();
                    $("#next_button").show();
                }, 10000);
            </script>
            <script type="text/javascript" src="https://wwwimages2.adobe.com/downloadcenter/js/live/polarbear.js"></script>

I'm able to get the first and fourth one with
/html/body/script[1] and
/html/body/script[2]
but I don't know how to get the one I actually need.

A: Try to use
//script[not(@*)]

to select script node with no attributes


text:
Q: Understanding Ninject mvc 3 boiler plate code If you install the nuget Ninject package for mvc, it puts a NinjectWebCommon.cs file in the App_Start folder.
I understand 99% of the stuff in this file apart from this line:
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);

Full code file here on GitHub
In my mind, it would be better to use:
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => bootstrapper.Kernel);

As the static instance is already defined at the top of the file, and thus it will get the kernal that has all the mappings built.
After some googling it seems this is also common:
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => ctx.Kernel);

What is the reasoning behind the way the boilerplate code is the way it is?

A: The binding for
"Func<IKernel>>"

Is used to inject a fresh instance of IKernel into the Bootstrapper.Initialize method.
The idea behind creating a new Bootstrapper, is that the Bootstrapper constructor should construct a fully initialized instance of IKernel. That new instance will be used to replace the old instance of the IKernel.
The assumption appears to be that, when the Initialize method is called, you would want to completely reset the IKernel instance in the Bootstrapper instance, removing any bindings added prior to calling Initialize.
Therefore, if you want to do something other than reset your kernel when the application starts, you should refacter the code in the lambda expression, so that a kernel is passed the Bootstrapper.Initialize with the desired state.
I hope this is helpful.


text:
Q: JVM backward compatibalitty If I have class A that is compiled in Java 1.6
I have class B that is compiled in Java 1.7
In its main method class A invokes a method of class B.
If I run class A under java JVM of version 1.7, everything works well.
May I get an explanation for that?

A: All classes compiled under java version 1.6, is supported and runnable by java version 1.6+, including version 1.7, 1.8, etc.
On the other hand, you can't run a program compiled in java 1.7 with a 1.6-JRE.
It's the backward compatibality principle


text:
Q: How do I dynamically choose an excel sheet to reference in a formula? I have an xlsx with sheets named "A", "B", "C", etc.  I need to form a table with the names "A", "B", "C" as the first column, and some data from the same cell in each sheet as the second column.  So for example, this might look like:
   Sheet          Data
   A              =A!C2
   B              =B!C2

In my "Data" column, is there some way to reference the names "A" and "B" from the "Sheet" column, so I can just fill the forumla in once and have it update as I add more sheets?

A: Assuming your sheet name A is in A2 - use this in B2: =INDIRECT("'"&A2&"'!C2")


text:
Q: JavaScript click div to show hidden content animation I am working on this JavaScript animated accordion, trying to get it to where when a Section div is clicked, a hidden panel slides down from behind it to reveal hidden content. Then when the bar is clicked again, the hidden area slides back up and becomes hidden again. This is almost working the way I need it to apart from a couple of issues that I haven't been able to solve.

*

*The vertical distance between the section bars should remain
consistent before and after the hidden area is revealed or hidden.
Right now, there is an undesired margin between them.

*When the hidden area slides back up to be hidden again, it needs to
slide all the way up so that the border of the hidden area also
disappears.

I believe there are a couple of small changes to my JavaScript/css code that could enable this to work properly, I just haven't been able to find them.
Here is what my code looks like:

var acc = document.getElementsByClassName("bar");
var i;

// For each bar
for (i = 0; i < acc.length; i++) {

  // If this bar is clicked
  acc[i].addEventListener("click", function() {

    // Toggle the clicked bar to "active"
    this.classList.toggle("active");

    // Panel will consist of the next hidden content
    var panel = this.nextElementSibling;
    var bar = this.nextElementSibling.nextElementSibling;
    console.log("hidden height:", panel.getBoundingClientRect().height)

    // Use logic to change CSS styles for the selected bar
    if (panel.style.maxHeight){

      var closeHeight = panel.getBoundingClientRect().height;
      console.log("close height", closeHeight)
      var newHeight = (closeHeight - 80) + "px";
      panel.style.height = newHeight
      console.log("close height after adjustment", newHeight)

      // panel.style.border = 'none';
      panel.style.maxHeight = null;
      console.log("close maxheight", panel.style.maxHeight)

      // panel.style.maxHeight = '0px';

      // panel.style.padding = '0 18px';
      panel.style.paddingTop = '80px';
      panel.style.border = 'solid 1px #aaa';

      bar.style.marginTop = '-15px'
      // panel.style.border = 'none';

    } else {
      // bar.style.marginTop = '15px'
      panel.style.border = 'solid 1px #aaa';
      panel.style.paddingTop = '80px';
      panel.style.maxHeight = panel.scrollHeight + "px";
      console.log("open maxheight", panel.style.maxHeight)
      console.log("open height", panel.getBoundingClientRect().height)
    }
  });
}
.bar {
  width: 350px;
  height: 90px;
  border-radius: 8px;
  padding: 20px;
  font-size: 24px;
  margin: 70px 15px 15px 15px;
/*   margin: 15px 15px 15px 15px; */
  z-index: -2;
  background-color: #eee;
  color: #444;
  cursor: pointer;
  border: 1px solid #444;
  text-align: left;
  outline: none;
  font-size: 16px;
/*   transition: 0.4s; */
  transition: 3.4s;
}

.active, .bar:hover {
  background-color: #ccc;
}

.hidden {
  width: 340px;
/*   height: 370px; */
/*   border: solid 1px #aaa; */
  border-radius: 8px;
  margin: -80px 0px 15px 0px;
  padding: 0 18px;
  max-height: 0;
  overflow: hidden;
/*   transition: max-height 0.2s ease-out; */
  transition: max-height 3.2s ease-out;
}
<button class="bar">Section 1</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

<button class="bar">Section 2</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
    incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
    exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
    incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
    exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
    incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
    exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

<button class="bar">Section 3</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

This is also visible on codepen:
https://codepen.io/Chris_Nielsen/pen/Lozedd

A: Because CSS + javascript is so powerful nowadays, the need of JQuery is unnecessary.

*

*I removed lots of javascript code.

*I added .information as a class to all .hidden divs.

*I added an extra div inside the .hidden.information div. I'm using this to calculate the real height of the hidden text blocks.

*I finally added a CSS variable so you only need to change the displacement of the .hidden.information text blocks in one place.

var acc = document.getElementsByClassName("bar");
var i

// For each bar
for (i = 0; i < acc.length; i++) {
  // If this bar is clicked
  acc[i].addEventListener("click", function() {
    // Toggle the clicked bar to "active"
    this.classList.toggle("active");

    var panel = this.nextElementSibling;

    if (!panel.style.maxHeight) {  // add only once
     var elementDisplacement = getComputedStyle(panel).getPropertyValue("--element-displacement");
     elementDisplacement = Number( elementDisplacement.replace("px", "") );

     var panelChildHeight = panel.firstElementChild.getBoundingClientRect().height;
     panel.style.maxHeight = panelChildHeight + elementDisplacement + "px";
    }

    panel.classList.toggle("hidden");
  });

}
.bar {
  width: 350px;
  height: 90px;
  border-radius: 8px;
  padding: 20px;
  font-size: 24px;
  margin: 70px 15px 15px 15px;
  z-index: -2;
  background-color: #eee;
  color: #444;
  cursor: pointer;
  border: 1px solid #444;
  text-align: left;
  outline: none;
  font-size: 16px;

}

.active, .bar:hover {
  background-color: #ccc;
}

.information {
  --element-displacement: 80px;

  width: 340px;
  border-radius: 8px;
  margin: calc(-1 * var(--element-displacement)) 0px 15px 0px;
  padding: 0 18px;
  padding-top: var(--element-displacement);
  border: 1px solid #aaa;
  max-height: initial;
  overflow: hidden;
  transition: max-height 1s ease-out;
}

.hidden {
  max-height: 0px !important;
  border-color: transparent;
}
<button class="bar">Section 1</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

<button class="bar">Section 2</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
    incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
    exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
    incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
    exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
    incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
    exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

<button class="bar">Section 3</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.


text:
Q: Is it possible to use pyparsing for nested calls in a string? I'm developing a parser for a config format that also uses functions and I'm trying to figure if it's possible to use pyparsing for this task.
My input is
%upper(%basename(filename)fandsomemore)f%lower(test)f _ %lower(test2)f

and the finite result should be
FILENAMEANDSOMEMOREtest _ test2

In order to do this I first have to get the function names and arguments. My current code works only for the upper function and the nested basename and only if the "andsomemore" part is missing. The code is bellow:
from pyparsing import *

identifier = Word(alphas)
integer  = Word(nums)
functor = identifier
expression = Forward()

lparen = Literal("%").suppress() + functor + Literal("(").suppress()
rparen = Literal(")f").suppress()

argnrec = identifier | integer
arg = Group(expression) | argnrec
args = arg + ZeroOrMore("," + argnrec)
expression << Group(lparen + args + rparen)

print expression.parseString("%upper(%basename(filename)f)f%lower(test)f%lower(test2)f")
print expression.parseString("%upper(%basename(filename)fandsomemore)f%lower(test)f _ %lower(test2)f")

This works great for the first print and outputs, as expected
[['upper', [['basename', 'filename']]]]

For the second print I have an error:
pyparsing.ParseException: Expected ")f" (at char 27), (line:1, col:28)

Is there any way to get this to work with pyparsing? If not, any alternative approach would be appreciated. Also, keep in mind that this must handle more complex arguments, like windows paths (the current code only works for alphas and numbers)
Later update:
The purpose for this is to be able to insert the functions anywhere in a string. Another possible usage would be:
 %upper(this)f is a %lower(TEST)f and m%upper(%lower(ORE)f)f

That will result in the end to
THIS is a test and mORE

A: Just having a play here, I'm not entirely sure what you want but perhaps this will help?
from pyparsing import *

identifier = Word(alphas+nums+'_')
integer  = Word(nums)
functor = identifier
expression = Forward()

lparen = Literal("%").suppress() + functor + Literal("(").suppress()
rparen = Literal(")f").suppress()

term = (lparen + expression + rparen) | identifier
#args = term + ZeroOrMore("," + argnrec)
expression << OneOrMore(term)

print(expression.parseString("%upper(%basename(filename)f)f%lower(test)f%lower(test2)f"))
print(expression.parseString("%upper(%basename(filename)fandsomemore)f%lower(test)f _ %lower(test2)f"))

C:\temp>python test.py
['upper', 'basename', 'filename', 'lower', 'test', 'lower', 'test2']
['upper', 'basename', 'filename', 'andsomemore', 'lower', 'test', '_', 'lower', 'test2']


text:
Q: Write to mutiple 3Dtextures in fragment shader OpenGL I have a 3D texture where I write data and use it as voxels in the fragment shader in this way:
#extension GL_ARB_shader_image_size : enable
...
layout (binding = 0, rgba8) coherent uniform image3D volumeTexture;
...
void main(){
vec4 fragmentColor = ...
vec3 coords = ...
imageStore(volumeTexture, ivec3(coords), fragmentColor);
}

and the texture is defined in this way
glGenTextures(1, &volumeTexture);
glBindTexture(GL_TEXTURE_3D, volumeTexture);
glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA8, volumeDimensions, volumeDimensions, volumeDimensions, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

and then this when I have to use it
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_3D, volumeTexture);

now my issue is that I would like to have a mipmapped version of this and without using the opengl function because I noticed that it is extremely slow. So I was thinking of writing in the 3D texture at all levels at the same time so, for instance, the max resolution is 512^3 and as I write 1 voxel VALUE in that 3dtex I also write 0.125*VALUE for the 256^3 voxel and 0.015625*VALUE for the 126^3 etc. Since I am using imageStore, which uses atomicity all values will be written and using these weights I would automatically get the average value (not exactly like an interpolation but i might get a pleasing result anyway).
So my question is, what is the best way to have multiple 3dtextures and writing in all of them at the same time?

A: I believe hardware mipmapping is about as fast as you'll get. I've always assumed attempting custom mipmapping would be slower given you have to bind and rasterize to each layer manually in turn. Atomics will give huge contention and it'll be amazingly slow. Even without atomics you'd be negating the nice O(log n) construction of mipmaps.
You have to be really careful with imageStore with regard to access order and cache. I'd start here and try some different indexing  (eg row/column vs column/row).
You could try drawing to the texture the older way, by binding it to an FBO and drawing a full screen triangle (big triangle that covers the viewport) with glDrawElementsInstanced. In the geometry shader, set gl_Layer to the instance ID. The rasterizer creates fragments for x/y and the layer gives z.
Lastly, 512^3 is simply a huge texture even by todays standards. Maybe find out your theoretical max gpu bandwidth to get an idea of how far away you are. E.G. lets say your GPU can do 200GB/s. You'll probably only get 100 in a good case anyway. Your 512^3 texture is 512MB so you might be able to write to it in ~5ms (imo this seems awfully fast, maybe I made a mistake). Expect some overhead and latency from the rest of the pipeline, spawning and executing threads etc. If you're writing complex stuff then memory bandwidth isn't the bottleneck and my estimation goes out the window. So try just writing zeroes first. Then try changing the coords xyz order.

Update: Instead of using the fragment shader to create your threads, the vertex shader can be used instead, and in theory avoids rasterizer overhead though I've seen cases where it doesn't perform as well. You glEnable(GL_RASTERIZER_DISCARD), glDrawArrays(GL_POINTS, 0, numThreads) and use gl_VertexID as your thread index.


text: Q: Can I only write assembly code for my computer architecture/instruction set? I was just wondering if I could only write assembly code that is specific to my processor? Would I have to download a VM of the instruction set that I am targeting to be able to write assembly code for that?


text:
Q: Cocos2d with ARC: what is the best implementation of singleton pattern for GameScene when having multiple levels? EDIT: I am using ARC
In my code (based on the ShootEmUp example in this book, which I highly reccomend, source code in chapter 8 available here) I often use the trick of accessing the GameScene via:
+(GameScene*) sharedGameScene;
which returns a reference to the static instance of GameScene and is used by all children of GameScene (e.g. ShipEntity, InputLayer.. etc..) to dialog with GameScene (EDIT: aka singleton instance of GameScene).
To create multiple levels I thought of implementing a method calledsceneWithId:(int) method where I load different level data each time.
EDIT: Code snippet of init method:
-(id) initWithId:(int)sceneId
{
    CCLOG(@"scene With id");
    if ((self = [super init]))
    {
     //All common initialization happens here..
     switch (sceneId) {
        case 1:
            [self loadFirstLevelData];
            break;
        case 2:
            [self loadSecondLevelData];
            break;
        default:
            [self loadSecondLevelData];
            break;
    }
    //Other common stuff..
    [self setUpCounters];
    [self setUpWeaponsMenu];
    [self scheduleUpdate];
    [self schedule:@selector(timerUpdate:) interval:1];
    InputLayerButtons* inputLayer = [InputLayerButtons node];
    [self addChild:inputLayer z:1 tag:GameSceneLayerTagInput];
}

EDIT: Is that init method ok? I have found this post which uses  dispatch_once. Should I do the same?
Or should I pheraps create a GameScene class and then sublcass it?
E.g. FirstGameScene : GameScene

EDIT: I have followed the advice of @LearnCocos2D and used the cleanup method, and I used it to stop a singleton object music layer to play (the MusicLayer object is initialized in AppDelegate and I meant to use it to "manage" the music across all scenes - the problem was that without stopping it in dealloc it would have kept playing the music that was loaded at init time).
-(void) loadFirstLevelData{
//HERE WILL LOAD ALL SPECIFIC ELEMENTS: ENEMIES, BONUSES etc..

//AS WELL AS THE MUSIC FOR THE LEVEL
[[MusicLayer sharedMusicLayer] _loadMusic:@"1.mp3"];
[[MusicLayer sharedMusicLayer] playBackgroundMusicFile: @"1.mp3"];
}

-(void) cleanup
{
    //Should I remove all child loaded in LoadLevelData??
    CCLOG(@"cleanup GameScene");
    [[MusicLayer sharedMusicLayer] stopAllMusic];
    //MusicLayer is not a child of GameScene but of AppDelegate - the idea is to keep loading and unloading music files - sometimes I need to keep playing the file between scenes and hence I used the singleton pattern for this as well..
    [super cleanup];
}

But I still have some doubts:

*

*Is it ok to have several loadLevelData methods in GameScene class? Each method can be 200 lines long! I tried to sublcass GameScene but is a bit messy. I explain better. I imported "GameScene.h" in the header file of the subclass and by doing so I expected that if I had ovverriden only certain methods (e.g. init) I would have been able to see the various classes imported in GameScene (e.g. InputLayerButtons). It is not the case. So I probably don't understand how imports work in Objective-C

*Is it ok to remove specifc children in the cleanup method? I thought that I would remove all child that are added in the LoadLevelXXXData method to reduce the memory usage.
I have set a bounty for this question but I will probably need to test the answer and re-edit as I don't have a clear enough understanding of the subject to be super precise in the question. Hope is ok.
PS: Would be great if someone would feel like sharing a UML style diagram of a Cocos2D Shooter Game where with various levels and GameScene using singleton pattern :).

A: I'll focus on the questions on the bottom:

*

*Is it ok to have several loadLevelData methods in GameScene class? Each method can be 200 lines long! I tried to sublcass GameScene but
  is a bit messy. I explain better. I imported "GameScene.h" in the
  header file of the subclass and by doing so I expected that if I had
  ovverriden only certain methods (e.g. init) I would have been able to
  see the various classes imported in GameScene (e.g.
  InputLayerButtons). It is not the case. So I probably don't understand
  how imports work in Objective-C

There's nothing wrong with having long methods. However I suspect your loading methods perform very similar routines, so you should check if you can generalize these into subroutines. A good indicator is if several lines of code are absolutely identical except for the parameters or variable names. The best practice is to write identical code only once, and execute it many times with varying parameters.
The #import statement is used to allow the compiler to "see" other classes. Without importing other header files, you couldn't use that class' methods and properties without the compiler complaining.

2 . Is it ok to remove specifc children in the cleanup method? I thought that I would remove all child that are added in the
  LoadLevelXXXData method to reduce the memory usage.

It makes no sense to remove children during cleanup. Cocos2D removes all children during cleanup automatically.
If that does not seem to be the case for you, you have a retain cycle somewhere that prevents child nodes from deallocating.

A: sorry for answering this but I have been experimenting and decided to:

*

*not use the singleton pattern for GameScene

*use, insteada a singleton object to keep all shared data

My implementation draft for the GameScene (now called ShooterScene) is the following (I followed some advices in a cocos2d-iphone forum post as well as this other one ):
#import "ShooterScene.h"
#import "LevelData.h"
#import "HudLayer.h"

@interface ShooterScene (PrivateMethods)
-(void) loadGameArtFile;
@end

@implementation ShooterScene

+ (id) sceneWithId:(int)sceneId
{
    CCScene *scene = [CCScene node];

    ShooterScene * shooterLayer = [ShooterScene node];
    [scene addChild:shooterLayer];
    [shooterLayer loadGameArtFile];

    LevelData * levelData = [LevelData node];
    [shooterLayer addChild:levelData];

    switch (sceneId) {
        case 1:
            [levelData loadLevelDataOne];
            break;
        case 2:
            [levelData loadLevelDataOne];
            break;
        default:
            break;
    }

    HudLayer * hud = [HudLayer node];
    [hud setUpPauseMenu];
    [shooterLayer addChild:hud];

    return scene;
}

I am using the update method of ShooterScene to manage the all the game events (E.g. spawning, checking collisions, moving the background layer). I haven't put the full implementation here as is still work in progress, but is just to have an idea of the type of answer I am finding useful.


text:
Q: how to display name on multi series pie chart in chartjs
How to display some text on chart like show in image in place of text using chart js

A: You can use the datalabels plugin for this.

Chart.register(ChartDataLabels)

var ctx = document.getElementById('chart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ["Day 1", "Day 2", "Day 3"],
    datasets: [{
        label: 'working',
        data: [10, 5, 6],
        backgroundColor: ["red", "blue", "pink"],
        renderText: [null, "Hello", null]
      },
      {
        label: 'sleeping',
        data: [4, 2, 7],
        backgroundColor: ["red", "blue", "pink"],
        renderText: ["No", "Hello", null]
      },
    ]
  },
  options: {
    plugins: {
      datalabels: {
        color: 'white',
        formatter: (val, ctx) => (ctx.dataset.renderText[ctx.dataIndex])
      }
    }
  }
});
<div class="chart-view">
  <canvas id="chart" width="600" height="200" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.js"></script>
</div>


text:
Q: bucket sort Implementation without using vector,pointer and counting sort We want to use Bucket sort to sort numbers between 1 to 2001. the count of numbers can be 10E6.
I know the bucket sort algorithm. But the issue is that in this question, we are not permitted to use variable-length array, vector and pointer. (The only pointer related thing allowed is "pass by reference" of the array) The only solution I found is using using counting sort for each bucket, like the code below, so the code is more like counting sort than the bucket sort: (C language)
#include <stdio.h>
int buckets[201][10]={}; int numbers[1000001]={};

void bucket_sort (int a[],int n) {
    for (int i =0;i<=n-1;i++)
    {
        int index = a[i]/10, index2 = a[i]%10;
        buckets[index][index2]++;
    }
    int counter =0;
    for (int i =0;i<=200;i++)
    {
        for (int j =0; j<=9;j++)
        {
            while (buckets[i][j])
            {
                a[counter] = i*10+j;
                counter++;
                buckets[i][j]--;
            }
        }
    } }

int main() {
    int n;
    scanf("%d",&n);
    if (n==0)
    {
        return 0;
    }
    for (int i =0;i<=n-1;i++)
    {
        scanf("%d",&numbers[i]);
        numbers[i];
    }
    bucket_sort(numbers,n);
    for (int i =0;i<=n-1 ;i++)
    {
        printf("%d\n", numbers[i]);
    }
    return 0; }

I want to know can bucket sort be implemented without variable-length array, vector and pointer and also without counting sort. Probably using Insertion or Bubble sort. Note that it must be a reasonable bucket-sort algorithm. So defining  very big buckets like int bucket [201][1000000]; is also an unacceptable approach.

A: Given that you can't use variable length arrays or pointers, one of which is required for a bucket sort, your best bet is to go with a counting sort.  You only have 2000 possible values, so create an array of size 2000 and for each value you find increments the corresponding array element.
void counting_sort(int a[], int n)
{
    int count[2002] = { 0 };
    int i, j;

    for (i=0; i<n; i++) {
        count[a[i]]++;
    }

    for (i=0, j=0; i<n; i++) {
        while (!count[j]) {
            j++;
        }
        a[i] = j;
        count[j]--;
    }
}


text:
Q: Error 500 browsing to webpage which functions correctly on localhost I am having horrible trouble debugging a MVC ASP.NET webpage deployed to IIS. The website works perfectly on localhost on the PC where it has been made. When I navigate to the page on a different PC on the same network however, I get this error :

Further inspection with Fiddler2 gives me the following information, the only debug information I can seem to get from this solution:

Here is the Layout.cshtml :
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>@ViewBag.Title - Intranet Page</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")

@Html.ActionLink("IntranetPage", "Index", "Home")

            @RenderSection("featured", required: false)

                @RenderBody()

        @Scripts.Render("~/bundles/jquery")
        @RenderSection("scripts", required: false)

And the index page in question :
@model IEnumerable<WhoIs.Models.Employee>
@{
    ViewBag.Title = "Contoso Employees";
}
@section featured {

            <hgroup class="title">

@ViewBag.Title.

            </hgroup>

}

      Enter employee details here :
      <input type="text" name="filter" value="" id="filter" />

Users (create new)

Name	Branch	Phone No.	Username	Email

            @foreach ( var prod in Model )
                {

                        @prod.FullName
                        @prod.Branch
                        @prod.PhoneNo
                        @prod.DomainAC
                        @prod.Email
                        @if (User.IsInRole(@"Admins") || User.Identity.Name == prod.DomainAC) {
                                edit
                         }else{
                         User => @User.ToString()
                        }

                 }

These render a simple page with a list of employees at Contoso, giving Admins and users themselves the ability to edit their details. Can anyone see what may be causing my problem here ? I have investigated this thoroughly with no results.
I have a .edmx file added to my models folder which is linked to the remote database Employees. I have tried to edit the web.config to give more information on what may be the problem by adding the lines :

But I am still only getting the error message above.
Can anyone tell me what may be causing this problem please ? Commenting out the section where I retrieve from the database gets rid of the error, but I cannot solve it.
Thanks a lot.
Edit :
Web.config extract :
<system.web>
    <compilation debug="true"/>
    <deployment retail="false" />
    <customErrors mode="Off">
    </customErrors>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>

    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxx"
        pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxx"
        userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxxx">
      <controls>
        <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxx" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

A: I had similar problem, and there are a lot of pitfalls I came across. I will try to provide their full list to help you check them:

*

*allow Directory browsing in your IIS

*in the folder, where the website is physically saved, check whether IUSR and IIS_IUSR have the permissions to read and browse

*check, whether you have allowed accessing the port in your firewall

*check, whether the IP address is correct. It is possible, that your external IP does not redirect to the internal IP. Or maybe (I made the rookie mistake) you are trying to browse the internal IP instead of external.

I hope this will help. If any questions, do not be afraid to ask.


text:
Q: There is a problem that Customize Ant Design Theme is not applied I am customizing the theme of antd while using next.js.
After Googling the related information, I found a good example and completed the setup as follows.
// package.json
    "dependencies": {
    "@ant-design/icons": "^4.8.0",
    "antd": "^4.24.3",
    "next": "^12.3.1",
    "next-plugin-antd-less": "^1.8.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "styled-components": "^5.3.6",
    "styled-reset": "^4.4.2"
  },
  "devDependencies": {
    "babel-plugin-import": "^1.13.5"
  }

// .babelrc
{
  "presets": [
    "next/babel"
  ],
  "plugins": [
    [
      "import",
      {
        "libraryName": "antd",
        "style": true
      }
    ]
  ]
}

// next.config.js
const withAntdLess = require('next-plugin-antd-less');

module.exports = withAntdLess({
  modifyVars: { '@primary-color': '#04f' },
  lessVarsFilePath: './styles/variables.less',
  lessVarsFilePathAppendToEndOfContent: false,
  cssLoaderOptions: {},

  webpack(config) {
    return config;
  },
});

// styles/variables.less
@import '~antd/lib/style/themes/default.less';
@import '~antd/dist/antd.less';

@primary-color: #52c41a;

// pages/app.js
import React from 'react';
import { ThemeProvider } from 'styled-components';

import "../styles/variables.less";
import GlobalStyles from '../styles/GlobalStyles';
import Theme from '../styles/Theme';

const Home = ({ Component, pageProps }) => {
  return (
    <>
      <GlobalStyles />
      <ThemeProvider theme={Theme}>
        <Component {...pageProps} />
      </ThemeProvider>
    </>
  );
};

export default Home;

// log of executing npm run dev command
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
warn  - Invalid next.config.js options detected:
  - The root value has an unexpected property, modifyVars, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).
  - The root value has an unexpected property, lessVarsFilePath, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).
  - The root value has an unexpected property, lessVarsFilePathAppendToEndOfContent, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).
  - The root value has an unexpected property, cssLoaderOptions, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).

See more info here: https://nextjs.org/docs/messages/invalid-next-config
info  - Disabled SWC as replacement for Babel because of custom Babel configuration ".babelrc.js" https://nextjs.org/docs/messages/swc-disabled
info  - Using external babel configuration from C:\Users\Administrator\OneDrive\Desktop\Training\.babelrc.js
event - compiled client and server successfully in 23.4s (193 modules)

After completing the setting, when I ran the code, the setting was not applied contrary to my expectations.
I might have made a mistake in my code, so I went back to the reference material and tried the settings again, the result was the same.
Is there something wrong with my settings?
We would appreciate it if you could leave a comment in the reply.


text:
Q: How to provide Ansible default value that includes another variable? I want an Ansible 2.6.2 task to use the value of variable var1 if it's set, otherwise a string containing variable var2. Only one of these will be set, however. If I use a simple {{ var1 | default(var2) }} it works, but when I try to append a string to var2 Ansible gives an error when var2 is undefined, even though var1 is:

FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'var2' is undefined\n\nThe error appears to have been in 'test.yml': line 13, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n        msg: \"Simple default: {{ var1 | default(var2) }}\"\n    - debug:\n      ^ here\n"}

Playbook:
- hosts: all
  gather_facts: false
  connection: local
  vars:
    var1: "one"
#    var2: "two"
  tasks:
    - debug:
        # This works
        msg: "Simple default: {{ var1 | default(var2) }}"
    - debug:
        # This fails when var2 is undefined, even though var1 is
        msg: "Default with concatenation: {{ var1 | default(var2 + '?') }}"

A: The error message is clear: parser requires a variable to be defined.
You can use the same default filter to provide default value instead of the var2:
msg: "Default with concatenation: {{ var1 | default(var2|default('') + '?') }}"

A: OK, I found a way that works, thanks to another answer by techraf:
{{ var1 if var1 is defined else var2 + '?' }}

This works if either var1 or var2 is defined, but if both are undefined throws an error:

The task includes an option with an undefined variable. The error was: 'var2' is undefined...

I can add a third variable to this, too:
{{ var1 if var1 is defined else (var2 + '?' if var2 is defined else var3 + '!' ) }}

Dictionary version:
{{ mydict.key1 if mydict.get('key1') else mydict.key2 }}

(if mydict.key1 raises an error if key1 is not in mydict)

A: Both doing the same (don't know which is more efficient)
Variables:
repo: hththt
file_name: file.txt

Templates:
url: "{{ url if url is defined else repo + '/files/' + file_name }}"

url: "{{ url | default(repo + '/files/'' + file_name) }}"


text:
Q: Clear a String array C++ I have 3 functions. One that adds content to each array, one that prints all its context and one that clears all the strings of that array. My question is on the definition of the function that clears the string array. My code deletes each array that is added except the original str[i] or str[0](first slot in array, which holds the string added first). What do i need to add? Am i missing something. Id rather clear it all than set each array slot to a NULL or a str[i] == "";
Here is my attempt:
void StringList::clear()
{
    for(int i=0;i<=numberOfStrings;i++)
    {
        for(int j=i;j<=numberOfStrings-1;j++)
        {
            str[j] = str[j+1];

        }

        numberOfStrings--;
    }

    cout<<"All strings cleared"<<endl;
}

The code clears everything but the first added string. Thoughts? Its probably very simple and my brain is not properly working but everything ive searched does not work.
Is there anyway to clear it without a loop? and just using str[numberOfStrings] ?

A: std::string has a clear() function, so that's all you need to call on each element, except the first one:
void StringList::clear()
{
    // Start from 1 so that we won't clear the first string.
    for(int i = 1; i <= numberOfStrings; i++) {
            str[i].clear();
    }
    cout << "All strings cleared" << endl;
}


text:
Q: Is there any way to get the list of attributes of a class without any instantiated object? I already know that we can get the list of attributes of a object using reflection in Swift, but all the examples that I found and have implemented so far uses a instantiate object. Something like that:
func attributeList() -> [String] {

    var attributeList = [String]()
    let serializableMirror = Mirror(reflecting: self) //using instantiate object

    for childMirror in serializableMirror.children {
        if let label = childMirror.label {
            attributeList.append(label)
        }
    }
    return attributeList
}

My question is, there is any way to get the attributes of a class without any reference to it? Some kind of static method where I pass my desired class type and get the attributes list of it.

A: In all implementations of reflection that I've worked with you need an object for the reflection to work on.
Whether it's one you provide or one the system creates for you, you have to have a concrete object.


text:
Q: Align subscript When i put the code $(f_{\mathcal{X}},f_{\mathcal{X}}^{\partial})$ I get the following:

But I want the subscripts to be aligned. How can I do this?

A: As you've noticed, LaTeX will shift down a subscript when there is a superscript above it to make room. What you need to do is have LaTeX pretend there is something in a superscript above. You can do this by adding a superscript to the first f of \vphantom{\partial}:
$(f^{\vphantom{\partial}}_{\mathcal{X}},f_{\mathcal{X}}^{\partial})$


text:
Q: Plotting disproportionate sets of data I solved an optimisation problem for three cases. I intend to plot the results as a groupplot (essentially a 3 by 1 groupplot). Since I present six sets of data in each plot, I get a graph that looks like this:
Due to the disproportionality of the datasets, we observe a near parallel line for 3 datasets, while the other lines show that the system design costs increase wrt routing costs. What I'd like to have is for the near parallel line to also show that the system design costs increase. However, this information gets suppressed. Could you please suggest some alternatives for this anomaly? Please find the code here
  \begin{tikzpicture}[every mark/.append style={mark size=.7pt}]
    \begin{axis}[
                scale=0.81,
                legend style={
                at = {(.48,-.8)},anchor=south},%at={(0.5,-0.34)},anchor=north},
                %legend columns = -1,
                xmin=0,xmax=50,
                ymin=0,ymax=400000,
                ymode = log,
                xlabel={routing costs},
                ylabel={system design costs},
                legend style={font=\small}]

\addplot
    coordinates {
        (0, 310006.712271894)
        (10, 312781.712271894)
        (20, 315556.712271894)
        (30, 318331.712271894)
        (40, 321106.712271894)
        (50, 323881.712271894)
    };\addlegendentry{Centralised RAN}

\addplot+
    coordinates {
        (0, 237.689033351856)
        (10, 535.932112624024)
        (20, 834.175191896192)
        (30, 1132.41827116836)
        (40, 1430.66135044053)
        (50, 1728.90442971269)
    };\addlegendentry{Distributed RAN}

\addplot+
    coordinates {
        (0, 47.5517657268742)
        (10, 404.104349185922)
        (20, 709.528125267976)
        (30, 1014.06344997298)
        (40, 1317.76112473382)
        (50, 1620.73092429476)     }
    ;\addlegendentry{Fluid RAN}
      \addplot+          coordinates {
        (0, 310007.104063121)
        (10, 312782.104063121)
        (20, 315557.104063121)
        (30, 318332.104063121)
        (40, 321107.104063121)
        (50, 323882.104063121)
    };\addlegendentry{Centralised RAN - HIGH}

\addplot+
    coordinates {
        (0, 93699.4500521545)
        (10, 94466.4160045098)
        (20, 95233.3819568651)
        (30, 96000.3479092204)
        (40, 96767.3138615757)
        (50, 97534.279813931)
    };\addlegendentry{Distributed RAN - HIGH}

\addplot+
    coordinates {
        (0, 90079.5312740768)
        (10, 90995.7138828325)
        (20, 91787.0309120226)
        (30, 92568.9759214698)
        (40, 93347.4344093317)
        (50, 94123.854677605)
    };\addlegendentry{Fluid RAN - HIGH}

 \end{axis}
\end{tikzpicture}

A: Just for fun, I created a part linear/part semilog plot.

\documentclass{standalone}
\usepackage{pgfplots}
\usetikzlibrary{calc}

\begin{document}
\begin{tikzpicture}[every mark/.append style={mark size=.7pt}]
    \begin{axis}[name=lower,
                scale=0.81,
                height=3cm, width=6cm, scale only axis,
                xmin=0,xmax=50,
                ymin=0,ymax=50000,
                ymode = log,
                xlabel={routing costs},
                ylabel={\hspace*{2.5cm}system design costs},
                ylabel shift=2cm,
                legend to name=part1,
                legend style={font=\small}]
\addplot+
    coordinates {
        (0, 47.5517657268742)
        (10, 404.104349185922)
        (20, 709.528125267976)
        (30, 1014.06344997298)
        (40, 1317.76112473382)
        (50, 1620.73092429476)     }
    ;\addlegendentry{Fluid RAN}
\addplot+
    coordinates {
        (0, 237.689033351856)
        (10, 535.932112624024)
        (20, 834.175191896192)
        (30, 1132.41827116836)
        (40, 1430.66135044053)
        (50, 1728.90442971269)
    };\addlegendentry{Distributed RAN}
\end{axis}

\begin{axis}[shift=(lower.north west),
        scale=0.81,
        height=3cm, width=6cm, scale only axis,
        xticklabels={}, cycle list shift=2,
        xmin=0,xmax=50,
        ymin=50000,ymax=400000,
        legend to name=part2,
        legend style={font=\small}]

\addplot
    coordinates {
        (0, 310006.712271894)
        (10, 312781.712271894)
        (20, 315556.712271894)
        (30, 318331.712271894)
        (40, 321106.712271894)
        (50, 323881.712271894)
    };\addlegendentry{Centralised RAN}

      \addplot+          coordinates {
        (0, 310007.104063121)
        (10, 312782.104063121)
        (20, 315557.104063121)
        (30, 318332.104063121)
        (40, 321107.104063121)
        (50, 323882.104063121)
    };\addlegendentry{Centralised RAN - HIGH}

\addplot+
    coordinates {
        (0, 93699.4500521545)
        (10, 94466.4160045098)
        (20, 95233.3819568651)
        (30, 96000.3479092204)
        (40, 96767.3138615757)
        (50, 97534.279813931)
    };\addlegendentry{Distributed RAN - HIGH}

\addplot+
    coordinates {
        (0, 90079.5312740768)
        (10, 90995.7138828325)
        (20, 91787.0309120226)
        (30, 92568.9759214698)
        (40, 93347.4344093317)
        (50, 94123.854677605)
    };\addlegendentry{Fluid RAN - HIGH}

 \end{axis}

\node[below=1cm,align=center] at (lower.south) {\pgfplotslegendfromname{part1}\\
  \pgfplotslegendfromname{part2}};
\end{tikzpicture}
\end{document}


text:
Q: (why) does an integrable function have to be measurable? In this definition, it says that for a function $u$ to be $\mu$-integrable, it also has to be measurable:

However, Here's what I am wondering:
Take the Lebesgue integral of $u^+$ (the same will apply to $u^-$). This Lebesgue integral is the limit of simple functions $f_i$ on $X$. Assume that we have a sequence of simple functions on $X$ that are all measurable and as $n\to \infty, f_i\to u^+$. Can't we then say: As we let $n\to \infty$, the integral of $f_n$ will go to the integral of $u^+$ even if $u^+$ is not measurable. We don't need $u^+$ to be measurable, so long as all the $f_i$'s are measurable.
Is this correct?

A: The limit of a sequence of measurable functions must be measurable.
For the Vitali non-measurable set $C$, then consider the non-measurable function $u=\chi_{C}$, in this case, $u^{+}=\chi_{C}$, so there is no any sequence $(f_{n})$ of measurable functions such that $f_{n}\rightarrow\chi_{C}$ a.e.

A: Actually you are missing one thing, a sequence of measurable function converges to a measurable function Hence so does the sequence of measurable simple functions therefore we require the functions to be measurable in the definition of Integrability.
Hope it works


text:
Q: How to sort QList according to a certain order (not alphabetical)? I have QList<m_User> with
m_User {
    QString status;
    QString firstName;
    QString lastName;
    QDate joinDate;
    QDate leaveDate;
}

status here can be: terminated, in test, requested, activated.
The order of sorting for status should be: activated -> terminated -> requested -> in test
This QList should be sorted according to this order:

*

*status (with order like above)

*if status is same, we sort firstName, this time alphabetically

*if firstName is same, we sort lastName, also alphabetically

So the result should look like
----------------------------------------------------------
| firstName | lastName |  status  | joinDate | leaveDate |
----------------------------------------------------------
|     A     |    C     |activated |   bla    |    bla    |
|     A     |    D     |activated |   bla    |    bla    |
|     B     |    E     |activated |   bla    |    bla    |

|     A     |    F     |terminated|   bla    |    bla    |
|     A     |    G     |terminated|   bla    |    bla    |
|     B     |    H     |terminated|   bla    |    bla    |

|     A     |    I     |requested |   bla    |    bla    |
|     B     |    I     |requested |   bla    |    bla    |
|     B     |    K     |requested |   bla    |    bla    |

|     A     |    L     | in test  |   bla    |    bla    |
|     B     |    L     | in test  |   bla    |    bla    |
|     B     |    M     | in test  |   bla    |    bla    |

A: You can add lessThen function to your class/struct and then if needed create forwarder for qSort.
Example:
class m_User {
public:
bool operator<(const m_User other) const {
        return a<other.a;
    }
};

template <typename T>
struct ForwardLessThen
{
  bool operator()(const T* a, const T* b) const
  {
    return *a < *b;
  }
};

qSort(list.begin(), list.end(), ForwardLessThen<m_User>());

if you use C++11/14 you can use lambdas
QList<const m_User*> l;
qSort(l.begin(), l.end(),
      [](const m_User* a, const m_User* b) -> bool { return a->firstName() < b->firstName(); //implement your logic here
});

With Qt5 qSort is actually deprecated and you should use std::sort function.
std::sort(container.begin(), container.end(), qLess<T>());

Take a look at template-based algorithms in QtAlgorithms
EDIT: Or if you plan using some kind of View Models(like ListView) you can even implement own QSortFilterProxyModel

A:     bool compareUsers(const m_User &u1, const m_User &u2)
    {
        if(u1.status != u2.status)
        {
            //compare all possible combination if statuses of the
            //u1 user and u2 user and return which has priority

            //example activated has priorty over terminated
            if(u1.status == "activated" && u2.status =="terminated")
            {
                return true;
            }
            else if(u1.status == "terminated" && u2.status =="activated")
            {
                return false;
            }
            ...
            ..
            .
        }
        else if(u1.firstName != u2.firstName)
        {
            return u1.firstName > u2.firstName;
        }
        else
        {
           return u1.lastName > u2.lastName;
        }
    }

and then just call the predicate in sort function
QList<m_User> list;
qSort(list.begin(), list.end(), compareUsers);


text:
Q: Installing pyinstaller using Anaconda (on Windows) I'm trying to install "pyinstaller" to my base environment using Anaconda.
I am using a Windows 10 setup.
I have not installed pyinstaller on my environment/setup before.
I'm wondering why the command
conda install -c conda-forge pyinstaller

gives me this output:
Collecting package metadata (current_repodata.json): done
Solving environment: done

## Package Plan ##

  environment location: D:\Anaconda

  added / updated specs:
    - pyinstaller

The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    altgraph-0.17              |     pyhd8ed1ab_0          21 KB  conda-forge
    ca-certificates-2020.11.8  |       h5b45459_0         183 KB  conda-forge
    certifi-2020.11.8          |   py38haa244fe_0         150 KB  conda-forge
    conda-4.9.2                |   py38haa244fe_0         3.1 MB  conda-forge
    macholib-1.14              |     pyh9f0ad1d_1          34 KB  conda-forge
    openssl-1.1.1h             |       he774522_0         5.8 MB  conda-forge
    pefile-2019.4.18           |             py_0          52 KB  conda-forge
    pyinstaller-4.1            |   py38hd0d6af5_1         2.4 MB  conda-forge
    pyinstaller-hooks-contrib-2020.10|     pyhd8ed1ab_0          65 KB  conda-forge
    python_abi-3.8             |           1_cp38           4 KB  conda-forge
    ------------------------------------------------------------
                                           Total:        11.7 MB

The following NEW packages will be INSTALLED:

  altgraph           conda-forge/noarch::altgraph-0.17-pyhd8ed1ab_0
  macholib           conda-forge/noarch::macholib-1.14-pyh9f0ad1d_1
  pefile             conda-forge/noarch::pefile-2019.4.18-py_0
  pyinstaller        conda-forge/win-64::pyinstaller-4.1-py38hd0d6af5_1
  pyinstaller-hooks~ conda-forge/noarch::pyinstaller-hooks-contrib-2020.10-pyhd8ed1ab_0
  python_abi         conda-forge/win-64::python_abi-3.8-1_cp38

The following packages will be UPDATED:

  ca-certificates    pkgs/main::ca-certificates-2020.10.14~ --> conda-forge::ca-certificates-2020.11.8-h5b45459_0

The following packages will be SUPERSEDED by a higher-priority channel:

  certifi            pkgs/main::certifi-2020.11.8-py38haa9~ --> conda-forge::certifi-2020.11.8-py38haa244fe_0
  conda               pkgs/main::conda-4.9.2-py38haa95532_0 --> conda-forge::conda-4.9.2-py38haa244fe_0
  openssl                                         pkgs/main --> conda-forge

but the command
conda install pyinstaller

gives me that output:
Collecting package metadata (current_repodata.json): done
Solving environment: done

## Package Plan ##

  environment location: D:\Anaconda

  added / updated specs:
    - pyinstaller

The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    altgraph-0.17              |             py_0          22 KB
    macholib-1.14              |             py_1          36 KB
    pefile-2019.4.18           |             py_0          57 KB
    pycryptodome-3.9.9         |   py38h2bbff1b_0         9.7 MB
    pyinstaller-3.6            |   py38h62dcd97_5         1.7 MB
    ------------------------------------------------------------
                                           Total:        11.5 MB

The following NEW packages will be INSTALLED:

  altgraph           pkgs/main/noarch::altgraph-0.17-py_0
  macholib           pkgs/main/noarch::macholib-1.14-py_1
  pefile             pkgs/main/noarch::pefile-2019.4.18-py_0
  pycryptodome       pkgs/main/win-64::pycryptodome-3.9.9-py38h2bbff1b_0
  pyinstaller        pkgs/main/win-64::pyinstaller-3.6-py38h62dcd97_5

I'd like to know what the differences between these two commands are
and which I should run for a reliable installation of pyinstaller to my Anaconda environment.
I bet for the first one :D
Thank you very much!


text:
Q: Cannot add extra-deps to Stack project I'm trying to set up a Haskell project with Stack. I have created a project: stack new project1 and added the suggested dependency (acme-missile) just to see how it works.
extra-deps:
- acme-missiles-0.3

But when I try to invoke launchMissile in the Main it won't work. I get
Error:(3, 1)     Could not find module 'Acme.Missiles'
    Use -v to see a list of the files searched for.
  |
3 | import Acme.Missiles
  | ^^^^^^^^^^^^^^^^^^^^

What is the problem? What am I missing?
EDIT
When I run stack solver I get this:
Using configuration file: stack.yaml
Using cabal packages:
- ./

The following changes will be made to stack.yaml:
* Dependencies to be deleted
    extra-deps:
    - acme-missiles-0.3

To automatically update stack.yaml, rerun with '--update-config'

Isn't that strange? Like it thinks my dependency is not needed?

A: You'll need to add the dependency to project1.cabal as well:
build-depends:
    base >=4.7 && <5
  , project1
  , acme-missiles

Alternatively, on newer versions of Stack, it looks like you should use package.yaml instead:
dependencies:
- base >= 4.7 && < 5
- acme-missiles

I can't say that I have deep knowledge of how this works, but if I understand it correctly, the main file where you're supposed to add dependencies is in the .cabal or package.yaml file. The extra-deps field in stack.yaml is where you can indicate if you have dependencies that deviate from the LTS that you currently use.


text:
Q: Get list of subscribed group by user using ejabberd API I am currently developing chat system for our application using ejabberd API.
I am having a problem on how to retrieve a list of subscribed group by username.
I only can retrieve a list of groups that user occupied, but not subscribed using get_room_users API.
My reference:
https://docs.ejabberd.im/developer/ejabberd-api/admin-api/
My question:

*

*How to retrieve list of subscribed group by username?

*Do I need to register all subscribers to the group to make use of get_room_users API?

A:

*

*How to retrieve list of subscribed group by username?

There is no command to obtain that information.

*Do I need to register all subscribers to the group to make use of get_room_users API?

I guess you mean get_room_occupants. Well, if you make the room subscribers also members of the room, then you can use get_room_affiliations, for example:
$ ejabberdctl get_room_affiliations room1 conference.localhost
user2   localhost       member
user1   localhost       owner


text:
Q: Is it possible to do a custom rendering with highchart-ng?! I tried to use Highcharts Renderer to create my own custom shapes.
Unfortunately, I cannot find a way to invoke those methods.
Is it even possible to use Highcharts methods? with highcharts-ng?!
My Plunk
My code:
var myapp = angular.module('myapp', ["highcharts-ng"]);

myapp.controller('myctrl', function ($scope) {
  $scope.chartDonut = {
    options: {
      chart: {
          type: 'pie',

      },
      colors: [
           '#FFFFFF',
           '#AA4643',

      ],
      credits: {
        enabled: false
      },

      legend: {
        borderWidth: 0
      },

      plotOptions: {
        pie: {
          borderWidth: 0.2,
          borderColor: '#000000',
        }
      }
    },

    title: {
        text: 'Browser market share, April, 2011'
    },

    backgroundColor: '#cccccc',
    tooltip: {
        formatter: function() {
            return ''+ this.point.name +': '+ this.y +' %';
        }
    },
    series: [{
        name: 'Browsers',
        data: [{
              name: 'MATCHED',
                y: 25
            }, {
                name: 'UNMATCHED',
                y: 50,

          color: {
              pattern: 'http://highcharts.com/demo/gfx/pattern1.png',
              width: 6,
              height: 6
          }

            }],

        size: '60%',
        innerSize: '56%',
        showInLegend: false,
        dataLabels: {
          enabled: true,
          connectorWidth: 0,
          connectorPadding: 0,
          useHTML: true,
          x: 20,
          formatter: function() {
              if (this.point.name === 'UNMATCHED')
                return '
'
                        + '
' + this.y + '
'
                        + '
' + this.point.name + '
'
                        + '
';
          }
        }
    }]
  };
});

A: This can be done with current version, while documentation is not clear.
In source code, highcharts constructor is called:

new Highcharts.Chart(mergedOptions, func)

The second parameter is a callback when highcharts initialization is finished:
http://api.highcharts.com/highcharts#Highcharts.Chart (it does not explain its arguments)
We can get the chart object from the 1st argument of this function. Add following code to your chart config object:

func: function(chart) {
  $scope.chartObj = chart;
}

Then you can use it in your view or code (for any API calls):

{{chartObj.renderer.height}}

$scope.chartObj.renderer.circle(...);
$scope.chartObj.getSelectedPoints();

As an example I forked the original plunk here:
http://plnkr.co/edit/6WvHEjJfr4pGqd2OvPKF?p=preview

A: Author here. At the moment it is not possible to do this. Pull requests gladly accepted. I'll probably add it myself in the near future.
See here to track changes: https://github.com/pablojim/highcharts-ng/issues/97

A: i can't find the answer either,but i've got a resolution, which is invoke the renderer in the formatter of xAxis label formatter function, and it works..


text:
Q: angular2 Can't resolve all parameters for AppComponent: (?) import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RestfulComponent } from '/app/rest/app.restful.component.ts';
import { HttpModule } from '@angular/http';

@NgModule({
  imports: [
    BrowserModule,
    HttpModule
  ],
  declarations: [
    RestfulComponent
  ],
  bootstrap: [ RestfulComponent ]
})
export class AppModule { }

app.restful.module.ts
import { Component } from '@angular/core';
import { RestfulService } from '/app/rest/restful/restfull.service.ts';

import {Http} from '@angular/http';
import { Observable } from 'rxjs';

@Component({
  selector: 'my-app',
  template: `
    <button (click)="onTestGet()">GET TEST</button>

Output: {{getData}}

  `,
  providers: [RestfulService]
})
export class RestfulComponent {

    getData: string;
    postData: string;
//
   constructor (private _http: Http){}

      onTestGet(){
          this._restfulService.getCurrentTime().subscribe(
          data => this.getData = JSON.stringify(data),
          error => alert(error),
          () => console.log("end")
              );
          }
}

app.restful.component.ts
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Headers} from '@angular/http';
import 'rxjs/add/operator/map'

@Injectable()
export class RestfulService {
        constructor (private _http: Http){}

        getCurrentTime(){
            return this._http.get('http://date.jsontest.com').map(res => res.json());
        }
}

restful.service.ts

[test.html2
I do not have much knowledge about angular. If in case you are missing any information or file, I am here to add.
I'll put the changed codes where they generated the following error:
What should I do??

A: declare RestfulService inside the constructor method :
constructor(private _restfulService: RestfulService) { }


text:
Q: Vuetify - Get object's single property on v-select I am creating a form with Vuetify, which has initial values on some inputs and these values come from objects.
Basically, the objects have two important properties: the name and the id. Folllowing the Vuetify docs, i'm using item-text prop to display the object's name on the v-select and item-value to return the object's id when the option is selected. When another option is selected, it returns the id as expected. However, if the initial option is not changed, the returned value is the whole object, instead of just the id.
The context is this:
       <v-select
          label="Select an specialty..."
          v-model="entry.specialty"
          :items="specialties"
          :item-text="item=>item.name"
          :item-value="item=>item.id"
        ></v-select>

The entry object has the specialty property and the initial specialty's name is displayed on the select. I think the problem is the v-model, which has the whole specialty object. I tried to set the v-model as entry.specialty.id, but it did not work as expected.
Let me know if there's more information i can give.

A: Try to set the property return-object:
<v-select
  label="Select an specialty..."
  v-model="entry.specialty"
  :items="specialties"
  :item-text="item=>item.name"
  :item-value="item=>item.id"
  :return-object="false"
/>

The return-obejct can be: true or false
If this don't work, please post whole component code.


text:
Q: How to search and highlight long passages in a PDF file? I made several highlights on Kindle Touch to PDF files. Kindle saves the highlighted text in a separate file, not on the PDFs themselves. I have all the text of the passages I want highlighted, what I need is: a program that can find long phrases and then highlight these phrases. This way, I can build a macro for this program to loop and do this for all my text passages.
I tried Adobe Acrobat XI, but Acrobat has a limit on how many words I can search (~28 characters). I know I could split the highlights, but it's important for me to not do this. So, my questions are:

*

*Is there a software that can do this? (Search for a long string and, once found, highlight it and save the modified PDF?)

*Acrobat has a JavaScript console, could someone who is savvy suggest me a script to do this? (I can code some very basic Python, but no Java/JavaScript)
I'm on Windows 7 Ultimate x64
Thank you!

A: Adobe Acrobat PRO X has the option of adding an action called for highlighting. It uses the highlight and redact option but, instead of redacting the text that was found, it replaces it for highlighting. I tried this with the Kindle clippings.txt file and it works like a charm. I hate ADOBE though, so I am trying to find a similar solution for a different PDF reader.
Two guys produced AppleScript for the MAC OS X Skim PDF reader (which I love) but I couldn't made them work. I will explore that possible solution in a different question. The Action file for ADOBE has a .sequ extension. I can't find it right now in Google but I know it's there. Sadly, I renamed the file so I can't point precisely to its source.
For the GitHub projects for Skim, see
my-clippings-to-pdf
Skim-AppleScript


text:
Q: Caching all entities in Cache Layer and Synchronizing with Database Is it possible, reliable and secure to cache all entities in distrubuted cache and notifies dao layer on update? My possible idea is;

*

*Use JPA 2.1 and Hibernate implementation.

*On creation persist it db

*After persisting it, cache it to distrubuted cache.

*Canalise all read actions to cache

*on update notify dao layer to update entity .

A: yes you can design a system that will

*

*On addition: persists data to db and adds to cache

*On read: reads data from cache, and considers a cache miss as not
present in database as well.

*On update: updates data in db and then updates in cache (or vice
versa)

*On delete: deletes data from cache and then deletes from database

This approach will work fine if you have a single application using that database and if data is not that critical. However if data integrity is of more importance, you may face following problems in this approach:

*

*You may face a cache miss when data is present in database(persisted
but not yet cached)

*You may get stale data from cache (updated in db but not yet updated
in cache)

*Also if data is removed from database by some other application, it
will still ramained cached in distributed cache(invalid data on
reads)

A better mothod my be if you use a rich featured distributed caching solution like NCache / Tayzgrid which provides Read Trough / Write behind features. This way your application will only need to use cache for all reads, writes or updates and cache will keep database updated using configured providers.
Another approach may be to use distributed cache as hibernate's second level cache and you will not need to add a caching layer by your self. See this article for details about hibernate's second level cache.
Distributed caching solutions like Tayzgrid provide caching provider for hibernate that can be easily configured. You can find hibernate providers for other solutions as well.


text:
Q: Como impedir um objeto de ser instanciado com determinada propriedade? Eu desejo impedir um objeto de ser instanciado com um determinado valor (por exemplo, impedir que um objeto "bateria" possua um valor negativo ou acima de 100). Como eu posso impedir que ocorra a instância?
Exemplo de código:
import java.util.Scanner;
public class Fotocopiadora{
    private String modelo; // essa string não deve ser nula
    private int quantTinta;
    private String proprietario;

    public Fotocopiadora(String modelo, String proprietario){
        this.proprietario = proprietario;
        this.quantTinta = 100;

        this.modelo = ((modelo != null) && (!modelo.isEmpty())) ? modelo : "default"; // usado como substituição ao impedimento de instância
    }
}

A: Experimente assim. A exceção se for lançada irá impedir o objeto de ser instanciado.
import java.util.Scanner;
public class Fotocopiadora{
    private String modelo; // essa string não deve ser nula
    private int quantTinta;
    private String proprietario;

    public Fotocopiadora(String modelo, String proprietario, int quantTinta){

        this.proprietario = proprietario;

        if (quantTinta < 0 || quantTinta > 100) {
            throw new IllegalArgumentException("QuantTinta inválido: " + quantTinta);
        }
        this.quantTinta = quantTinta;

        this.modelo = ((modelo != null) && (!modelo.isEmpty())) ? modelo : "default"; // usado como substituição ao impedimento de instância
    }

    // Este outro construtor aproveita o construtor já existente para
    // criar uma fotocopiadora com bateria 100% carregada. Isso se
    // chama sobrecarga de construtor.
    public Fotocopiadora(String modelo, String proprietario) {
        this(modelo, proprietario, 100);
    }
}


text:
Q: "Object Not Found" error in phpmyadmin I installed xampp in window 7 . but whenever i tried to click home button in phpmyadmin .  the url turn weird and it doesn't redirect to
http://localhost/phpmyadmin/main.php?token=b0ffa519161e4c2e54c230a2fe97107a

and redirect to the following instead .
http://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/://localhost/phpmyadmin/navigation.php?server=1&token=b0ffa519161e4c2e54c230a2fe97107a&db=&table=&lang=en-utf-8&collation_connection=utf8_general_ci

so it showed "Objects not found message" because that url isn't supposed to be . but it totally ok when i tried with Control + Click .  please help me to fix it . it only happened when i clicked four icons ,  Home , SQL , question mark and other SQL icon from left side of phpmyadmin  btw it totally fine in chrome browser (version 17.0.963.2)  but not ok in firefox (16.0.2)  and phpmyadmin version is 3.3.9

A: If it's only with a specific browser only as you stated out then you can clear your browsers cache and check..
Under Firefox main menu click on Tools->Clear Recent History and clear out Everything..


text:
Q: Debugging django-allauth Social Network Login Failure When using django-allauth to do an OAuth login via a social provider, sometimes it fails with the error page "Social Network Login Failure".  There is no log output containing more information.  There is a feature request for this log output (https://github.com/pennersr/django-allauth/issues/1120) but it has been open for over a year.  In the mean time, how do I get more information to debug this error?

A: @Zags answers is great and pointed me in the right direction.
Building on that answer, I suggest start by copying the default authentication_error.html to your tree, e.g.:
$ find /wherever/your/python/is -name socialaccount
$ cp .../that/dir/socialaccount/authentication_error.html \
     ./myapp/templates/allauth/socialaccount/

Then add in to the copy of the template:
<p>
Code: {{ auth_error.code }}, Error: {{ auth_error.exception }}
</p>

(Technically you could just edit the installed python version...)
Result for me, slightly formatted:
Code: unknown,
Error: Error retrieving access token:
b'{"error":{
  "message":"This IP can\'t make requests for that application.",
  "type":"OAuthException",
  "code":5,
  "fbtrace_id":"..."
}}'

A: More information is passed to the context used to render the error template but is not used in the default template.
You can get log output by overriding the template and including in your template the following:
{{ auth_error }}

or alternatively:
Code: {{ auth_error.code }}, Error: {{ auth_error.exception }}

To override the template, add a folder to your Django template DIRS.  In Django 1.8+, this looks like the following:
TEMPLATES = [
    {
        ...
        DIRS: [os.path.join(BASE_DIR, 'templates')]
    }
]

Then, in that folder, make directory socialaccount and put in it a file called authentication_error.html

A: "Social Network Login Failure" can occur due to multiple reasons but URL mismatch is the most frequent problem I have experienced:

*

*If you are facing this problem while hosting on third party, do remember to change expected URL to host's url

*If the problem is occuring during development only, you must have registered on social website using localhost or 127.0.0.1 . Do call social website through correct url. For e.g. facebook doesn't allow to register 127.0.0.1 but localhost and "manage.py runserver" gives 127.0.0.1 as default. So open your website using "localhost".
Also ensure that you have added correct url to 'sites' in django admin and it has been correctly added to 'social application'

A: This also happened to me when I was checking https site on http (if I could redirect production). Error code/message was empty.
I commented out these for the http testing:
# SESSION_COOKIE_SECURE = True
# CSRF_COOKIE_SECURE = True
# APPEND_SLASH = True
# PREPEND_WWW = True

A: If you use a custom SocialAccountAdapter (can be set in your settings.py, read more here) then you can simply overwrite the function authentication_error to log all of the errors.
The function signature (source here) looks like this:
(main/wherever.py):
class SocialAccountAdapter(DefaultSocialAccountAdapter):
    def authentication_error(self, request, provider_id, error, exception, extra_context):
        your_log_function(
            'SocialAccount authentication error!',
            'error',
            request,
            extra_data = {'provider_id': provider_id, 'error': error.__str__(), 'exception': exception.__str__(), 'extra_context': extra_context},
        )

(and in settings.py)
SOCIALACCOUNT_ADAPTER = "main.wherever.SocialAccountAdapter"

I'm doing this in my app and it works great!

A: When I was testing locally, my problem was two fold:
First, I had to make sure that I started the server using
python manage.py runserver localhost:8000

Then, in the admin page I had to make sure the Sites table had an entry for localhost:8000, e.g. at
http://localhost:8000/en/admin/sites/site/

The gotcha for me was that I'd had multiple attempts at this and the result was the the ID for my localhost:8000 Sites table entry had become greater than 1. You'll notice in the allauth documentation that is says to to have SITE_ID = 1 in the settings.py but if you inadvertently create a different ID for the entry, you'll have to either alter the database entry's ID or change SITE_ID value.
The other issue I had (unrelated to the poster's issue) was that I also had old registrations url template include interfering with the allauth ones.

A: In my case I had everything ok except the flag SESSION_COOKIE_DOMAIN = mydomain.com which I only had to comment because I was working on localhost and not in mydomain.com.


text:
Q: Compile error when setting Excel cell to bold when using NPOI 1.2.5.0 We are trying to bold a row in excel , Visual studio 2008,
framework 3.5 NPOI 1.2.5.0 - getting compile error
Following is the code snippet,
ICellStyle style1 = templateWorkbook.CreateCellStyle();
style1.SetFont(font1);
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
HSSFFont font = (HSSFFont)hssfworkbook.CreateFont();
font.Boldweight = HSSFFont.BOLDWEIGHT_BOLD;
style1.SetFont(font1);

it is giving compile error on line where we have written
   font.Boldweight = HSSFFont.BOLDWEIGHT_BOLD;
compile Error    2
'NPOI.HSSF.UserModel.HSSFFont' does not contain a definition for 'BOLDWEIGHT_BOLD'
C:\SampleApp\XLSFormatDotNet\XLSFormatingDLL\Class1.cs   301    60    XLSFormatingDLL

Sample codes on the internet show same syntax, but I am getting this compiler error, seems strange,
please help me. any suggestion welcome.
Regards
sham

A: HSSFFont is a class (see http://npoi.codeplex.com/SourceControl/changeset/view/64939#134674). The Boldweight property is of type short and there is an enum to help you set the properties:
public enum FontBoldWeight:short
{
        /**
     * Normal boldness (not bold)
     */

    NORMAL = 0x190,

    /**
     * Bold boldness (bold)
     */

    BOLD = 0x2bc,
}

You should try to do something like this:
 font.Boldweight = FontBoldWeight.BOLD;

Maybe they have changed from constants to enums and haven't updated their samples.


text:
Q: Can I get Azure Cosmos DB header 'x-ms-request-charge' from fail calls? I am getting this header in response for every successful call to Cosmos DB, but in case of unsuccessful call, I don't get it. Is this by design?

A: As Query Documents REST API for example, you could see that the x-ms-request-charge is returned by all Cosmos DB responses.
I tested the rest api in the postman and I get get x-ms-request-charge header.

So, you just use below code :
System.out.println(connection.getHeaderField("x-ms-request-charge"));


text:
Q: Can't push view controller from UISearchDisplayController delegate I have created a UISearchDisplayController which uses a separate UITableViewController as the delegate to display the results of the search. In this view controller, I have the 'didSelectRowAtIndexPath' method which allocates and initializes a detailViewController then uses:
[[self navigationController] pushViewController: detailViewController animated: YES];

to push it onto the stack. However, this line doesn't work. When a cell is tapped, nothing happens. 'didSelectRowAtIndexPath' is being called, but the 'pushViewController' method call isn't working. Am I not in the context of my navigationController any more? How can I fix this problem?
Any help would be much appreciated.

A: your table's navigationController is probably the wrong one, I think that you might want to push it on the navigationController of your UISearchDisplayController.
To do this, you can create a protocol in your tableviewcontroller with a method "pushViewController" for instance and have UISearchDisplayController implement it.
Then your register this delegate in your table view and you call your delegate on pushViewcontroller in your 'didSelectRowAtIndexPath'


text:
Q: Network layer Lan network When we sent packets from one router to another router on the network layer and the packet size is greater than the MTU (maximum transferable unit) of the router, we have to fragment the packet. My questions is: suppose we need to add padding bits in last fragment, then where do we add padding bits (in the LSB or MSB) and how does the destination router differentiate between packet bits or padding bits?

A: I want you to consider the following things before:

*

*Limit on the maximum size of IP data-gram is imposed by data link protocol.

*IP is the highest layer protocol that is implemented both at routers and hosts.

*Reassembly of original data-grams is only done at destination host. This takes off the extra work that need to be done by the routers present in the network core.

I will use the information from the following image to help you get to the answer with an example.

Here initial length of the packet is 2400 bytes which needs to to fragmented according to MTU limit of 1000 bytes.
There are only 13 bits available for the fragment offset and the offset is given as a multiple of eight bytes. This is why the data fields in first and second fragment has size of 976 bytes (It is the highest number divisible by 8, which is smaller than 1000 - 20 bytes). This makes first and second fragment of total size of 996 bytes. The last fragment contains the remaining of 428 bytes of payload (with 448 bytes of total).
Offset can be calculated as 0; 976/8 = 122 and 1952/8 = 244.
When these fragments reach the destination host, reassembly needs to be done. Host uses identification, flag and fragmentation offset for this task. In order to make sure which fragments belong to which data-gram, host uses source, destination addresses and identification to uniquely identify them. Offset values and more fragment bits are used to determine whether all fragments have arrived or not.
Answer to your question
The need to divide payload into multiples of 8 is only required for non-last fragment. Reason of using offset dividing by 8 helps the host to identify the starting address of the next fragment. The host don't need the address of the next fragment if it encounters the last fragment. Thus, no need to worry about payload being multiple of 8 in case of last fragment. Host checks the more fragment flag to identify the last fragment.
A bit of additional information: It is not the responsibility of the network layer to guarantee the delivery of the data-gram. If it encounters that one or more fragment(s) have not arrived then, it simply discards the whole data-gram. Transport layer, which is working above network layer, will take care of this thing, if it is using TCP, by asking the source to re-transmit the data.
Reference: Computer Networking-A Top Down Approach, James F. Kurose, Keith W. Ross (Fifth Edition)

A: You don't need to add any padding bits.  All bits will be push on down the route until the full frame has been sent.


text:
Q: lodash filtering nested json Hi I have the following json data...
    {
    "contacts":
    [
        {
            "contactId": "00001",
            "firstName": "test",
            "lastName": "test",
            "email": "test@test.com",
            "phone": "0207 0000000",
            "role": "Surveyor",
            "customer": "00001",
            "projects": [{"projId": "00002"}]
        },
        {
            "contactId": "00002",
            "firstName": "test1",
            "lastName": "test1",
            "email": "test@test.com",
            "phone": "0207 1111111",
            "role": "Manager",
            "customer": "00001",
            "projects": [{"projId": "00002"}, {"projId": "00003"}]
        }
    ]
}

I need an API endpoint that returns contacts based on projID but am having problems because the projId is nested in the projects array...
    //Get contacts by Project
app.get('/v1/projcontacts/:id', function(req, res) {
    var id = req.params.id;
    var projContacts = lodash.filter(contactData.contacts, { 'projId': id });
    res.json(projContacts);
})

Anyone help me out with the code above to get lodash to look inside projects?

A: You can try something like this:

app.get('/v1/projcontacts/:id', function(req, res) {
  var id = req.params.id;
  var projContacts = contacts.filter(
    contact => contact.projects.map(
      projects => projects.projId === id
    ).includes(true)
  )
  res.json(projContacts);
})

A: You can try something like this:

const data = {
    "contacts":
    [
        {
            "contactId": "00001",
            "firstName": "test",
            "lastName": "test",
            "email": "test@test.com",
            "phone": "0207 0000000",
            "role": "Surveyor",
            "customer": "00001",
            "projects": [{"projId": "00002"}]
        },
        {
            "contactId": "00002",
            "firstName": "test1",
            "lastName": "test1",
            "email": "test@test.com",
            "phone": "0207 1111111",
            "role": "Manager",
            "customer": "00001",
            "projects": [{"projId": "00002"}, {"projId": "00003"}]
        }
    ]
};

const projId = "00003";

// E.g Filter by project ID "00003"
const results = data.contacts.filter(x => x.projects.some(x => x.projId === projId));

console.log(JSON.stringify(results, null, 4));

A: lodash may be overkill for this. You could use .some(), which has the added benefit of exiting early when it finds the first match:
app.get('/v1/projcontacts/:id', function(req, res) {
    var id = req.params.id;
    var projContacts = contactData.contacts.filter(contact => {
        return contact.projects.some(project => project.projId === id);
    });
    res.json(projContacts);
})