text:
Q: Colour change on scroll Need help replicating a feature on a website (https://www.splinegroup.ca). Would like to replicate the background and font colour change, especially further down from black to white...
Would greatly appreciate any assistance.
Here is what I've tried so far... it's not as smooth
https://codepen.io/laluuk/pen/gOrELGb
Also quite like the way the main text reveals "A Leading Mechanical", would greatly appreciate if someone could help recreating this please.

$(function() {
  $(window).scroll(function() {
    if ($(this).scrollTop() > 150) {
      $('section').removeClass('bg-black', 500)
      //$('section h1').removeClass('text-white')
      $('section').addClass('bg-white', 1000)
    }
    if ($(this).scrollTop() < 150) {
      $('section').removeClass('bg-white', 500)
      $('section').addClass('bg-black', 500)
    }
  });
});
.bg-black {
  background-color: #000;
  color: #fff;
}

.bg-white {
  background-color: #fff;
  color: #000;
}

section {
  height: 80vh;
}

  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
  survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
  software like Aldus PageMaker including versions of Lorem Ipsum.

  Heading

Thanks

A: Explanation : The changes in color and background will happen when the value of cur will be between 125, and 177 (exclusive). Now, I divided the color in 51 shades (ie same as the difference 176 and 125). For every unit between 125 and 127 (again exclusive), the value of col increases/decreases by 5, depending upon the value of cur.
You may ask, that what's with 51 shades, and inc/dec in 5. Then the reason is because (5 * 51) = 255 i.e. max possible value of col for rgb().
NOTE : Expand it to full screen, while trying out snippet.

var col = 0;

$(window).scroll(function() {
  var cur = $(this).scrollTop();

  if (cur <= 125) {
    col = 0;
  } else if (cur > 125 && cur <= 176) {
    col = (cur - 125) * 5;
  } else {
    col = 255;
  }
  var col2 = 255 - col;

  $('section').css("color", "rgb(" + col + "," + col + "," + col + ")").css("background", "rgb(" + col2 + "," + col2 + "," + col2 + ")")
});
section {
  height: 80vh;
}

  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
  survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
  software like Aldus PageMaker including versions of Lorem Ipsum.

  Heading


text:
Q: Prove that I -xx* is singular if and only x*x = 1 (=>) Suppose  I - xx* is singular if and only there is a y such that (I−xx*)y=0, i.e. xx* y=y. Now set λ=x* y. Then y=λx, i.e. xx* λx=λx
Thus λx(x* x) = λx => x* x = 1
(<=) Suppose x*x = 1
Please help

A: On top of the fact that your standing fragment of a proof is mostly incomprehensible, note that for matrices: $AB = 0$ does not imply $A = 0$ or $B = 0$.
Hint: Note that $xx^*$ has eigenvalues $0$ and $\|x\|^2 = x^*x$. A matrix is singular if and only if $0$ is one of its eigenvalues.
Alternative approach: assuming $x \neq 0$, extend $\frac{x}{\|x\|}$ into an orthonormal basis.  Find the matrix of $I - xx^*$ relative to this basis.

A: Just start from the basics. $I-xx^*$ is singular if and only there is a $y$ such that $(I-xx^*)y=0$, i.e. such that $xx^*y=y$. Now set $\lambda=x^*y$. Then $y=\lambda x$, i.e. $xx^*\lambda x=\lambda x$, and you have almost proved one direction.
Make sure that you are aware at each step which expressions are scalars.

redpajama_set_name: RedPajamaStackExchange


text:
Q: textarea not rendering properly on an ajax load I am having issue with loading a html textarea via ajax, essentially the text area's content is rendering outside of the textarea.
Here is the javascript call
function editForm(button,type,id)
{
if (id == null)
    id = -1;
$("#errMsg").html("");
parentID = button.parentNode.id;
cFormName = parentID.replace("controls_","");

$("#addAnother").load("getHTML.php", {addAnother:type,formID:cFormName,id:id},
    function()
    {
        $("#"+cFormName).html($("#addAnother > form").html());//grab the form
        $("#"+parentID).html($("#addAnother > p").html());//grab the controls
    }//end function
);//end ajax load
}

Here is the response (I had to change the img tags to imageTag to post)
<form class="wrapped" id="additional-info0" method="post" action="http://192.168.2.107/resumes/getHTML.php">
<fieldset>

        Additional Information:
        <textarea cols="75" type="text" name="additional-description[]" size="80" />asdfasdfdfasf</textarea>
         <imageTag src="assets/img/delete.png" alt="Delete">

Maecenas blandit nulla sit amet urna posuere lacinia ultrices libero scelerisque. Pellentesque imperdiet iaculis ullamcorper.
            E.g. Mauris feugiat urna non lacus gravida in pulvinar dolor hendrerit.

            <imageTag src="assets/img/add-another2.jpg" alt="Add Another" /> Add another description point

</fieldset>

         Save

     Clear

A:  <textarea cols="75" type="text" name="additional-description[]" size="80" />asdfasdfdfasf</textarea>

You've terminated the textarea tag ...
<textarea ... /> <-- remove the /


text:
Q: Dell G3 3590 microphone not working I'm having problems with the internal microphone of my dell G3 for since I installed Linux (first with in Manjaro, and now the same problem in Ubuntu).
Right now: basically the sound is working fine, everything seems ok (despite the fact that there is no detection of input device)

In alsamixer also seem ok with one exception, there is no internal microphone detected

but there is this two input source in the right at alsamixer, I can switch both between "Headset Mic" and "Headphone Mic" which dos not affect anything at first when I switch between then.
I tried to use audacity to test the mic and see if I could get any sound at all, I can control this options of mic

If I select any of the HDA Intel PCH: ALC3254 Analog I get no sound, and if I select any of the Alt Analog I get a static noise, what is curious about it is that in the DELL's website in windows drivers you can find this "Realtek ALC3254 High Definition Audio Codec Driver".
At this point I noticed another thing, if I connect a headset things start to change, in the settings->sound I got two options

If I select in the input device "Headset Microphone - built-in Audio" everything works normally, but if I select "Microphone - Built-in Audio" then everything just mute, I can't hear anything from the computer and audacity changes too, now only the "Alt Analog" inputs got available, and all of them just output static.
A thing that I notice is that in dell's website there is a mention that this laptop has two microphone input,
My guess is: Somehow the way that they assemble these two microphones kinda bug everything.
Do you have any ideas how can I solve it?
edit1: I tried update the bios, but no success. A curious thing that i notice in the Pulse Audio Volume Control->Input Devices there is a "Monitor of Build-in Audio Analog Stereo" which is playing the same thing that the Volume Control->Output Devices "Speakers".

quick update 06/01/20
i try call the dell technical services and they basically said that once you buy a product with a operational system, they cannot provide you ANY support to other operational system even though they have all that is needed to.
i have a friend who bought a G3 with Ubuntu standard, and i'll try to "pirate" a copy of dell recovery tools for Ubuntu, from him service tag and i'll update you guys here.

A: THIS IS WHAT WORKED FOR ME,
DELL G3 3590 is certified in Ubuntu 18.04 ONLY. It's very weird that later versions break functionality in this laptop.
The Dell G3 3590 version I have is the revised one (2019 version) but I guess the older 3590 version should work as well.
Do not install Ubuntu 20.04 or other version except 18.04 on this notebook.
I just did a Fresh install and at first sound wasn't working, then a Automatic Update at first boot (it's common when fresh install to get an update) added the sound and microphone working. If not, just apt-get update && apt-get upgrade
Then I added additional drivers for Nvidia and is working nice.
UPDATE
On February aprox. a new version of ubuntu was released (18.04.4) and it has an optional upgrade called HWE that contains newer kernel and stuff. My solution worked but in some point, audio from the headphone jack was missing.
running sudo apt-get install --install-recommends linux-generic-hwe-18.04 xserver-xorg-hwe-18.04 solved this issue. So I have fresh install ubuntu 18.04.4, updated it and finally updated to HWE and have all sound working! internal and external as well.
WHAT A RIDE!!!

A: If you were able to achieve static noise while recording, you were close to victory. You just had to change the sampling rate using console commands.

A: I had the same problem. The only solution I found was to reinstall the system with dell's ISO.
I know it's not the best solution. But I really didn't find another one.

Dell Linux Recovery Image Create Linux installation media for your
  Dell device. Need to install or reinstall Linux on you Dell
  system? Download a Dell ISO recovery image file and use the Dell
  OS Recovery Tool to create a bootable USB drive.
What you will need

*

*The Service Tag or product ID of the device you need a recovery image for.

*A hard drive or removable media with access rights and at least 8GB of available data storage space for the download.

*A blank USB drive with at least 8GB of space to create the installation media.

*Preview the instructions before you begin.

Reference


text:
Q: Spring rspec not speeding up tests Running a single test in our test suite takes anywhere from 20 - 30 seconds. Prior to adding spring and spring-commands-rspec, the output from running a test would look like this.
Finished in 21.99 seconds (files took 21.64 seconds to load)
1 example, 0 failures

Randomized with seed 52406

The 22 second file load time suggested that adding the aforementioned gems would help, but after doing so the test is still just as slow (I am running with bundle exec spring rspec [path_to_spec]. The new output (see below) suggests the file time has in fact been drastically improved (down from 21.64 seconds to 1.25 seconds), but the overall speed of the test is basically the same. This seems very odd and unexpected based on what I have read about the expected effects of adding these gems.
Finished in 21.86 seconds (files took 1.25 seconds to load)
1 example, 0 failures

Randomized with seed 7594

Any thoughts on why the test is still just as slow, and does anyone have tips on how to fix this/speed up the test? Thanks.

A: This is what I'd expect, to be honest. Spring's raison d'être is to speed up the loading of files -- and once RSpec starts running, Spring's job is done. And it's done quite a job – going from 21.64 seconds to 1.25 is pretty good!
Now you can concentrate on what RSpec is doing and how to speed that up. While RSpec does have a --profile option which will tell you which examples are running the slowest, in your output above you only have one example so that's not going to tell you anything you don't already know.
If it's a system test that is spending that time in getting some form of headless browser to start up, say, then you may find that adding more tests don't double or triple the running time because the setup is shared across tests and the impression of a 'slow test suite' might fade. On the other hand, if the example that's running slow is a unit test I'd be very concerned.
This post on the Evil Martians website has some pointers for looking at where the slow patches of whole test suites are (mostly involving the TestProf gem). It's probably overkill for a single test, but if you run out of other ways to find clues you might find some use in it.


text:
Q: Ribbon does not get created when WordProcessingDocument is created out of byte[] Ribbon gets created when I open the WordProcessingDocument from the path of a docx file. However It does not get created when I open the same from the byte content of the docx file. The below does not show up the ribbon in the docx file:-
public void AddRibbonToTemplate(byte[] templateContent)
        {
                string sanitizedRibbonXml = GetRibbonXML().ToString().Replace("xmlns=\"\"", "");
                MemoryStream stream = new MemoryStream();
                stream.Write(templateContent, 0, templateContent.Length);
                using (WordprocessingDocument myDoc = WordprocessingDocument.Open(stream, true))
                {
                    MainDocumentPart mainPart = myDoc.MainDocumentPart;

                    if (myDoc.GetPartsCountOfType<RibbonExtensibilityPart>() > 0)
                        myDoc.DeletePart(myDoc.GetPartsOfType<RibbonExtensibilityPart>().First());

                    RibbonExtensibilityPart ribbonExtensibilityPart = myDoc.AddNewPart<RibbonExtensibilityPart>();
                    ribbonExtensibilityPart.CustomUI = new DocumentFormat.OpenXml.Office.CustomUI.CustomUI(sanitizedRibbonXml);
                    myDoc.CreateRelationshipToPart(ribbonExtensibilityPart);

                }
                stream.Close();
         }

The below shows the ribbon:-
public void AddRibbonToTemplate(string documentFileName)
        {
            string sanitizedRibbonXml = GetRibbonXML().ToString().Replace("xmlns=\"\"", "");
            using (WordprocessingDocument myDoc = WordprocessingDocument.Open(documentFileName, true))
            {
                MainDocumentPart mainPart = myDoc.MainDocumentPart;

                if (myDoc.GetPartsCountOfType<RibbonExtensibilityPart>() > 0)
                    myDoc.DeletePart(myDoc.GetPartsOfType<RibbonExtensibilityPart>().First());

                RibbonExtensibilityPart ribbonExtensibilityPart = myDoc.AddNewPart<RibbonExtensibilityPart>();
                ribbonExtensibilityPart.CustomUI = new DocumentFormat.OpenXml.Office.CustomUI.CustomUI(sanitizedRibbonXml);
                myDoc.CreateRelationshipToPart(ribbonExtensibilityPart);
            }
        }

GetRibbonXml() gets the XML of the ribbon. I am removing the xmlns="" which gets added in the ribbon element (from question here).
Could somebody throw some idea why the ribbon does not get added. Even the customUI folder does not get added in the word zip file. Could anybody help.

A: I should have verified the stream by writing the same to a file. Following is the code:-
public void AddRibbonToTemplate(byte[] templateContent)
        {
                string sanitizedRibbonXml = GetRibbonXML().ToString().Replace("xmlns=\"\"", "");
                using (MemoryStream stream = new MemoryStream())
                {
                    stream.Write(templateContent, 0, (int)templateContent.Length);
                    using (WordprocessingDocument myDoc = WordprocessingDocument.Open(stream, true))
                    {
                        MainDocumentPart mainPart = myDoc.MainDocumentPart;

                        if (myDoc.GetPartsCountOfType<RibbonExtensibilityPart>() > 0)
                            myDoc.DeletePart(myDoc.GetPartsOfType<RibbonExtensibilityPart>().First());

                        RibbonExtensibilityPart ribbonExtensibilityPart = myDoc.AddNewPart<RibbonExtensibilityPart>();
                        ribbonExtensibilityPart.CustomUI = new DocumentFormat.OpenXml.Office.CustomUI.CustomUI(sanitizedRibbonXml);
                        myDoc.CreateRelationshipToPart(ribbonExtensibilityPart);

                    }
                    using (FileStream fileStream = new FileStream("Test20.docx",
                    System.IO.FileMode.CreateNew))
                    {
                        stream.WriteTo(fileStream);
                    }

                }

         }


text:
Q: Change in the position of mass under the influence of an impulse I know that $J=m\Delta v$. Since $\Delta v$ is the only variable that contains any information about distance I can isolate it resulting in $\frac{J}{m}=\Delta v$. Generally change in position can be written as $\Delta R=v\Delta t$ and in this case $\Delta v$ should be rewritable as $\Delta \frac{\Delta R}{\Delta t}$ giving me
$\frac{F\Delta t}{m}=\Delta \frac{\Delta R}{\Delta t}$. From here my intuition tells me that I shouls be able to multiply both sides by $\Delta t$, but I don't think would be entirely useful since the $\Delta t$ on the right hand side is stuck behind a second delta, so I feel as if I've backed myself into a corner. Is there some simpler path that I could be taking that I'm missing or is that path that I'm moving along good and going somewhere?


text:
Q: Razor view page with multiple partial view razor pages I am somewhat new to this and I am having trouble displaying a page which contains partial views and I want someone to look over my structure and maybe point out what I am doing wrong.
This is my main page in which I will display other razor page contents int it.
PROFILE PAGE:
@model Project.Models.PasswordModel
@{ ViewBag.Title = "Profile Page"}

//right column
@if(ViewBag.HasLocalPassword)

{ @Html.Partial("passwordChange") }

else { @Html.Partial("passwordSet")}

//left column

@Html.Partial("username")
@Html.Partial ("biography")

when I created the username and biography razor view pages this is what I had in the "Add View" box:
View engine: Razor(cshtml)
only the "Use a layout or master page: " was checked and the box underneath was left empty ( Leave empty if it is set in a Razor _viewstart file)
When I render the whole page all different parts are displayed but the username and biography areas are supposed to be filled with data from the database which isn't doing that. Only when I change the url to actually direct to username page that the proper information from the database is being displayed.
when I click on the change password button after entering new password information I get this error message:
The model item passed into the dictionary is of type 'Project.Models.PasswordModel', but this dictionary requires a model item of type 'Project.Models.UserNameModel'.
any help to how I can properly display different razor view pages into one or the right structure please help me out.

A: I normally use ajax calls to the controller for partial views like here How to populate a Table in View with Json results on click of button MVC
for your code you can pass a model to the partial in your call
@Html.Partial("_passwordSet", Model.passwordSet)

if you have a view model you can pass the part of the view model to the partial or you can pass the full model.  Whatever works best.


text:
Q: Run Flutter in both iOS and Web at the same time I am trying to build and run a project in both iOS and Web from VS Code. Is there any way to do this?
I have tried running flutter run -d all but that only runs iOS, even though flutter devices lists both of them

A: Yep, you can create a compound launch config in your .vscode/launch.json. This one creates three configs, one to launch on the current device (shown in the status bar), one to launch on iOS, and one to launch on Android. It then creates a compound config that will launch on iOS and Android devices at the same time. You can change one of the device IDs to chrome to launch on Chrome.
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Current Device",
            "request": "launch",
            "type": "dart"
        },
        {
            "name": "Android",
            "request": "launch",
            "type": "dart",
            "deviceId": "android"
        },
        {
            "name": "iPhone",
            "request": "launch",
            "type": "dart",
            "deviceId": "iphone"
        },
    ],
    "compounds": [
        {
            "name": "All Devices",
            "configurations": ["Android", "iPhone"],
        }
    ]
}

More info can be found on the Flutter wiki.


text:
Q: What is the maximum number of intersection of 3d dimention boxes for example, if I have 2d rectangles the total number of intersections is:
Two rectangles can intersect in at most two points .By looking at all possible pairs of rectangles, the maximum number of intersection is $2\binom{n}{2}=o(2n^2)$.
is it okay to apply this on 3d boxes as well? two boxes can intersect in at most three points, then the maximum number of intersection is $3\binom{n}{3}=o(3n^3)$.
can i apply this also on every dimension? maximum number of intersection of d dimension hyper-rectangles is $d\binom{n}{d}=o(dn^d)$?
I'll try to explain my idea, for intersections circles, I'll get at most pieces $o(n^2)$. for boxes, With all the box intersections, I will then have $o(n^3)$ boxes. is it true? Is this also true for a larger dimension?
for example when 2 circles intersect with each other I get at most 3 pieces, with 3 circles intersecting with each other, I get at most 7 pieces.

I want to generalize this to 3D and larger dimensions as well.


text:
Q: How to change the color of subtrees in tikz-qtree? Is there an elegant way to color subtrees in tikz-qtree, without going through each of the respective nodes and edges by hand?
The following code example shows the ugly way:
\documentclass{standalone}
\usepackage{tikz-qtree}
\begin{document}

\tikz{
\Tree
[.A
    [.B D ]
    [.\node[text=red]{C};
        \edge[draw=red];\node[text=red]{E};
        \edge[draw=red];\node[text=red]{F}; ]
]
}

\end{document}

Instead I would like to fix the color of a subtree just in one place, for example at its root node (hence at 'C' in the code example). Any suggestions?

A: There is a fairly simple way to color subtrees using the forest package, which has a similar syntax, but is more flexible than tikz-qtree. Here is an MWE:
\documentclass{standalone}
\usepackage{forest}
\begin{document}

\forestset{
    sn edges/.style={for tree={parent anchor=south, child anchor=north}},
    red subtree/.style={for tree={text=red},for descendants={edge=red}}}
\begin{forest}
sn edges
[A
    [B [D]]
    [C,red subtree
        [E]
        [F]]
]
\end{forest}

\end{document}


text:
Q: Ajax attached to Composite Component updates model but does not fire listener I have a custom component location. I want that, when a change is done, the model is update so another component (an autocomplete) is to show only results related to the location value. Also, that component is rerendered to reset it.
I have a page with the following code (simplified):
<h:form id="ticketForm">
  ...
  <loc:location id="locationId"                         <-- CUSTOM COMPONENT
    hiddenFieldValue="#{ticketCtrl.ticket.location}"
    visibleFieldValue="#{ticketCtrl.ticket.locationDescription}"
    rendered="#{ticketCtrl.ticketModifiable}">

    <f:ajax event="changeLocation" render=":ticketForm:gfhId"       <-- AJAX CALL.
      execute=":ticketForm:locationId" listener="#{ticketCtrl.locationListener}"/>
  </loc:location>
  ...
</h:form>

When the value in the component is changed, the model is updated and :ticketForm:gfhId is rendered as needed, but the listener(which performs additional resets) is not executed.
Attaching the ajax to a simpler control results in the listener being executed; v.g.
<h:inputText id="contactId"
  value="#{ticketCtrl.ticket.contactPerson}"
  disabled="#{not ticketCtrl.ticketModifiable}">
  <f:ajax event="change" render=":ticketForm:gfhId"
    execute=":ticketForm:locationId" listener="#{ticketCtrl.locationListener}"/>
</h:inputText>

works perfectly.
I do not know if it may be related as how the changeLocation event is fired; inside my component I define it as
<composite:interface>
   ...
   <composite:clientBehavior name="changeLocation" event="change" targets="visibleId"/>
</composite:interface>

with visibleId being a readonly text; when it is changed by javascript I fire the change event on it with JS.
function launchEvent(fieldName) {
  if ("fireEvent" in fieldName) {
    fieldName.fireEvent("onchange");
  } else {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    fieldName.dispatchEvent(evt);
  }
}

The info I find in other questions is about making ajax an inner part of the composite component, here I want ajax detached because I probably won't need it in other uses of the component.
I am using JBoss 6.1 wih Mojarra 2.1.9 and Richfaces 4.
Thanks in advance.
UPDATE:
Even after finding jarek.jpa's answer right, if someone wants to check the code it is here:
The composite component
http://pastebin.com/9wqMVfR5
The main form
http://pastebin.com/i39ys2D9

A: This may have to do with the "readonly" attribute set to true. Though you manage to send the change-event by hand (JS), the server-side processing of the listener may be dropped due to the readonly state. See e.g. jsf (richfaces) readonly input text validation.


text:
Q: Programming OOP in Javascript - Properly I'm interesting in improving my javascript code to be properly OOP.... currently I tend to do something like this:
jQuery(document).ready(function () {
    Page.form = (function () {
        return {
            //generate a new PDF
            generatePDF: function () {

            },
            //Update the list of PDFs available for download
            updatePDFDownloads: function () {

            },
            /*
             * Field specific functionality
             */
            field: (function () {
                return {
                    //show the edit prompt
                    edit: function (id, name) {

                    },
                    //refresh the value of a field with the latest from the database
                    refresh: function (id) {

                    }
                };
            }())
        };
    }());
});

In the end it's just mainly organized functions I suppose... what's a good resource where I can learn to program javascript in an OOP manner, or what suggestions would you have for improving my current style of programming?
It seems like I should do a sort of model prototype and have my form object inherit from that prototype.
(I'm using jQuery instead of $ because of conflicts with prototypeJS)

A: Your question is quite broad so I don't think a complete answer is possible here. But here are a few points.
Regarding the code you have shown. You're jumping a couple of redundant hoops.

*

*Unless you're accessing the DOM in some way, there is no need to wrap your code in jQuery(document).ready()

*There is no need to return an object from a self calling anonymous function unless you're closing over some private functions or data

The object you have created can be created more simply (a good thing) like this
var Page = {
    form: {
        //generate a new PDF
        generatePDF: function () {

        },
        //Update the list of PDFs available for download
        updatePDFDownloads: function () {

        },
        /*
        * Field specific functionality
        */
        field: {
            //show the edit prompt
            edit: function (id, name) {

            },
            //refresh the value of a field with the latest from the database
            refresh: function (id) {

            }
        }
    }
};

It's easier to read and less confusing, only do things that buy you something. see cargo cult programming
Here's an example using a self calling anonymous function to create private members
var Obj = (function() {
    privateFunction( param ) {
        // do something with param
    }

    var privateVar = 10;

    return {
        // publicMethod has access to privateFunction and privateVar
        publicMethod: function() {
            return privateFunction( privateVar );
        }
    }

})();

The structure you have used, object literals are very good, as you say, at grouping a set of functions (methods) and properties. This is a kind of namespace. It is also a way of creating a Singleton. You may also want to create many objects of the same Class.
JavaScript doesn't have classes like traditional OO languages (I'll get to that) but at the simplest level it's very easy to create a 'template' for creating objects of a particular type. These 'templates' are normal functions called constructors.
// a constructor
// it creates a drink with a particular thirst quenchingness
function Drink( quenchingness ) {
    this.quenchingness = quenchingness;
}

// all drinks created with the Drink constructor get the chill method
// which works on their own particular quenchingness
Drink.prototype.chill = function() {
   this.quenchingness *= 2; //twice as thirst quenching
}

var orange = new Drink( 10 );
var beer   = new Drink( 125 );

var i_will_have = ( orange.quenchingness > beer.quenchingness )
    ? orange
    : beer; //beer

var beer2  = new Drink( 125 );
beer2.chill();

var i_will_have = ( beer2.quenchingness > beer.quenchingness )
    ? beer2
    : beer; //beer2 - it's been chilled!

There's a lot to know about constructors. You'll have to search around. There are lots of examples on SO.
Inheritance, the foundation of OO, is not that intuitive in js because it is prototypal. I won't go into that here because you will more than likely not use js's native prototypal inheritance paradigm directly.
This is because there are libraries that mimic classical inheritance very effectively, Prototype (inheritance) or mootools (Class) for example. There are others.
Many say that inheritance is overused in OO and that you should favour composition and this brings me to what I initially set out to recommend when I started this rambling answer.
Design patterns in JavaScript are as useful as in any OO language and you should familiarise yourself with them
I recommend you read Pro JavaScript Design Patterns.
There, that's it

A: Some good sources for Object-Oriented JavaScript and JavaScript in general...
Online Articles

*

*How to "properly" create a custom object in JavaScript?

*https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript

*http://mckoss.com/jscript/object.htm

*http://ejohn.org/blog/simple-javascript-inheritance/

*JavaScript: How To Get Private, Privileged, Public And Static Members (Properties And Methods)
Books

*

*JavaScript: The Good Parts - Douglas Crockford

*Object-Oriented JavaScript - Stoyan Stefanov
I hope this helps.
Hristo

A: There isn't one correct way...  Some people use a framework to define their object, I like to just extend prototype directly.  Anyhow, I wanted to say that Oran Looney has some good posts on OO mechanics in JS:
http://oranlooney.com/classes-and-objects-javascript/
Its also worth looking at his other articles:
http://oranlooney.com/deep-copy-javascript/
http://oranlooney.com/functional-javascript/

A: The top 3 I suggest to read is

*

*JavaScript and Object Oriented Programming (OOP)

*Classical Inheritance in JavaScript

*Prototypal Inheritance in JavaScript
Have a nice reading!

A: The code we are using follows this basic structure:
//Create and define Global NameSpace Object
( function(GlobalObject, $, undefined)
{
    GlobalObject.Method = function()
    {
        ///
    }

}) (GlobalObject = GlobalObject || {}, jQuery);

//New object for specific functionality
( function(Functionality.Events, $, undefined)
{
    //Member Variables
    var Variable; // (Used for) , (type)

    // Initialize
    GlobalObject.Functionality.Events.Init = function()
    {
        ///
    }

    // public method
    this.PublicMethod = function(oParam)
    {
        ///
        ///<param type=""></param>
    }

    // protected method (typically define in global object, but can be made available from here)
    GlobalObject.Functionality.ProtectedMethod = function()
    {
        ///
    }

    // internal method (typically define in global object, but can be made available from here)
    GlobalObject.InternalMethod = function()
    {
        ///
    }

    // private method
    var privateMethod = function()
    {
        ///
    }
}) (GlobalObject.Funcitonality.Events = GlobalObject.Funcitonality.Events || {}, jQuery )

The strength to this is that it initializes the Global object automatically, allows you to maintain the intergrity of your code, and organizes each piece of functionality into a specific grouping by your definition. This structure is solid, presenting all of the basic syntactical things you would expect from OOP without the key words. Even setting up intelisense is possible with javascript, and then defining each peice and referencing them makes writing javascript cleaner and more manageable. Hope this layout helps!

A: I dont think it matters what language you use, good OOP is good OOP. I like to split up my concerns as much as possible by using an MVC architecture. Since JavaScript is very event based, I also use the observer design pattern mostly.
Heres a tutorial you can read about MVC using jQuery.


text:
Q: $wpdb->get_row not working on a single page. 500 Internal Server Error I constantly get 500 Internal Server Error while trying to query a db. The data is passed by Ajax to that specific page.
Here is the code:

DOMAĆI

                <?php

                    $igraci_home = $this->igraci_u_timu($league_id, $mec->home_team);

                    foreach ($igraci_home as $igrach){
                        /* Listam igrače */
                        echo "

                                    $igrach->ime $igrach->prezime

                                <input type='hidden' class='igracId' value='$igrach->id' />
                                <input type='hidden' class='brDresa' value='$igrach->brojDresa' />

";
                    }

                ?>

I have checked everything with the variables. Everything is fine.
And this is the insert_tim.php page that is sending Server Error.
<?php
global $wpdb;

$id = intval( $_POST['id'] );

$row = $wpdb->get_row("SELECT * FROM wp_pls_leaguemanager_person WHERE id = '$id'", ARRAY_A);

echo $row['ime'];

?>

It works on other pages.
Thanks!

A: Please, read this post carefully about AJAX in WordPress plugins.
You need to send AJAX requests to special script, not directly to your plugin! And then you handle request using actions.
But what you have done? - You send request to your script, so it knows nothing about WordPress :). WordPress must include your plugin and then your plugin will have access to native functions and classes.
Update. More detailed explanation.
AJAX is just calling your script from given link. When you call your script directly (http://site.com/wp-content/plugins/myplugin/insert_tim.php), then php begins to execute it and NOTHING MORE! It doesn't initiate WordPress engine. So $wpdb will be undefined variable that will throw exception on use (if exception display is disabled in your php config, then you will just see "Internal Server Error 500"). Of course, if you remove $wpdb usage - all will be OK.
And what does WordPress's ajaxurl (http://site.com/wp-admin/admin-ajax.php) change? If you will open this file - you will see, that it contains WordPress engine load:
/** Load WordPress Bootstrap */
require_once( dirname( dirname( __FILE__ ) ) . '/wp-load.php' );

So if you pass ajaxurl to your AJAX call - then this script will load WordPress engine, then using actions - will call your function and your function will see $wpdb class.
Remember the rule: Don't call your plugin's PHP scripts directly using AJAX. Use native WordPress behavior.

A: I had the same problem. Actually, AJAX doesn't get $wpdb object. You need to set your path there and it will work fine.
require_once( 'path/to/wordpress/wp-includes/wp-db.php' );
if ( file_exists( 'path/to/wordpress/wp-content/db.php' ) )
    require_once( 'path/to/wordpress/wp-content/db.php' );

$wpdb = new wpdb( 'user', 'password', 'database', 'host' );


text:
Q: prove that $f_n(x) = \frac{n^2x}{1 + n^2x^2\log n}$ converge but not uniform
I have to prove that the sequence of functions
  $$
f_n(x) = \frac{n^2x}{1 + n^2x^2\log n},
$$ converges.

So I think that I can just show that $\lim_{n \to \infty} (f_n) = 0$ pointwise. But to show that the sequence does not converge uniformly, I need to show that $f_n$ has a point of maximum $x = \frac{1}{n \sqrt{\log n}}$ and at this point, the limit is equal to infinity. Is that correct?
And finally I need to show that $\forall \alpha > 0$ in the interval $\mathbb{R} \setminus (-\alpha,+\alpha)$, the sequence $f_n$ converges uniformly, but I don't have ideas how to do it.

A: $1).\ $ If $x=0$ the sequence clearly converges to $0$. If not, then $|f_n(x)|\le \frac{1}{x\log n}\to 0$ as $n\to \infty$ so $(f_n)$ is pointwise convergent.
$2).\ $ The trouble will be near zero, so take $x_n=1/n$. Then $x_n\to 0$ whereas $f_n(x_n)\to \infty$, and so $(f_n)$ is not uniformly convergent.
$3).\ $ $f_n$ is odd for each $n\ge 1$ so it suffices to check $[\alpha,\infty).$ In this case,$\ |f_n(x)|\le \frac{1}{\alpha\log n}$ so $(f_n)$ is uniformly bounded, and so converges uniformly.


text:
Q: RHEL8: Cannot read / modify / delete directory We have a cluster of flash drives (8TB) mounted on /data as per:
/dev/mapper/vg.data-lv.data on /data type ext4 (rw,relatime)

There are a couple of directories inside /data with one being tmp:
ls -lst /data/
total 1036468
...
1036360 drw-r--r-- 1 secadmin sudo 1061183488 Nov  8 13:10 tmp
...

For some reason this folder /data/tmp seems to be malfunctioning: Any attempts to modify its, delete it, list it contents etc. leads to the respective command idling / blocking forever not returning any results:
# ls /data/tmp
^C
#
# rm -rf /data/tmp
^C
#

I already ran fsck.ext4 -fvy to check the underlying file system but everything seems to be fine.
How can I get control back over this directory and what is the underlying issue that I lost control over it?

A: As @meuh wrote, this looks like a very large directory, and may have thousands or millions of files and/or subdirectories in it. The GNU ls and rm tools are not very useful for dealing with such large directories, because they try to sort or otherwise process the full output.
You could try "find /data/tmp -print" to generate a list of filenames, or "find /data/tmp -ls" to get a long listing.  This should immediately begin printing files, unless the directory has a very large number of empty blocks. In that case, you could also try "e2fsck -fD <dev>" to have it shrink the directory, but that may also take a long time.
It would also be useful to determine what was creating so many files in /data/tmp so that these files are either cleaned up when no longer needed, and/or put into a proper directory hierarchy instead of a single large directory.


text:
Q: "Confirm Form Resubmission" popup/error (after login error) in Spring MVC 3 I am getting "Confirm Form Resubmission" pop up-
1) When refresh the page (after login errors).
2) When press browser's back button after submit of the login page (after login errors).
My controller code is:
// Showing Login Page
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String showLoginPage(ModelMap model) {

    model.addAttribute("credentials", new Credentials());
    return "login";
}

// Submitting Login Form
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@ModelAttribute("credentials") Credentials credentials,
        BindingResult result, ModelMap model) {

        // Validation on Login form fields
        validator.validate(credentials, result);
        if (result.hasErrors()) {
            return "login";
        }

        return "redirect:success";
}

My steps are:
Case 1:
i) Left username blank and click on login button. This will show error "username can not be left blank"
ii) Now refresh the page. Then I will get the "Confirm Form Resubmission" pop up.
Case 2:
i) Repeat step 1 of case 1
ii) Then fill all the field correctly and then click on Login button. User will be redirect to success.jsp page
iii) now click on back button of browser and I will get "Confirm Form Resubmission" error on the page.
How can I remove this problem. Where is the mistake in my code ? Please guide me.
Thanks.

A: Rather than forwarding to the login jsp on error, you could save the BindingResult in RedirectAttributes and then redirect to login instead. The resulting POST-REDIRECT-GET should then resolve the "confirm form resubmission" issue for login errors.
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@ModelAttribute("credentials") Credentials credentials,
        BindingResult result, ModelMap model, RedirectAttributes attrs) {

        // Validation on Login form fields
        validator.validate(credentials, result);
        if (result.hasErrors()) {
            attrs.addFlashAttribute("org.springframework.validation.BindingResult.credentials", result);
            attrs.addFlashAttribute("credentials", credentials);
            return "redirect:login"; // Redirect to login, rather than forward
        }

        return "redirect:success";
}


text:
Q: How to ignore blank rows in a csv file I'm using dictreader to open some csv files, adding them to one big list of dictionaries, and then using dictwriter to write the list of dictionaries out to one csv file.
The problem I'm having is that the resultant csv file has a bunch of blank rows between rows with data. I guess when the csv files are being read, it's not ignoring blank rows.
Could someone please send me in the right direction to find how I say to ignore the blank rows?
I've tried finding this in the csv module but no joy.
Any help would be much appreciated please.
Hi! Thanks for replying!
I more want dictreader to read rows if there is anything of interest in them, but will ignore a row only if it's totally blank. Eg if I had
{'1': '', '2': 'two', '3': ''},
{'1': '', '2': '', '3': ''}

I would just want to keep
{'1': '', '2': 'two', '3': ''}

I've found that the following works for me
for dictionary in csv.DictReader(open(filename)):
    if any(x != '' for x in dictionary.itervalues()):

A: You can read a fake file object that skips the blank lines in the real file. I'm not familiar with exactly what you're doing, but this will work better than mac's answer if the blank lines are making your reading process crash, or you really don't want the blank lines ever in there.
class BlankLineSkipper(object):
    def __init__(self, file):
        self.file = file
    def __iter__(self):
        return (line for line in self.file if line.strip())
    def read(self):
        return ''.join(self)

>>> print open('lol.csv').read()
5,7,8

1,2,3

abc,lol,haha

>>> list(csv.reader(open('lol.csv')))
[['5', '7', '8'], [], ['1', '2', '3'], [], ['abc', 'lol', 'haha'], []]

>>> list(csv.reader(BlankLineSkipper(open('lol.csv'))))
[['5', '7', '8'], ['1', '2', '3'], ['abc', 'lol', 'haha']]

(You might need to implement readline() or something else to make your code work, depending on how it uses the file object.)

A: If I understand you correctly, you simply have to filter your dictionary for blank lines before dumping it to a file. A trivial example for getting you started:
>>> d = {'l1': 'data', 'l2': '   '}
>>> dict([(k, v) for k, v in d.iteritems() if v.strip()])
{'l1': 'data'}

Does this help?

A: Your iterating through lines form the dictreader and then only "using" lines that have values.
mac's list comprehension to check for values should be the correct method to clear out unwanted lines by returning an empty dictionary.  You can write out the resulting dictionary, {'2': 'two'}, using the dictwriter object even if all keys aren't present.
The sample below performs a check of the line dict to see if it has any values assigned.
column_headers = ["1", "2", "3"]
dictwriter = csv.DictWriter(open("output.csv", "wb"), fieldnames=column_headers)
for line in dictreader:
    # check if the line contains "interesting" values.
    # --> Result will be empty list if not and evaluate to False
    if [True for v in line.values() if v.strip()]:
        # line is not EMPTY, process as desired
        dictwriter.writerow(line)


text:
Q: Cannot stop HTML string being escaped in Blazor / razor I am having problems getting a string containing HTML to be output from a razor page as HTML. It always comes out HTMLencoded.
Now I know razor does this by default, but nothing I try to avoid this encoding seems to work.
Here is my page. I have defined an HtmlString and set some value of HTML. I put some simple HTML onto the page above and below my string, and that displays correctly (i.e. I see bold text, not  tags).
@page "/Skins/Email/Template"
@layout Skins.Email.Template
@using Microsoft.AspNetCore.Html
@using Microsoft.AspNetCore.Mvc.Razor
@using System.Web

This is some text

@HTMLBody

Some more text

@code {
    [Parameter]
    public HtmlString HTMLBody { get; set; } = new HtmlString("Test link here test");
}

I have tried using a string too, with the following attempts to get the raw content without encoding:
<text>@HTMLBody</text>

This still comes out HTML encoded.
@Raw(HTMLBody)

This gives an error "The name 'Raw' does not exist in the current context. Ditto for Html.Raw.
I have even tried explicitly HTMLDecoding, but makes no difference.
@HttpUtility.HtmlDecode(HTMLBody)

But still it is HTMLencoded. I have tried applying it twice, or three times, still the same.
@HttpUtility.HtmlDecode(HttpUtility.HtmlDecode(HTMLBody))

However, when I switch to HTMLEncode, I do see full HTML encoding (effectively double encoded) show up on the output. So this code is definitely running.
I am out of ideas. Is it actually possible to get an HTML string and actually put that raw string into a page with razor?
Also, please check version. This is .NET 6. Not MVC. It is not the same, and things have changed since MVC with regard to this.

A: Use a normal string for the parameter.
And then display @((MarkupString)HTMLBody)


text: Q: Android Cast Api to RTMP server I would like to make the server side application to save the android mirror screen by using Cast Api,  I made a lot of research there is no one talking about it. Can anyone help me out of this problem?


text:
Q: Outlook Add-in file download What I'm trying to do
Download a file from an Office Outlook add-in inside Outlook application in MacOS X "El Capitan"  ( not the web portal )
How I tried to do it
I have tried with:

*

*Blob

*data URL

*btoa - atob

*A tag with download variable

*internal window.open ( in a allowed domain )

*Applying Office Dev tutorial Office-Add-in-JavaScript-FileDownload ( with a modification to make it work in outlook due to OfficeExtension class)

But result is always the same: or it shows the file (i.e. images or text ), or Outlook prompts a mesage about that he cannot open a blob.
The only way that works is by opening an external browser window but I want to avoid it for UX and security reasons.
Note that it works perfectly in the web portal of Outlook.
Question
Does anyone knows when this will be allowed in Outlook (as it seems it works in Word, due to the mentionned tutorial ) or if it can be done?
Thanks for the help


text:
Q: rails unchanged file fields got deleted on updating nested forms with carrierwave I've two models: ad and variant
Model: Ad
has_one :variant
accepts_nested_attributes_for :variant

Controller AdsController strong parameters:
params.require(:ad).permit(:title, :desc, variant_attributes: [:custom_image_1, :custom_image_2, :custom_image_3])

View ads/_form.slim
= f.fields_for :variant, @ad.variant || Variant.new do |va|
  - 3.times do |i|
    = va.file_field "custom_image_#{i+1}"

In view I added the nested form fields using a loop. The problem is when I create any AD, that time suppose I upload only one image in variant form (custom_image_1). Now, I came back for editing and uploaded another image on the variant (custom_image_2).
After the update, I saw that my previously uploaded custom_image_1 is deleted and only custom_image_2 is present in the database.
What is the reason behind it?
I check the params while submitting the edit form. There only contains the custom_image_2 in submitted attributes.

A: Hope someone will find that useful:
In my strong parameters, I need to include :id to resolve this issue.
params.require(:ad).permit(:title, :desc, variant_attributes: [:id, :custom_image_1, :custom_image_2, :custom_image_3])


text:
Q: Android Menu item is displayed in overflow area even with app:showAsAction always I am using MainActivity to extend Activity class. Project is using minimum API as 11. When I am inflating Menu Items, it always gets displayed in overflow.
public class MainActivity extends Activity {
....
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the Menu Items
    getMenuInflater().inflate(R.menu.menu_main,menu);
    return true;
}

menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
 <menu xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 tools:context=".MainActivity">
 <item android:id="@+id/attach"
    android:title="Attachment"
    android:orderInCategory="1"
    app:showAsAction="always"/>

</menu>

Styles.xml

<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

A: Your MainActivity extends Activity not AppcompatActivity and you are using android: Theme.Holo.Light native theme so, can u just replace
app:showAsAction="always" with android:showAsAction="always"
and try, like
<?xml version="1.0" encoding="utf-8"?>
 <menu xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 tools:context=".MainActivity">
 <item android:id="@+id/attach"
    android:title="Attachment"
    android:orderInCategory="1"
    android:showAsAction="always"/>

</menu>

A: Set it as showAsAction="always"

A: Try this code,
to show in overflow :
yourapp:showAsAction="always"

to show underflow
yourapp:showAsAction="never"

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:yourapp="http://schemas.android.com/apk/res-auto">
    <!-- Search, should appear as action button -->
    <item
        android:id="@+id/attach"
        android:icon="@drawable/ic_action_hardware_keyboard_arrow_left"
        android:title="Attachment"
        android:orderInCategory="1"
        yourapp:showAsAction="ifRoom" />

</menu>

check this menu resource doc


text:
Q: Swift with iOS 5 deployment target What is the minimum deployment target for Xcode 6 and the new Swift language?  Specifically, can I still support iOS 5.0?

A: From one of the engineers working on Swift, iOS 7, Mavericks and later:

A: Swift is supported on devices running iOS 7 or later.


text:
Q: Case sObject ContactEmail Standard Field Before Insert Trigger Is the ContactEmail standard field on the Case sObject a "formula" field?
I plan to reference it during a before insert trigger, I am suspicious it shall not populated during a before insert trigger.
Per the official documentation: "The Case.ContactEmail field displays the Email field on the contact that is referenced by Case.ContactId. Label is Contact Email."
When I view the Case sObject metadata the field shows up as an email type.

A: Yes, this field is null before insert. This happens because formulas are only calculated when a record is loaded from the database. In a before insert, there's no data to load, so the field is null. It is available after insert, before update, etc.


text:
Q: JPQL : How to construct a WHERE clause? i would like to create a namedquery in JPQL, but i don't understand how it's working...
Here my entity:
@Entity
@NamedQueries({
    @NamedQuery(name = "Translation.lang",
                query = "SELECT t FROM Translation t WHERE t.reference.id = :refId AND t.language.lang = :lang")
})
@Table(name = "T_E_TRANSLATION_TRL")
public class Translation implements java.io.Serializable {

@Id
@Column(name = "TRL_ID", unique = true, nullable = false)
@TableGenerator(name="translationSeqStore",
    table="T_S_APP_SEQ_STORE_AST",
    pkColumnName="AST_SEQ_NAME",
    valueColumnName = "AST_SEQ_VALUE",
    pkColumnValue = "T_E_TRANSLATION_TRL.TRL_ID",
    allocationSize=1)
@GeneratedValue(strategy=GenerationType.TABLE,
    generator="translationSeqStore")
private Integer id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "TRL_REF_ID", nullable = false)
private Reference reference;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "TRL_LAN_ID", nullable = false)
private Language language;

@Column(name = "TRL_LABEL", nullable = false, length = 4000)
private String label;

Should i use LEFT JOIN on Reference & Language to select my translatation with these id ?
Thank you.

A: I think you want:
SELECT t FROM Translation t join fetch t.reference join fetch t.language WHERE t.reference.id = :refId AND t.language.lang = :lang

That will join (and fetch the LAZY reference and language) and return the Translations for the reference with ID refId and language with lang = lang.


text:
Q: Inserting Equations in Pages - Keyboard Shortcut? I use the "Insert > Equation..." feature in Pages quite frequently. Is there a keyboard shortcut to open this box faster than clicking through first "Insert" and then "Equation..."?

A: The defined shortcut is shown as Option & Command & E to enter the equation editor.


text:
Q: TCP - C# - Server Client Chat Compare I have managed to create a Server/Client chat system, where the client sends a message to the server and the the server sends the message to all the clients.
I want to extend this so that the Server compares the messages and then sends a message to the client.
For Example: If client 1 sends 10 and client 2 sends 20 the server will compare these and the server will send a message saying 20 is more than 10.
Is this possible to do? And if so how?
Server Code:
namespace Server
{
    public partial class Form1 : Form
    {

        private const int m_iMaxConnections = 2;

        struct Connection_Struct    // Define a structure to hold details about a single connection
        {
            public Socket ClientSpecific_Socket;
            public bool bInUse;
        };

        Socket m_ListenSocket;
        Socket m_SendSocket;

        Connection_Struct[] m_Connection_Array = new Connection_Struct[m_iMaxConnections]; // Define an array to hold a number of connections

        System.Net.IPEndPoint m_LocalIPEndPoint;
        static int m_iNumberOfConnectedClients;
        private static System.Windows.Forms.Timer m_CommunicationActivity_Timer;

        public Form1()
        {
            InitializeComponent();

            Initialise_ConnectionArray();
            m_CommunicationActivity_Timer = new System.Windows.Forms.Timer(); // Check for communication activity on Non-Blocking sockets every 200ms
            m_CommunicationActivity_Timer.Tick += new EventHandler(OnTimedEvent_PeriodicCommunicationActivityCheck); // Set event handler method for timer
            m_CommunicationActivity_Timer.Interval = 100;  // Timer interval is 1/10 second
            m_CommunicationActivity_Timer.Enabled = false;
            string szLocalIPAddress = GetLocalIPAddress_AsString(); // Get local IP address as a default value
            txtIPAddress.Text = szLocalIPAddress;             // Place local IP address in IP address field
            txtPort.Text = "8000";  // Default port number
            m_iNumberOfConnectedClients = 0;
            txtClientNo.Text = System.Convert.ToString(m_iNumberOfConnectedClients);

            try
            {   // Create the Listen socket, for TCP use
                m_ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                m_ListenSocket.Blocking = false;
                m_SendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Tcp);
            }
            catch (SocketException se)
            {   // If an exception occurs, display an error message
                MessageBox.Show(se.Message);
            }

        }

        private void Initialise_ConnectionArray()
        {
            int iIndex;
            for (iIndex = 0; iIndex < m_iMaxConnections; iIndex++)
            {
                m_Connection_Array[iIndex].bInUse = false;
            }
        }

        private void btnEnableServer_Click(object sender, EventArgs e)
        {

            // Bind to the selected port and start listening / receiving
            try
            {
                // Get the Port number from the appropriate text box
                String szPort = txtPort.Text;
                int iPort = System.Convert.ToInt16(szPort, 10);
                // Create an Endpoint that will cause the listening activity to apply to all the local node's interfaces
                m_LocalIPEndPoint = new System.Net.IPEndPoint(IPAddress.Any, iPort);
                // Bind to the local IP Address and selected port
                m_ListenSocket.Bind(m_LocalIPEndPoint);

                txtLog.Text = "Bind succeded";

                // Prevent any further changes to the port number
                txtPort.ReadOnly = true;
            }

            catch // Catch any errors
            {   // If an exception occurs, display an error message
                txtLog.Text = "Bind failed";
            }

            try
            {
                txtLog.Text = "Listening";
                m_ListenSocket.Listen(2); // Listen for connections, with a backlog / queue maximum of 2

            }
            catch (SocketException se)
            {
                // If an exception occurs, display an error message
                MessageBox.Show(se.Message);
            }
            catch // Silently handle any other exception
            {
            }

            m_CommunicationActivity_Timer.Start();  // Start the timer to perform periodic checking for connection requests
            txtLog.Text = "Accepting (waiting for connection attempt)";
            btnEnableServer.Enabled = false;

        }

        private void OnTimedEvent_PeriodicCommunicationActivityCheck(Object myObject, EventArgs myEventArgs)
        {   // Periodic check whether a connection request is pending or a message has been received on a connected socket

            // First, check for pending connection requests
            int iIndex;
            iIndex = GetnextAvailable_ConnectionArray_Entry(); // Find an available array entry for next connection request
            if (-1 != iIndex)
            {   // Only continue with Accept if there is an array entry available to hold the details

                try
                {
                    m_Connection_Array[iIndex].ClientSpecific_Socket = m_ListenSocket.Accept();  // Accept a connection (if pending) and assign a new socket to it (AcceptSocket)
                    // Will 'catch' if NO connection was pending, so statements below only occur when a connection WAS pending
                    m_Connection_Array[iIndex].bInUse = true;
                    m_Connection_Array[iIndex].ClientSpecific_Socket.Blocking = false;           // Make the new socket operate in non-blocking mode
                    m_iNumberOfConnectedClients++;
                    txtClientNo.Text = System.Convert.ToString(m_iNumberOfConnectedClients);
                    txtLog.Text = "A new client connected";

                    SendUpdateMesageToAllConnectedclients();
                }
                catch (SocketException se) // Handle socket-related exception
                {   // If an exception occurs, display an error message
                    if (10053 == se.ErrorCode || 10054 == se.ErrorCode) // Remote end closed the connection
                    {
                        CloseConnection(iIndex);
                    }
                    else if (10035 != se.ErrorCode)
                    {   // Ignore error messages relating to normal behaviour of non-blocking sockets
                        MessageBox.Show(se.Message);
                    }
                }
                catch // Silently handle any other exception
                {
                }
            }

            // Second, check for received messages on each connected socket
            for (iIndex = 0; iIndex < m_iMaxConnections; iIndex++)
            {
                if (true == m_Connection_Array[iIndex].bInUse)
                {
                    try
                    {
                        EndPoint localEndPoint = (EndPoint)m_LocalIPEndPoint;
                        byte[] ReceiveBuffer = new byte[1024];
                        int iReceiveByteCount;
                        iReceiveByteCount = m_Connection_Array[iIndex].ClientSpecific_Socket.ReceiveFrom(ReceiveBuffer, ref localEndPoint);

                        string szReceivedMessage;
                        if (0 < iReceiveByteCount)
                        {   // Copy the number of bytes received, from the message buffer to the text control
                            szReceivedMessage = Encoding.ASCII.GetString(ReceiveBuffer, 0, iReceiveByteCount);
                            if ("QuitConnection" == szReceivedMessage)
                            {
                                CloseConnection(iIndex);
                            }
                            else
                            {

                               txtLog.AppendText(szReceivedMessage + Environment.NewLine);

                                // Send message to each connected client.

                                //  int iIndex2;
                                for (iIndex = 0; iIndex < m_iMaxConnections; iIndex++)
                                {
                                    if (true == m_Connection_Array[iIndex].bInUse)
                                    {
                                        string szMessage;

                                        szMessage = szReceivedMessage;

                                        txtLog.Text = m_Connection_Array[m_iMaxConnections].ToString();

                                        byte[] SendMessage = System.Text.Encoding.ASCII.GetBytes(szMessage);
                                        m_Connection_Array[iIndex].ClientSpecific_Socket.Send(SendMessage, SocketFlags.None);
                                    }
                                }

                            }
                        }
                    }
                    catch (SocketException se) // Handle socket-related exception
                    {   // If an exception occurs, display an error message
                        if (10053 == se.ErrorCode || 10054 == se.ErrorCode) // Remote end closed the connection
                        {
                            CloseConnection(iIndex);
                        }
                        else if (10035 != se.ErrorCode)
                        {   // Ignore error messages relating to normal behaviour of non-blocking sockets
                            MessageBox.Show(se.Message);
                        }
                    }
                    catch // Silently handle any other exception
                    {
                    }
                }
            }
        }

        private void SendUpdateMesageToAllConnectedclients()
        {   // Send message to each connected client informing of the total number of connected clients
            int iIndex;
            for (iIndex = 0; iIndex < m_iMaxConnections; iIndex++)
            {
                if (true == m_Connection_Array[iIndex].bInUse)
                {
                    string szMessage;
                    if (1 == m_iNumberOfConnectedClients)
                    {
                        szMessage = string.Format("There is now {0} client connected", m_iNumberOfConnectedClients);
                    }
                    else
                    {
                        szMessage = string.Format("There are now {0} clients connected", m_iNumberOfConnectedClients);
                    }
                    byte[] SendMessage = System.Text.Encoding.ASCII.GetBytes(szMessage);
                    m_Connection_Array[iIndex].ClientSpecific_Socket.Send(SendMessage, SocketFlags.None);
                }
            }
        }

        private void CloseConnection(int iIndex)
        {
            try
            {
                m_Connection_Array[iIndex].bInUse = false;
                m_Connection_Array[iIndex].ClientSpecific_Socket.Shutdown(SocketShutdown.Both);
                m_Connection_Array[iIndex].ClientSpecific_Socket.Close();
                m_iNumberOfConnectedClients--;
                txtClientNo.Text = System.Convert.ToString(m_iNumberOfConnectedClients);
                txtLog.Text = "A Connection was closed";
                SendUpdateMesageToAllConnectedclients();
            }
            catch // Silently handle any exceptions
            {
            }
        }

        private void Close_And_Quit()
        {   // Close the sockets and exit the application
            try
            {
                m_ListenSocket.Close();
            }
            catch
            {
            }
            try
            {
                int iIndex;
                for (iIndex = 0; iIndex < m_iMaxConnections; iIndex++)
                {
                    m_Connection_Array[iIndex].ClientSpecific_Socket.Shutdown(SocketShutdown.Both);
                    m_Connection_Array[iIndex].ClientSpecific_Socket.Close();
                }
            }
            catch
            {
            }
            try
            {
                Close();
            }
            catch
            {
            }
        }

        public string GetLocalIPAddress_AsString()
        {
            string szHost = Dns.GetHostName();
            string szLocalIPaddress = "127.0.0.1";  // Default is local loopback address
            IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress IP in IPHost.AddressList)
            {
                if (IP.AddressFamily == AddressFamily.InterNetwork) // Match only the IPv4 address
                {
                    szLocalIPaddress = IP.ToString();
                    break;
                }
            }
            return szLocalIPaddress;
        }

        private int GetnextAvailable_ConnectionArray_Entry()
        {
            int iIndex;
            for (iIndex = 0; iIndex < m_iMaxConnections; iIndex++)
            {
                if (false == m_Connection_Array[iIndex].bInUse)
                {
                    return iIndex;  // Return the index value of the first not-in-use entry found
                }
            }
            return -1;      // Signal that there were no available entries
        }

    }
}

Client Code:
namespace Client
{
public partial class Form1 : Form
{

    Socket m_ClientSocket;
    System.Net.IPEndPoint m_remoteEndPoint;
    IPEndPoint m_localIPEndPoint;
    Socket m_ReceiveSocket;

    private static System.Windows.Forms.Timer m_CommunicationActivity_Timer;

    public Form1()
    {
        InitializeComponent();

        m_CommunicationActivity_Timer = new System.Windows.Forms.Timer(); // Check for communication activity on Non-Blocking sockets every 200ms
        m_CommunicationActivity_Timer.Tick += new EventHandler(OnTimedEvent_PeriodicCommunicationActivityCheck); // Set event handler method for timer
        m_CommunicationActivity_Timer.Interval = 100;  // Timer interval is 1/10 second
        m_CommunicationActivity_Timer.Enabled = false;

        string szLocalIPAddress = GetLocalIPAddress_AsString(); // Get local IP address as a default value
        txtIPAddress.Text = szLocalIPAddress;             // Place local IP address in IP address field
        txtPort.Text = "8000"; // Default port number

    }

    private void btnConnect_Click(object sender, EventArgs e)
    {

        // Connect the Socket with a remote endpoint
        try
        {
            // Create the socket, for TCP use
            m_ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_ClientSocket.Blocking = true; // Socket operates in Blocking mode initially
        }
        catch // Handle any exceptions
        {
            Close_Socket_and_Exit();
        }
        try
        {
            // Get the IP address from the appropriate text box
            String szIPAddress = txtIPAddress.Text;
            System.Net.IPAddress DestinationIPAddress = System.Net.IPAddress.Parse(szIPAddress);

            // Get the Port number from the appropriate text box
            String szPort = txtPort.Text;
            int iPort = System.Convert.ToInt16(szPort, 10);

            // Combine Address and Port to create an Endpoint
            m_remoteEndPoint = new System.Net.IPEndPoint(DestinationIPAddress, iPort);

            m_ClientSocket.Connect(m_remoteEndPoint);
            m_ClientSocket.Blocking = false;    // Socket is now switched to Non-Blocking mode for send/ receive activities
            txtLog.Text = "Connected";

            m_CommunicationActivity_Timer.Start();  // Start the timer to perform periodic checking for received messages
        }
        catch // Catch all exceptions
        {   // If an exception occurs, display an error message
            txtLog.Text = "(Connect attempt failed)\nRetry Connect";
        }

    }

    private void OnTimedEvent_PeriodicCommunicationActivityCheck(Object myObject, EventArgs myEventArgs)
    {   // Periodic check whether a message has been received
        try
        {
            EndPoint RemoteEndPoint = (EndPoint)m_remoteEndPoint;
            byte[] ReceiveBuffer = new byte[1024];
            int iReceiveByteCount;
            iReceiveByteCount = m_ClientSocket.ReceiveFrom(ReceiveBuffer, ref RemoteEndPoint);

            string szReceivedMessage;
            if (0 < iReceiveByteCount)
            {   // Copy the number of bytes received, from the message buffer to the text control
                szReceivedMessage = Encoding.ASCII.GetString(ReceiveBuffer, 0, iReceiveByteCount);

               txtResult.Text = szReceivedMessage;
            }
        }
        catch // Silently handle any exceptions
        {
        }
    }

    private void Close_Socket_and_Exit()
    {
        try
        {
            m_ClientSocket.Shutdown(SocketShutdown.Both);
        }
        catch // Silently handle any exceptions
        {
        }
        try
        {
            m_ClientSocket.Close();
        }
        catch // Silently handle any exceptions
        {
        }
        this.Close();
    }

    private void btnDisconnect_Click(object sender, EventArgs e)
    {

        try
        {
            String szData = "QuitConnection"; // Special code to signal 'close connection' to the server
            // This ensures that the server is aware the Client wants to close the connection
            // (TCP should otherwise automatically detect disconnection, but this approach ensures a clean disconnect)
            byte[] byData = System.Text.Encoding.ASCII.GetBytes(szData);
            m_ClientSocket.Send(byData, SocketFlags.None);
            m_ClientSocket.Shutdown(SocketShutdown.Both);
            m_ClientSocket.Close();

            btnConnect.Text = "Connect";
            txtResult.Text = "";

        }
        catch // Silently handle any exceptions
        {
        }

    }

    private string GetLocalIPAddress_AsString()
    {
        string szHost = Dns.GetHostName();
        string szLocalIPaddress = "127.0.0.1";  // Default is local loopback address
        IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress IP in IPHost.AddressList)
        {
            if (IP.AddressFamily == AddressFamily.InterNetwork) // Match only the IPv4 address
            {
                szLocalIPaddress = IP.ToString();
                break;
            }
        } return szLocalIPaddress;
    }

}
}


text:
Q: Why is my extension method not found? I want to add a method to string that convert space char to underscore (extension method), I deployed the code but why it doesn't work?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "moslem";
            string.SpaceToUnderScore(name);
        }

        public static string SpaceToUnderScore(this string source)
        {
            string result = null;
            char[] cArray = source.ToArray();
            foreach (char c in cArray)
            {
                if (char.IsWhiteSpace(c))
                {
                    result += "_";
                }
                else
                {
                    result += c;
                }
            }
            return result;
        }
    }
}

Why doesn't it work?

A: First put your extension method to a static class then invoke as name.SpaceToUnderScore()
var newstr = "a string".SpaceToUnderScore();

public static class SomeExtensions
{
    public static string SpaceToUnderScore(this string source)
    {
        return new string(source.Select(c => char.IsWhiteSpace(c) ? '_' : c).ToArray());
        //or
        //return String.Join("",source.Select(c => char.IsWhiteSpace(c) ? '_' : c));
    }
}

A: Extension methods should be written in static classes.
Example
public static class StringExtension
{
    public static string SpaceToUnderScore(this string source)
    {
        string result = null;
        char[] cArray = source.ToArray();
        foreach (char c in cArray)
        {
            if (char.IsWhiteSpace(c))
            {
                result += "_";
            }
            else
            {
                result += c;
            }
        }
        return result;
    }
}

A: Without changing the code in your extension method, add the extension method to a static class:
public static class MyExtensions // Name this class to whatever you want, but make sure it's static.
{
    public static string SpaceToUnderScore(this string source)
    {
        string result = null;
        char[] cArray = source.ToArray();
        foreach (char c in cArray)
        {
            if (char.IsWhiteSpace(c))
            {
                result += "_";
            }
            else
            {
                result += c;
            }
        }
        return result;
    }
}

Then call it like so:
string name = "moslem";
string underscoreName = name.SpaceToUnderScore(); // Omit the name parameter (prefixed with this) when called like this on the string instance.

// This would work to:
string underscoreName = MyExtentions.SpaceToUnderScore(name);

If you don't find the extension method, make sure you are using the namespace of the static class.

A: public static class MyStringExtenstionClass
{

    public static string SpaceToUnderScore(this string source)
    {
        string result = null;
        char[] cArray = source.ToArray();
        foreach (char c in cArray)
        {
            if (char.IsWhiteSpace(c))
            {
                result += "_";
            }
            else
            {
                result += c;
            }
        }
        return result;
    }
}

and like this
 string name = "John Doe";
 name = name.SpaceToUnderScore(); //no argument and called on instance of string


text:
Q: Proper way to pass values Assuming that we have the following class, is it better (in terms of oop) to pass the object of class Foo to Bar constructor rather than pass only the arguments baz and qux to Bar constructor?
class Foo
{
    public $baz, $qux;

    public function __construct($baz, $qux)
    {
        $this->baz = $baz;
        $this->qux = $qux;
    }

    public function main()
    {
        $bar = new Bar($this);
        //OR
        $bar = new Bar($this->baz, $this->qux);
    }
}

A: The first case is reasonable if object of Bar class has dependency injection in its __constructor:
class Foo
{
    public $baz, $qux;

    public function __construct($baz, $qux)
    {
        $this->baz = $baz;
        $this->qux = $qux;
    }

    public function main()
    {
        $bar = new Bar($this);
        //OR
        //$bar = new Bar($this->baz, $this->qux);
    }
}

class Bar
{
    private $fooMembers = [];

    public function __construct(Foo $foo_object)
    {
         // just for example
         $this->$fooMembers[] = $foo_object->baz;
         $this->$fooMembers[] = $foo_object->qux;
    }
}

A: In my opinion in terms of OOP the option to pass explicit dependencies is much better:
class Foo
{
    //...

    public function main()
    {
        $bar = new Bar($this->baz, $this->qux);
    }
}

In the other case you directly implement an GOD object anti-pattern. The Bar object doesn't need Foo, it needs Baz and Qux.
Imagine, that you need to create the Bar outside of Foo:
$baz = new Baz();
$qux = new Qux();
$foo = new Foo($baz, $qux);
$bar = new Bar($foo);

Do you see the problem? Now you always have to create Foo in order to create Bar.
Update: check this post - Flaw: Digging into Collaborators, it explains in more details why you should prefer passing dependencies directly.

A: Usually, it is better to pass arguments because they are explicit and code can be read easily.
But, there are some cases where the arguments are too numerous or too complex. Take this for example:
public function __construct(arg1, arg2, arg3, arg4, arg5)
{
    if (arg1 == 1)
    {
        $this->property1 = arg2;
        $this->property2 = arg3;
    } else {
        $this->property1 = arg4;
        $this->property2 = arg5;
    }
}

In this case, only some of the arguments are used on each instantiation. It would be cleaner to define the constructor like this:
public function __construct(Foo $foo)
{
    if ($foo->arg1 == 1)
    {
        $this->property1 = $foo->arg2;
        $this->property2 = $foo->arg3;
    } else {
        $this->property1 = $foo->arg4;
        $this->property2 = $foo->arg5;
    }
}

It does the same thing, but it would be easily readable at instantiation point. There may be cases where the argument scheme is even more complex.
I recommend reading about Builder design pattern. You will find examples of when to user objects as arguments.


text:
Q: Render out nestled arrays in an object via map I have data that looks like:
{
  title: "Category title",
  description: "Example description",
  lists: [
    {
      id: "popular",
      title: "Popular",
      items: [
        {
          id: 1,
          title: "title",
          provider: "provider",
          image: ""
        },
      ....
      ]
    },
    {
      id: "new",
      title: "New",
      items: [
        {
          id: 4,
          title: "title4",
          provider: "provider",
          image: ""
        },
       ....
      ]
    }
  ]
}

I want to render it out, and the object contains two nestled arrays - lists and items and for that I use map like this:
return (
    <>
      {iconItems?.lists.map((icon, i) => {
        return (
          <>

{icon.title}

            {icon.items.map((i) => {

{i.title}
;
            })}
          </>
        );
      })}
    </>
  );

However, above will not work, and only title will be rendered out. What I am missing? Working sandbox: https://codesandbox.io/s/quirky-jerry-wfzso2?file=/src/App.js
I have tried to add id to the key props as, after Googling, could be an issue. But that didnt fix the problem.

A: You need to return value from your function. Adding return like this will make it work:
return
{i.title}
;


text:
Q: R splm: Spatial panel with no exogenous regressors I want to estimate the spatial panel autoregressive model
y_{t} = a + \rho W y_{t} + \epsilon_{t}

where a is a vector of individual fixed effects. I am using the excellent splm package in R.
Note that I don't have any independent variables X here - if I include some regressors X there is no problem, but I wonder how to specify the model with splm in the absence of independent variables.
library(splm)
library("spdep")
data("Produc", package = "Ecdat")
data("usaww")
usalw <- mat2listw(usaww)

# this works well since I have independent regressors
spml(formula = log(gsp) ~ log(pcap), data = Produc,
     listw = usaww, lag = TRUE, spatial.error = "none", model = "within",
     effect = "twoways")

 # this does not work
 spml(formula = log(gsp) ~ ., data = Produc,
      listw = usaww, lag = TRUE, spatial.error = "none",
      model = "within", effect = "individual")

A: To estimate an "empty" model (intercept only) the formula has to be y ~ 1. This currently works with random or no individual effects, "within" (fixed effects) estimators need a fix.
A workaround for getting the FE estimates: explicit demeaning of the data
    library(plm)
    spml(formula = Within(log(gsp)) ~ 1, data = Produc,
         listw = usaww, lag = TRUE, spatial.error = "none",
         model = "pooling")


text:
Q: How get them to work - npm & sails (html-pdf) EDIT : Well I'll keep it simple and I'll ask all my other issues in other posts if need be. The original post was way too vast, hoping someone would answer me with a guide through all that needs to be known to use sails to its full potential. Sorry.
First of all, I'm quite new to angular, npm, and sails.js, but I have a very good Javascript base.
All I know about those come from the 'Sails.js in Action' book.
I'm trying to use an npm package (html-pdf to name it), but I can't get it to work.
I need to create a pdf invoice from the webpage.
So I installed the html-pdf package via npm install html-pdf --save into my sails project. Then just to test it out and get it to work, I used my home page which was currently blank and added some text and a 'save as pdf' button.
Here is the ejs homepage code (in views) :

Accueil

Bienvenue !

Test création PDF

Si vous avez des questions ou des problèmes,

veuillez contacter l'assistance technique.

            <button class="btn btn-success btn-lg" type="button" ng-click="printPdf()">
              Imprimer
              </button>

Now here is the first thing I tried (quite a copy of the example code) for the printPdf function from my assets/js/controllers/homePageCtrl.js :
angular.module('teknik').controller('homePageCtrl', ['$scope', '$http', function($scope, $http) {

    $scope.printPdf = function(){
      var fs = require('fs');
      var pdf = require('html-pdf');
      var html = fs.readFileSync('./views/homepage.ejs', 'utf8');
      var options = { format: 'Letter' };

      pdf.create(html, options).toFile('/pdfs/test.pdf', function(err, res) {
        if (err) return console.log(err);
        console.log(res);
      });
    };

}]);

It gives me an error on the var fs = require('fs'); line (Can't find variable: require) so I tried a few changes afterward. I found this example Sails EJS-view after html-pdf usage does not render image and tried to change the code to fit my needs but it also gave me an error on the beginning of the code (same error but I don't have that adaptation anymore).

A: I'm no expert on this topic, but I think I can see exactly the gap in your knowledge that's giving you so much trouble.
npm modules, and most of the documentation that goes with them, are geared towards using the modules in code run on the server. From what I can see in your code above, you are running the code in the client's browser. Npm modules and the whole require framework they use is not set up there.
In Sails, the code you write in your controllers, services, and models (pretty much anything in your /api/ folder is run server-side, so requiring and using npm modules will work there.
Code you put in your /assets/ folder is different. Files here have javascript that is sent (without being run) to the browser on a client machine and run there. Npm modules are not set up to work there.
Sails views are a bit of a confusing case: the templating is done on the server side (all the <% ... %> blocks are evaluated), but none of the javascript outside those blocks is run until a client browser runs it later. For example, event handler code is all client-side.
If you do need libraries etc that run client side, you can do it the "old fashioned" way: add a javascript asset, and link to it from the file where you need to run it, same as jquery, etc. So, if you have the file /assets/js/some_library.js in your project, then in an html file or view, you can add:

Npm can be an awkward place to find scripts to use in this way. Sometimes you can dig into the npm folder and find a file in a lib or dist folder that you can use like I've used some_library.js above, but not always. There is probably a more browser-oriented source for any of the functions you are trying to get from npm.
Hope this helps!


text:
Q: make promise.all wait until both API's are done before it completes I have a profile that is doing this..
Promise.all([this.fetchInsights(), this.fetchTouchpoints()])
     .then(([insights, touchpoints]) =>
       console.log(insights, touchpoints)
     )

Here is the fetchInsights()
fetchInsights = () => {
  fetch('API_URL' + this.queryParams.custId + '/' + this.queryParams.acctNo, {
    method: 'GET', // or 'PUT'
    headers:{
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then(res => res.json())
  .catch(error => console.error('Error:', error));
};

Here is the fetchTouchpoints()
  fetchTouchpoints = () => {
    fetch('API_URL' + this.queryParams.custId + '/' + this.queryParams.acctNo, {
      method: 'GET', // or 'PUT'
      headers:{
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    }).then(res2 => res2.json())
    .catch(error => console.error('Error:', error));
  };

When I run this, the page reads undefined, undefined right away. This is because insights and touchpoints are both undefined since the API's calls are not finished.
When I look at the log in Eclipse (this is a Springboot app), I see that the response is both successful and it prints out the response in console there... but the app doesn't update.
How can I make it so that Promise.all prints the log AFTER both API calls are done?
I tried putting Promise.all in componentDidMount and in render()
Any help would be greatly appreciated!!

A: You forgot to return the promises.
Btw, for code readability, use template strings
Here is the fixed fetchInsights:
fetchInsights = () => {
  return fetch(`API_URL${this.queryParams.custId}/${this.queryParams.acctNo}`, {
    method: 'GET', // or 'PUT'
    headers:{
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then(res => res.json())
  .catch(error => console.error('Error:', error));
};


text:
Q: Advantages and disadvantages between sql 2005 and sql 2008? Exact duplicate:

Advantages of MS SQL Server 2008 over MS SQL Server 2005?

i am a sql developer and i use sql 2005. i want to now to pass to 2008 but i am a little affraid. can anyone gives me some advices about this. should i still continue using sql 2005 or is better pass all my projects to 2008 due to better performace?

A: Who is going to use your projects; if they are going to customers with existing SQL Licenses then 2005 might be the way to go; assuming they are running 2005. SQL 2005 databases will work on 2008; though if you use some of the new language features in 2008 then the SQL2008 databases wont be backwards compatible to 2005.
If you are controlling where they are going to be deployed; some of the new features in sql 2008 might be of interest; better full text search, improved Analysis services, reporting services and some language tweaks. If you are managing the servers; your admins will likely appreciate the new management features in 2008.

A: I moved to 2008 because I am heavy into SSIS and have large databases meaning: The backup compression and increased concurrent processes in SSIS for 2008 make it worth it for me.

A: I moved 6 projects from 2005 to 2008 without any problems except reporting services. To me the biggest benefit is the SQL Management Studio enhancements like auto complete and change history.
The only reason I did upgrade was because I work in education and Microsoft is very gracious on licensing.

A: In general, unless you hear that it is a disaster, I think you should strive to use the most recent release at the earliest opportunity.  The advances in server functionality and the tool set will usually offset the time it takes you to learn the new features.  All software is built with planned obsolescence in mind, so you will eventually need to migrate to newer technology.  If you make a habit of migrating your systems to the latest technology, you will find that the migrations become relatively painless.

A: One of the benefits of SQLServer 2008 with respect to SSIS is that it includes very fast bulk connectors for Oracle and Teradata (well, the development and enterprise versions do).
So if you need to move data between SQLServer 2008 and those databases you get this for no additional cost.
See Microsoft Connectors for Oracle and Teradata by Attunity
Another major benefit in SQLServer 2008 is the new Change Data Capture (CDC) functionality which means you can build your application in any way you like and then if at later time you are interested in starting some processing when table X changed, you can turn on CDC for that table and get a change table that contains all the changes to table X with minimal overhead. Ben Hall did a useful post on this.

A: I think SQL 2008 has somewhat advantage in compare to sql 2005

*

*New data types(date,time,files stream)
2.Backup compressin
3.Data compression
4.policy based management.
If anyone know better answer kindly inform


text:
Q: Interrupt completion block based animations to perform separate animations I am using block based animations to simulate dealing cards as an intro animation for a game. The animation works great unless the user causes a segue to fire DURING the animation, where we perform additional animations in order to get the effect a "sliding" transition from source to destination view controller. What happens now is the cards that have already been "dealt" slide off screen appropriately, and if there are cards that have not been dealt, it deals it in the middle of the transition and then the card disappears when the destination view controller is pushed. It's very ugly.
I have tried 'view.layer removeAllAnimations' which didn't help (I did import quartzcore). What I want to do is cancel the pending animations in the completion blocks, and simply perform the segue animations.
Here's the "dealing" code:
[UIView animateWithDuration:0.20f
                  delay:0.20f
                options:UIViewAnimationOptionCurveEaseOut
             animations:^
{
 _fiveOfHearts.center = CGPointMake(90, 198);
 _fiveOfHearts.transform = fiveOfHeartsTransform;
}

             completion:^(BOOL finished)
{[UIView transitionWithView:_fiveOfHearts duration:0.20f options:UIViewAnimationOptionTransitionFlipFromRight animations:^{
     _fiveOfHearts.image = [UIImage imageNamed:@"52"];
 }completion:nil];
 [UIView animateWithDuration:0.30f
                    delay:0.0f
                  options:UIViewAnimationOptionCurveEaseOut
               animations:^
  {
   _jackOfHearts.center = CGPointMake(128, 196);
   _jackOfHearts.transform = jackfHeartsTransform;
  }
               completion:^(BOOL finished)
  {[UIView transitionWithView:_jackOfHearts duration:0.40f options:UIViewAnimationOptionTransitionFlipFromRight animations:^{
       _jackOfHearts.image = [UIImage imageNamed:@"112"];
   }completion:nil];
   [UIView animateWithDuration:0.30f
                         delay:0.0f
                       options:UIViewAnimationOptionCurveEaseOut
                    animations:^
    {
        _aceOfHearts.center = CGPointMake(162, 196);
        _aceOfHearts.transform = aceOfHeartsTransform;
    }
                    completion: ... and so on.

The segue code looks something like:
for (UIView *iv in src.view.subviews) {
    if (iv.tag != 99999) {
        [UIView animateWithDuration:0.5f animations:^{iv.center = CGPointMake(iv.center.x - 600, iv.center.y);}];
    }
}

A: You could add a global BOOL say hasUserSkippedOn once the user presses to move on set it to YES and then every time you hit a completion block check if _hasUserSkipped is still YES then do not proform any more. Normally on blocks it has a default end bool but I am not too sure if animations blocks have the end bool.


text:
Q: jquery ajax request using OPTIONS instead of GET/POST - only on iPad? I've got a site under development that is using lots of AJAX calls. I'm using the shortcuts - .get(), .post() and .load()
On the desktop machine, everything works just fine using any browser I've tested so far. But when I test using my iPad, all AJAX calls fail. Checking the server log reveals that they are using OPTIONS instead of GET/POST - so far that sounds like questions answered before, BUT:
a) this ONLY happens with the iPad Mobile Safari, NOT with Safari on the desktop or any other browser on the desktop
b) I have tripple-checked that I am using the same domain, no subdomain, no http/https, etc.
I have no idea what's going on here, so if anyone can help?

A: I had the same problem with a project in JQuery/.NET WCF where Firefox used OPTIONS verb to know what verbs are allowed (get, post, delete, put).
So i had this to my global.asax.cs file in the method "Application_BeginRequest", which is inherited by all REST Services. So when a REST service is called, it pass through that method first :
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

if (HttpContext.Current.Request.HttpMethod == "OPTIONS") {
    HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, x-requested-with");
    HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
    HttpContext.Current.Response.End();
}

When the verb "OPTIONS" is used, the global page returns options allowed. Then the browser send the POST/DELETE/GET/PUT request.
I guess you have to do something like that. What techno do you use for your website ?
BTW, if you have a better method to get through that prob, i'ld be glad to use it too :)


text:
Q: Add multiple list items to combobox How do I get all the testName present in the ListForTesting into the combobox? I have tried combobox_testType.ItemsSource = ListForTesting.testName but it doesn't work.
public class ManoeuvresID
{
    public string manName { get; set; }
    public int manID { get; set; }
}

public class TestID
{
    public string testName { get; set; }
    public int ID { get; set; }
    public IList<ManoeuvresID> manoeuvres { get; set; }
}

    HardCodedDatabase.TestID TestObjet = new HardCodedDatabase.TestID();
    TestObjet.manoeuvres = new List<HardCodedDatabase.ManoeuvresID>();
    HardCodedDatabase.ManoeuvresID man = new HardCodedDatabase.ManoeuvresID();
    man.manName="man1";
    man.manID = 2;
    TestObjet.manoeuvres.Add(man);
    List<HardCodedDatabase.TestID> ListForTesting = new List<HardCodedDatabase.TestID>();
    TestObjet.testName = "Steady State";
    ListForTesting.Add(TestObjet);
    TestObjet = new HardCodedDatabase.TestID();
    TestObjet.testName = "test2";
    ListForTesting.Add(TestObjet);
    combobox_testType.ItemsSource = ListForTesting;

A: All you need to is add you object items using Items.Add or Items.AddRange
Example below
        foreach (var item in ListForTesting)
            comBox.Items.Add(item);

Add range
 comBox.Items.AddRange(ListForTesting);

Then you set, which properties within you class object, will be used to display and is you key
        comBox.DisplayMember = "testName";
        comBox.ValueMember = "TestId";

A: have you tried linq
combobox_testType.ItemsSource = ListForTesting.Select(t=>t.testName);

another option would be to use the DisplayMemberPath
combobox_testType.ItemsSource = ListForTesting;
combobox_testType.DisplayMemberPath= "testName";


text:
Q: FileMaker - Total SubSummary Values I have a table with records each representing an appointment. I have the name of the contactthe appointment is with, and the date. In another table I have a field that contains how many appointments each contact is supposed to have during the day. There are 12 entries for each contact, because some are expected to have different numbers during different months.
I am able to call up the data for the appropriate contactfor the appropriate month. It looks great in the graph when I count up the number of entries for Contact A and put next to it the expected number of entries from the related table.
The problem I'm running into now is that I need to add up all of the expected appointments between all of the entities. So:
::ContactName::  ::appointments::       ::expected::
Contact A              12                   10
Contact B              33                   34
Contact C              18                   27

Getting the roll up for the actual appointments is easy, a simple COUNT summary field in a subsubsummary section. But what of the expected?  Because ContactA had 12 appointments that means that there will be 12 records for them, so putting a summary field for the expected column is would return 120 for all Contact A's. Instead, given the dataset above, I need the calculation to return 71. Does this issue make sense? Any help would be greatly appreciated.

A: If I am following this correctly, you need to divide the amount of expected appointments between the entries of the group, then total the result. So something like:
Sum ( Entities::Expected ) / GetSummary ( sCount ; EntityID )

(this would be easier if we knew the names of your tables and fields).

P.S. The term "entity" has a specific meaning in the context of a relational database. Consider using another term (e.g. "contacts").

Added:
Using your example data, you should see the following results in the above calculation field:

*

*in the 1st group of 12 records: 10 / 12 = .8333333333333333

*in the 2nd group of 33 records: 34 / 33 = 1.0303030303030303

*in the 3rd group of 18 records: 27 / 18 = 1.5

When you sum all this up (using a summary field defined as Total of this calculation field), you should get 71 (or a number very near 71, due to rounding errors).
Note: in the above calculation, sCount is a summary field defined in the Appointments table as Count of [ any field that cannot be empty ], and EntityID is the field by which your records are sorted and grouped (and it must be a local field).