text:
Q: Binding an specific context to an event handler I am just learning JavaScript and reading from that Ninja Secrets book and this is how he has done it to bind a click event to a button.  So as I am just a beginner and learning I wanted to do is it the best and final way of doing this ( adding click handler to a button ) or he has just used this as an example to demonstrate closures and this is NOT how in real world it is done.
  <body>
    <button id="test">Click Me!</button>

    <script>
      function bind(context,name){                                 //#1
        return function(){                                         //#1
          return context[name].apply(context,arguments);           //#1
        };                                                         //#1
      }                                                            //#1

      var button = {
        clicked: false,
        click: function(){
          this.clicked = true;
          assert(button.clicked,"The button has been clicked");
          console.log(this);
        }
      };

      var elem = document.getElementById("test");
      elem.addEventListener("click",bind(button,"click"),false);     //#2

    </script>

  </body>

A: He's mostly explaining how this works for educational purposes. In modern ECMAScript 5 there's a native Function.bind (docs here) so you can do:
elem.addEventListener("click", button.click.bind(button), false);


text:
Q: I'm getting an error when I turn on string Unicode encoding So, I'm making a program that reads from the Spanish dictionary. It grabs a random word. I need to turn on Unicode for a string because there will be characters like "é" and that, obviously requires encoding the string differently. When I turn on Unicode for the string[] it gives me this error message:
    System.Windows.Markup.XamlParseException was unhandled
  Message='The invocation of the constructor on type 'WordADay.MainWindow' that matches the specified binding constraints threw an exception.' Line number '4' and line position '9'.
  Source=PresentationFramework
  LineNumber=4
  LinePosition=9
  StackTrace:
       at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
       at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
       at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
       at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
       at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
       at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
       at System.Windows.Application.DoStartup()
       at System.Windows.Application.<.ctor>b__1(Object unused)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.DispatcherOperation.InvokeImpl()
       at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
       at System.Threading.ExecutionContext.runTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.ProcessQueue()
       at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at WordADay.App.Main() in C:\Documents and Settings\admin\My Documents\WordADay\WordADay\obj\x86\Debug\App.g.cs:line 0
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.IndexOutOfRangeException
       Message=Index was outside the bounds of the array.
       Source=WordADay
       StackTrace:
            at WordADay.MainWindow.newWord() in C:\Documents and Settings\admin\My Documents\WordADay\WordADay\MainWindow.xaml.cs:line 132
            at WordADay.MainWindow..ctor() in C:\Documents and Settings\admin\My Documents\WordADay\WordADay\MainWindow.xaml.cs:line 33
       InnerException:

Which, by the way, is completely wacky for me and I can't understand it. Just asking, what does this mean when coming from this code?:
        #region Setup
        Random word = new Random();
        string[] lines = File.ReadAllLines(dictionarypath, Encoding.Unicode);
        int randomword = word.Next(1, lines.Count());

        string[] excludedlines;
        if (!File.Exists(path))
        {
            File.Create(path);
        }
        excludedlines = File.ReadAllLines(path);
        string chosenWord = lines[randomword];
        #endregion

        #region Logic
        if (excludedlines.Count() == 58110)
        {
            File.WriteAllText(path, "");
        }
        if (excludedlines.Contains(chosenWord))
        {
            while (excludedlines.Contains(chosenWord))
            {
                randomword = word.Next(58110);
                chosenWord = lines[randomword];
            }

            File.AppendAllText(path, chosenWord + Environment.NewLine);
            excludedlines = File.ReadAllLines(path);
            label1.Content = chosenWord;

        }
        else
        {
            File.AppendAllText(path, chosenWord + Environment.NewLine);
            excludedlines = File.ReadAllLines(path);
            label1.Content = chosenWord;
        }
        #endregion

A: The following two lines could easily throw an index out of range exception:
        randomword = word.Next(58110);
        chosenWord = lines[randomword];

Surely the following would make more sense:
        randomword = word.Next(lines.Length);
        chosenWord = lines[randomword];

Also, the following line:
        int randomword = word.Next(1, lines.Count());

should probably be
        int randomword = word.Next(lines.Length);

In your version, the word at lines[0] will never be chosen randomly, which looks wrong.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Should I buy..." or "Should I purchase..."

*

*Should I buy/purchase web hosting?

*Should I buy/purchase Adobe Photoshop?

*Should I buy/purchase this car?

*Should I buy/purchase this land?

When should I use buy and purchase? Why?

A: In meaning, they're exactly the same. You can interchange fairly freely. Looking at the definitions on The Free Dictionary, each is used to define the other.
In practice, "purchase" is of a higher register than "buy", making it more formal. You might find "purchase" in a legal document, or regarding government expenditure, whereas "buy" is perhaps more for daily use.
The only other discernible difference I can think of is that "purchase" has the noun "purchase/s" whereas "buy" doesn't.
In your examples, simply consider the formality required for the context.


text:
Q: Airflow parameter passing I have a simple job that I'd like to move under an Airflow process, if possible. As it stands, I have a string of bash scripts that access a server and download the latest version of a file and then perform a variety of downstream manipulations to that file.
exec ./somescript.sh somefileurl

What I'd like to know is: how can I pass in the URL to this file every time I need to run this process?
It seems that if I try to run the bash script as a bash command like so:
download = BashOperator(
task_id='download_release',
bash_command='somescript.sh',
# params={'URL': 'somefileurl'},
dag=dag)

I have no way of passing in the one parameter that the bash script requires. Otherwise, if I try to send the bash script in as a bash command like so:
download = BashOperator(
task_id='download_release',
bash_command='./somescript.sh {{ URL }}',
params={'URL': 'somefileurl'},
dag=dag)

I receive an execution error as the program tries to execute the script in the context of a temporary directory. This breaks the script as it requires access to some credentials files that sit in the same directory and I'd like to keep the relative file locations intact...
Thoughts?
Update: What worked for me
download = BashOperator(
task_id='download_release',
bash_command='cd {{ params.dir }} && ./somescript.sh {{ params.url }}',
params={'url': 'somefileurl',
        'dir': 'somedir'},
dag=dag)

I did not implement any parameter passing yet, though.

A: Here is an example of passing a parameter to your BashOperator:
templated_command = """
cd /working_directory
somescript.sh {{ dag_run.conf['URL'] }}
"""
download = BashOperator(
   task_id='download_release',
   bash_command=templated_command,
   dag=dag)

For a discussion about this see passing parameters to externally trigged dag. Airflow has two example DAG's that demonstrate this: example_trigger_controller_dag and example_trigger_target_dag.  Also, see the Airflow api reference on macros.


text:
Q: Let $ABC$ be a triangle with $AB=AC=6$. If the circumradius of the triangle is $5$ then $BC$ equals:___ This is the question.

Let $ABC$ be a triangle with $AB=AC=6$. If the circumradius of the triangle is $5$ then $BC$ equals:___

My approach:
This is the diagram I drew (it's a bit messy, sorry for that).
$(1)$ Since O is the Circumcentre; $OA=OB=OC=5 \ cm$
As given in the question.
$(2)$ I wanted to find $\angle OCD$ in order to find the remaining angles and get the length of $BC$ in form of a trigonometric ratio.
$(3)$ So, I used Heron's formula to calculate the area of $\triangle AOC$, which I got as $12 \ cm^2$
$(4)$ I then calculated the height $OD$ which I got as $4 \ cm$
$(5)$ By trigonometric relations, $\angle OCD$ comes out to be $53$ degrees.
Since, $AO=OC$, $\angle OAC$ must be $53$ degrees too.
And even $\angle BAO= 53$ degrees.
Therefore, $\angle BAC = 106$ degrees.
Since, $\Delta ABC$ is also Isosceles, we have:
$\angle ABC = \angle ACB = x $ (let)
$\therefore 2x+106 = 180 \implies x = 37$
But we have $\angle ABO = \angle OBC = 53$ degrees!
And it is impossible for $\angle ABO$ to be greater than $\angle ABC$
Could someone tell where I am making a mistake? Thanks

A: As you found $\angle BAC$ is $106^0$ and as it is an obtuse angled triangle, the circumcenter of $\triangle ABC$ is outside the triangle as mentioned in the comments. If $E$ is the midpoint of $BC$, circumcenter is on line going through $AE$, outside of triangle and below $BC$. So yes $\angle BCA = 37^0$ and $\angle OCA = 53^0$ are both possible.
But you can make your working much simpler by applying extended sine rule.
$\dfrac{AC}{\sin \angle B} = 2 R \implies \sin \angle B = \dfrac{6}{10} = \dfrac{3}{5}$
So, $\cos \angle B = \dfrac{4}{5}$
If $E$ is the midpoint of $BC$, $\triangle AEB$ is right angled triangle.
So, $BE = \dfrac{BC}{2} = AB \cos \angle B = \dfrac{24}{5}$
$BC = \dfrac{48}{5}$

A: Usual notational conventions for the sides of a triangle are used
Suppose $\delta$ denotes the area of $ABC$ and $R$ the circumradius
Also let's define $\angle BAC=\xi$
Then we've $$\frac{abc}{4R}=\frac{bc \sin(\xi)}{2}=\delta$$
From this we get using the Law of sines
$$\frac{a}{\sin(\xi)}=10=\frac{b}{\sin\left(\frac{\pi}{2}-\frac{\xi}{2} \right)}=\frac{b}{\cos \left(\frac{\xi}{2} \right)}$$
Thus we get $$\cos(\xi)=\left(2\cos\left(\frac{\xi}{2} \right)\right)^{2}-1=\frac{-7}{25}$$
Using the law of cosines we get
$$\cos(\xi)=\frac{b^2 +c^2-a^2}{2bc}$$
Solving this we get $a=\frac{48}{5}$


text:
Q: input type hidden attribute value missing when I inspect with Fiddler For the same request, the attrib value of tag input type=hidden is not displayed on the content (raw text) of the response using Fiddler and VStudio debugger. But when I inspect the code with Chrome it is displayed. Why does this happen?  See these snapshots:
Element inspect from google

Inspector response content from Fiddler4

I'm a beginner in HTTP and HTML.


text:
Q: Mac OS X automount not mounting fstab entries correctly I'm trying to automount a Windows SMB share on Mac OS X.
The first thing I tried was to put entries only in /etc/fstab:
$ dgrant$ cat /etc/fstab
//darrengrant@d-grant/share    /pc/share    smbfs    nodev,nosuid

This works fine using mount -a.
But I want my drives to be mounted whenever the machine is turned on.  But the drives aren't getting mounted when I restart my computer.  I check the Console and I see the following:
3/24/11 2:09:32 PM  com.apple.launchd[1]    *** launchd[1] has started up. ***
3/24/11 2:09:48 PM  com.apple.autofsd[50]   automount: Mount for //darrengrant@d-grant/share has no path for the directory to mount

I can reproduce this error message on the commandline by a simple use of sudo automount.  I think launchd calls automountd, that mounts everything in /etc/fstab.  The file /etc/auto_master contains a reference or two to fstab, so that seems reasonable.
I found the 'no path for the directory to mount' error in the actual source for automountd, and it seems the cause is a missing colon in the fstab line between the machine name and mount directory name. I made the error disappear by adding the colon to fstab like this:
//darrengrant@mypc:/share   /pc/share   smbfs    nodev,nosuid

But after a reboot, automount doesn't work with an entirely different set of errors:
$ sudo automount -v
automount: /net updated
automount: /home updated
    [ pauses here for a couple of seconds ]
automount: /pc/share updated
automount: no unmounts              # looks good so far  ...

$ mount
....
map -static on /pc/share (autofs, automounted, nobrowse) # OK, a little different..

$ ls /pc/share
ls: share: Host is down     # fail.

This doesn't really make much sense.. why does fstab not need the colon but automount does? And what is the 'Host is down' part all about? Some confusion between network and local drives perhaps?

A: There's a bit of confusion here.  mount reads /etc/fstab, and is used for things that should be mounted when the system boots.
automount reads /etc/auto_master, and is used to mount things only when the directory is used, and not before.  It's typically used for things like NFS home directories, which should only be mounted when the user actually needs them.  You can do that, too, but /etc/fstab is not where to do it.
If you just want to have your smb share mounted when the machine starts up, all you need is what you already have in /etc/fstab, with a couple of gotchas that you should be aware of.

*

*use the soft option - otherwise,
if you're not networked, the mount
will hang and prevent your system
from booting correctly

*it looks like you're connecting
without credentials.  If you
actually do need credentials in the
fstab entry, be careful, since
/etc/fstab is usually readable by
anyone on the system, so your
username and password used for the
smb system will be exposed.  There
are ways around that by editing
~/Library/Preferences/nsmb.conf

A: malcolmpdx.  What you say is correct in theory and, for all previous versions of OS-X, true in practice.  Unfortunately Catalina seems to have stopped processing fstab.  I would love an explanation as to why or, better, a solution.
I've been managing unix boxes of all different flavors for 30+ years and this change is disappointing to say the least.  In my case I'm trying to mount a bunch of NFS shares at boot since I need them to be accessed by background tasks - a very common configuration for anyone coming from the Sun world.
Any guidance will be gratefully received.


text:
Q: internet explorer not working properly with fancy box I'm not a programmer, but I've put together a site that uses fancy box and all is good in chrome and firefox, but ie8 & ie9 are a disaster. the site is http://www.pinnaclebillboards.com.
I've searched to correct the problem but i'm not even sure how to describe it. Can anyone point me in the right direction please?

A: You are missing the DOCTYPE so IE is working in quirks mode. You need to set the proper DOCTYPE to make fancybox to work in IE. Check this link or this other for more on this topic.
Also be sure that you close your tags properly to avoid further issues.

A: I'm going to take a stab in the dark here and suggest it has something to do with loading a flash object into the fancybox. Shouldn't be a problem, but ya never know with IE.

A: From looking at the source I have a few recommendations:

*

*Add a doctype, e.g.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

*Change encoding to UTF-8


text:
Q: Putting an individuals distinct diagnosis into one horizontal row AND excluding a specific diagnosis I am working from the same query as explained in this question: Diagnosis in One Horizontal Row. The diagnosis data is now horizontal and I want to exclude those with active dementia (diagnosis status is indicated for each diagnosis). The max # of diagnoses per person is 50 so I have to search each of the 50 ICD9 Code fields for each of the 18 different ICD9 codes (indicating dementia). I have declared each of the 18 codes as @ICD9Code49 - @ICD9Code66, but cannot figure out how to exclude these from my data set. I have tried the following (ProblemStatus is the diagnosis status):
SELECT * FROM Diagnosis
WHERE
(
([ProblemStatus_1] = @ProblemStatus AND (ICD9Code_1 <> @ICD9Code49 OR ICD9Code_1 <> @ICD9Code50 OR ICD9Code_1 <> @ICD9Code51 OR ICD9Code_1 <> @ICD9Code52 OR ICD9Code_1 <> @ICD9Code53 OR ICD9Code_1 <> @ICD9Code54 OR ICD9Code_1 <> @ICD9Code55 OR ICD9Code_1 <> @ICD9Code56 OR ICD9Code_1 <> @ICD9Code57 OR ICD9Code_1 <> @ICD9Code58 OR ICD9Code_1 <> @ICD9Code59 OR ICD9Code_1 <> @ICD9Code60 OR ICD9Code_1 <> @ICD9Code61 OR ICD9Code_1 <> @ICD9Code62 OR ICD9Code_1 <> @ICD9Code63 OR ICD9Code_1 <> @ICD9Code64 OR ICD9Code_1 <> @ICD9Code65 OR ICD9Code_1 <> @ICD9Code66))
AND ([ProblemStatus_2] = @ProblemStatus AND (ICD9Code_2 <> @ICD9Code49 OR ICD9Code_2 <> @ICD9Code50 OR ICD9Code_2 <> @ICD9Code51 OR ICD9Code_2 <> @ICD9Code52 OR ICD9Code_2 <> @ICD9Code53 OR ICD9Code_2 <> @ICD9Code54 OR ICD9Code_2 <> @ICD9Code55 OR ICD9Code_2 <> @ICD9Code56 OR ICD9Code_2 <> @ICD9Code57 OR ICD9Code_2 <> @ICD9Code58 OR ICD9Code_2 <> @ICD9Code59 OR ICD9Code_2 <> @ICD9Code60 OR ICD9Code_2 <> @ICD9Code61 OR ICD9Code_2 <> @ICD9Code62 OR ICD9Code_2 <> @ICD9Code63 OR ICD9Code_2 <> @ICD9Code64 OR ICD9Code_2 <> @ICD9Code65 OR ICD9Code_2 <> @ICD9Code66))
AND ([ProblemStatus_3] = @ProblemStatus AND (ICD9Code_3 <> @ICD9Code49 OR ICD9Code_3 <> @ICD9Code50 OR ICD9Code_3 <> @ICD9Code51 OR ICD9Code_3 <> @ICD9Code52 OR ICD9Code_3 <> @ICD9Code53 OR ICD9Code_3 <> @ICD9Code54 OR ICD9Code_3 <> @ICD9Code55 OR ICD9Code_3 <> @ICD9Code56 OR ICD9Code_3 <> @ICD9Code57 OR ICD9Code_3 <> @ICD9Code58 OR ICD9Code_3 <> @ICD9Code59 OR ICD9Code_3 <> @ICD9Code60 OR ICD9Code_3 <> @ICD9Code61 OR ICD9Code_3 <> @ICD9Code62 OR ICD9Code_3 <> @ICD9Code63 OR ICD9Code_3 <> @ICD9Code64 OR ICD9Code_3 <> @ICD9Code65 OR ICD9Code_3 <> @ICD9Code66))
)

I've tried various combinations of AND's and OR's but it doesn't seem to be working.

A: This is a great time for NOT IN:
with dementiaCodes as (
    select @ICD9Code49 as code
    union all select @ICD9Code50
    union all select @ICD9Code51
    ...
)
SELECT * FROM Diagnosis
WHERE
NOT ((ProblemStatus_1 = @ProblemStatus AND ICD9Code_1 IN (select code from dementiaCodes))
    OR (ProblemStatus_2 = @ProblemStatus AND ICD9Code_2 IN (select code from dementiaCodes))
    OR (ProblemStatus_3 = @ProblemStatus AND ICD9Code_3 IN (select code from dementiaCodes)))


text:
Q: AngularJs post request getting error I am trying to do a POST request to a login api through angular js .
<form method="post" ng-submit="doLogin()">

          Username
          <input type="text" ng-model="loginData.user_mail">

          Password
          <input type="password" ng-model="loginData.password">

          <button class="button button-block button-positive" type="submit" >{{loginTxt}}</button>

      </form>

Controller.js
$scope.doLogin=function(){
     $http({
          method  : 'POST',
          url     : 'http://examplemns.com/customer/api/v1/login/login',
          data    : $scope.loginData, //forms user object
          timeout:20000
         })
         .success(function(response){

              alert(JSON.stringify(response));
           })
           .error(function(err){
                console.log(JSON.stringify(err));
                alert("Network error");

             });
         }

But i will get invalid username response even if the username and password is correct.
I checked the api through postman plugin its working fine,but when comes with angular i will get invalid.
Here is the sample input
user_mail:avm@gmail.com
password:123456

When try this input with postman plugin i will get the correct response
{
  "status": 1,
  "message": "Done",
  "data": {
    "name": "A.V.M TOURIST HOME",
    "username": "avm@gmail.com",
    "id": "37",
    "key": "cos4ok88woo0kcw40cog0s4gg4skogscso8848ok"
  }
}

but when trying through the angularjs post i with the same input i will get this response
{"status":0,"message":"Invalid username"}

Please help me:(
UPDATE
I need to transform my  data to application/x-www-form-urlencoded rather than json (from comments) for that i am used this way.
var data= {user_mail:$scope.loginData.user_mail,password:$scope.loginData.password};
$http({
              method  : 'POST',
              url     : 'http://examplemns.com/customer/api/v1/login/login',
              data    : data,
              timeout:20000
             })
             .success(function(response){

                  alert(JSON.stringify(response));
               })
               .error(function(err){
                    console.log(JSON.stringify(err));
                    alert("Network error");

                 });

But again i will get the same
Screenshot of request and response from the postman

A: Try this
    $scope.loginData = {};
    $scope.doLogin=function(){

         $http({
              method  : 'POST',
              url     : 'http://examplemns.com/customer/api/v1/login/login',
              data    : $scope.loginData, //forms user object ,
              headers: {'Content-Type': 'application/x-www-form-urlencoded'}

             })
             .success(function(response){
                  console.log(response);
             })
             .error(function(err){
                    console.log(err);
              });
            }

OR
$scope.loginData = {};
var data = $scope.loginData;
$http.post('/examplemns.com/customer/api/v1/login/login', data).then(successCallback, errorCallback);

ALSO TRY THIS
  <input type="text" ng-model="user_mail">
  <input type="password" ng-model="password">

  var data = {};
  data.user_mail = $scope.user_mail;
  data.password = $scope.password;

  $http.post('/examplemns.com/customer/api/v1/login/login',   data).then(successCallback, errorCallback);

A: Try changing the following line:
data    : $scope.loginData, //forms user object

to:
data    : JSON.stringify($scope.loginData), //forms user object


text:
Q: jQuery Mobile Button Size? I'm trying to make all these buttons the same size, two are bigger because of the text.
Is this possible using the CSS?

A: If this is a jQuery Mobile question then button size can be changed by changing this class:
.ui-btn {
    width: 200px !important;
}

!important is necessary with jQuery Mobile because we need to override default values.
Working example: http://jsfiddle.net/Gajotres/NJ8q4/
Now because you are using a tag buttons (I so it from your previous question) you will need to give it a custom id or class. If you change just .ui-btn you will change every button inside your app. So in the end this CSS will work with this HTML:
HTML :
Level 5
Level 4
Level 3
Level 2
Level 1
Stretch
Warm up

CSS :
.custom-btn {
    width: 200px !important;
}

Second working example: http://jsfiddle.net/Gajotres/NJ8q4/1/


text:
Q: Assigning raster values to a label in R I have a raster, the pixel values inside the raster is equal to 1; outside is 0.
I would like to write an r function that assign these 1 values = "cloud" in other way it will return cloud. otherwise clear.
I would like to keep the result as DF. like in the photo; (the photo is the result of different code so I cannot apply that to this situation)
How can I do this?

A: I have solved it in case someone needed;
recode_poly <- function(x){
  poly_recode = c()
  for (i in (1:1000)){
    if (x[i] == 1) {
      poly_label = "cloud"
    } else {
      poly_label = "clear"
    }
    poly_recode <- c(poly_recode, poly_label)
  }
  return (poly_recode)
}

then you can convert poly_recode to a dataframe
but I am pretty open new solutions


text:
Q: MVC C# Adding items to to a List<> within foreach I'm working on something and while I usually have no problems with c# i've had a brain meltdown and got a bit stuck...
Within my MVC app I have a controller which manages some markers for Google Maps (as follows)
   public ActionResult GetMarkers()
    {
        MarkerList markers = getMarkersForMap();

        return Json(markers, JsonRequestBehavior.AllowGet);

    }

    public MarkerList getMarkersForMap()
    {
        MarkerList ml = new MarkerList();

        foreach (var shop in dirRepo.getAllShops())
        {
            Marker marker = new Marker
            {
                html = shop.ShopName,
                lat = shop.Lat,
                lng = shop.Lng,
                label = shop.DirectoryID.ToString()
            };

            ml.markers.Add(marker); // <<<< Object ref not set to an instance of an object

        }
        return m;
    }

I also have a Markers controller as follows:
public class MarkerList
{
    public List<Marker> markers { get; set; }
}

public class Marker
{
    public string lat { get; set; }
    public string lng { get; set; }
    public string html { get; set; }
    public string label { get; set; }
}

Data is being populated in the foreach no problem, but I want to add the multiple markers into the list so I can pass them back to the calling function and carry on with displaying the results in my view page. I can add single items no problem by doing this
return new MarkerList {markers = new List<Marker> {marker}};

but how about multiple items??

A: You need to have initialized list in your MarkerList to use it. You can initialize it in the default MarkerList constructor.
public class MarkerList
{
    public List<Marker> markers { get; set; }

    public MarkerList()
    {
        markers = new List<Marker>();
    }
}

Then, you are sure the inner list is always initialized.
BTW: Why do you want to encapsulate your list in the object that contains this list only? There's no benefit of the MarkerList class now. Unless this is only shortened for question's needs, it'll be better to remove this class and use List<Marker> directly.

A: ml.markers is null because You are using auto properties (without backing store). You need to initialize it in ctor for example.
But one thing looks weird. First why is markers public and not started with capital letter. And more important. What is MarkersList class for when You access inner List? Right now it doesn't make much sense. Either make the inner markerslist private/protected and add AddMarker method to MarkersList. Or just use List in controller and return it.


text:
Q: how to use ajax to change data in blade template hey guys i'm trying to make changes in my blade template using ajax , when i press the button it changes the value of data in database and i want to display this data at once on my blade template .
that's my java script code :
(function($){
    $('.wishlistForm').on('submit', function(){
        var form = $(this);
        $.ajax({
            url: form.attr('action'),
            data: form.serialize(),
            method: 'post',
            dataType: 'json',
            success: function(response){
                var wishlistButton = form.find("button[type='submit']");
                var x = parseInt($('.wish-btn-count').text());
                if(response.actiondone == 'added') {
                    $('.wish-btn-count').text(x++);
                    console.log(x);
                    wishlistButton.text(response.message);
                } else if(response.actiondone == 'removed') {
                    $('.wish-btn-count').text(x--);
                    console.log(x);
                    wishlistButton.text(response.message);
                }
            }
        });
        return false;
    });
})(jQuery);

and here is the part i want to change in my template :
<div class="wish-btn-count" id="wishlist">
                        {{$wishlistcount}}
                    </div>

so how can i do it ? and for record it returns the value right in the console but don't show it in my view

A: Prevent the default submit event, so you can trigger the ajax
 $('.wishlistForm').on('submit', function(e){
e.preventDefault();

A: This may be the solution.
If you are receiving json object response from the ajax call,first you have to parse that object and then use it.

Try this,

(function($){
$('.wishlistForm').on('submit', function(){
    var form = $(this);
    $.ajax({
        url: form.attr('action'),
        data: form.serialize(),
        method: 'post',
        dataType: 'json',
        success: function(response){
           /*Add this in your code*/
            var response = JSON.parse(response.trim());
            var wishlistButton = form.find("button[type='submit']");
            var x = parseInt($('.wish-btn-count').text());
            if(response.actiondone == 'added') {
                $('.wish-btn-count').text(x++);
                console.log(x);
                wishlistButton.text(response.message);
            } else if(response.actiondone == 'removed') {
                $('.wish-btn-count').text(x--);
                console.log(x);
                wishlistButton.text(response.message);
            }
        }
    });
    return false;
});

})(jQuery);


text:
Q: Echo cancellation in Ubuntu 20 I have added following lines to my Pulse's settings in order to have echo cancellation:
#Active Noise Removal
load-module module-echo-cancel

all works but when I turn on the machine microphone with echo cancellation hides. When I delete the two lines, restart the machine and add once more time all works fine..
How to make it working at bootstrap as expected, any ideas? The same situation is with the fonts in top bar, when I increase all works but after restart I have default smaller fonts. The system was upgraded from 18.04 LTS

A: Ubuntu 20 sucks heavily on this (as many other things). The only working solution I found was to

*

*Create a startup script with line:

sleep 60s && pactl load-module module-echo-cancel

Script could be run by Startup Application Preferences.
Explanation:

*

*sleep 60s - we need to wait until pulseaudio is ready, it's shorter time but I didn't care, 60 seconds is ok for me

*Put some configuration in /etc/pulse/default.pa:

load-module module-echo-cancel source_name=noechosource sink_name=noechosink
set-default-source noechosource
set-default-sink noechosink

*Set in /etc/pulse/client.conf
default-source = noechosource

This is all.

This is hideous solution, but I couldn't find anything better.
Other solutions found on the web didn't work, like:

*

*PulseAudio doesn't load after adding noise cancellation to config

*https://www.informaticar.net/enable-noise-cancellation-in-ubuntu/

*https://medium.com/@rahul.y.dudhane/how-to-do-noise-and-echo-cancellation-in-ubuntu-7a5607c7e887


text:
Q: Ridge regression - what is k=0? I'm getting to know ridge regression and what to check my understanding quickly.
I understand that k is the shrinkage parameter. If I'm reading off coefficients where k=0, is that equivalent to an OLS linear regression?
Or have I got totally the wrong end of the stick?
Simon.

A: Assuming k is the coefficient in front of the regularization term, then yes having k=0 is the same as OLS linear regression.


text:
Q: Change connection definitions for clear_border in Python I've been using clear_border from scikit-image and label from scipy to identify areas of adjacent pixels in a 2d array of 1s and 0s. I use clear_border first, which removes all groups of 1 that are touching the edge, and then label the groups that are left with label.
My question is, with label a custom structure parameter can be passed. This determines what is defined to be connected, and in my case it basically allows me to decide whether diagonals are connected. To be concrete, in the array
[[0,0,0,0,0]
 [0,1,0,0,0]
 [0,0,1,1,0]
 [0,0,0,0,0]
 [0,0,0,0,0]

label would find 2 independent objects if [[0,1,0],[1,1,1],[0,1,0]] is used for structure, but only one if [[1,1,1],[1,1,1],[1,1,1]] is used. The problem is, clear_border has no such option and works the same as label when [[1,1,1],[1,1,1],[1,1,1]] is used (in other words, clear_border always defines diagonal pixels to be connected).
So my problem is just that I need to use a function exactly like clear_border, but one that does not define diagonal pixels to be connected. The analogue of passing structure=[[0,1,0],[1,1,1],[0,1,0]] to label.
Update
Based on Juan's answer, here is my general function that I was looking for.
from skimage.segmentation import clear_border
from scipy.ndimage.measurements import label

def clear_border_adjacent(matrix):
    """
        clear_border from skimage.segmentation considers diagonal pixels to be connected,
        so e.g. all structures will be removed in all of these:
                [[0,0,0,0],                [[0,0,0,0],                [[0,0,0,0],
                 [0,1,1,0],                 [0,1,1,0],                 [0,1,0,0],
                 [0,0,0,1],                 [0,0,1,1],                 [1,0,0,0],
                 [0,0,0,0]]                 [0,0,0,0]]                 [0,0,0,0]]
        This function clears the border but only considers adjacent pixels connected,
        so ex 1 and 3 would still have one structure in output but ex 2 would have 0.
    """
    border_cleared = clear_border(label(matrix)[0])
    border_cleared[border_cleared > 0] = 1
    return border_cleared

A: I think you can use label first, then clear border, to achieve the same result? If there is a reason why this fails, please make a feature request on https://github.com/scikit-image/scikit-image/issues


text:
Q: How to create executable application to using opencv? I am greener in Python .I have design a small application for my personal project . But the problem is that when i use it on python then it's ok after create a executable(exe) application by pyinstaller then it's show "Fatal error" and "cam returned  -1" my python project name is cam.py.
enter image description here
 I don't know what's the problem of this application .
and my code is below:
 import cv2
 import numpy
 face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
 cam = cv2.VideoCapture(0)

 while True :
     ret,frame = cam.read()
     gray = cv2.cvtColor (frame, cv2.COLOR_BGR2BGRA)
     faces = face_cascade.detectMultiScale(gray, 1.3,5)
     for (x,y,w,h) in faces:
         cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
         cv2.imshow("LubnaX(NSL2)",frame)

     k = cv2.waitKey(10)
     if k==27:
        break

cam.release()
cv2.destroyAllWindows()


text:
Q: Search for a substring in an another string using hashing I wrote code to find a substring in another string using hashing, but it's giving me a wrong result.
A description of how the code works:

*

*Store the first n powers of p=31 in array pows.

*Store hashes for each substring s[0..i] in the array h.

*Calculate the hash for each substring of length 9 using the h array and store it in a set.

*Hash the string t and store its hash.

*Compare the hash of t and hashes in the set.

The hash h[n2-1] should exist in the set but it does not. Could you help me find the bug in the code?
Note: When I use the modular inverse instead of multiplying by pows[i-8] the code runs well.

#include <bits/stdc++.h>

#define m 1000000007
#define N (int)2e6 + 3

using namespace std;

long long pows[N], h[N], h2[N];

set<int> ss;

int main() {

    string s = "www.cplusplus.com/forum";

    // powers array
    pows[0] = 1;
    int n = s.length(), p = 31;
    for (int i = 1; i < n; i++) {
        pows[i] = pows[i - 1] * p;
        pows[i] %= m;
    }

    // hash from 0 to i array
    h[0] = s[0] - 'a' + 1;
    for (int i = 1; i < n; i++) {
        h[i] = h[i - 1] + (s[i] - 'a' + 1) * pows[i];
        h[i] %= m;
    }

    // storing each hash with 9 characters in a set
    ss.insert(h[8]);
    for (int i = 9; i < n; i++) {
        int tp = h[i] - h[i - 9] * pows[i - 8];
        tp %= m;
        tp += m;
        tp %= m;
        ss.insert(tp);
    }

    // print hashes with 9 characters
    set<int>::iterator itr = ss.begin();
    while (itr != ss.end()) {
        cout << *(itr++) << " ";
    }
    cout << endl;

    // t is the string that i want to check if it is exist in s
    string t = "cplusplus";
    int n2 = t.length();
    h2[0] = t[0] - 'a' + 1;
    for (int i = 1; i < n2; i++) {
        h2[i] = h2[i - 1] + (t[i] - 'a' + 1) * pows[i];
        h2[i] %= m;
    }
    // print t hash
    cout << h2[n2 - 1] << endl;

    return 0;
}

A: I can see two problems with your code:

*

*When you're computing hashes for substrings of length 9, you're storing the intermediate result (of type long long) in an int variable. This could cause integer overflow and the hash you computed would probably be incorrect.

*Given a string s = {s[0], s[1], ..., s[n-1]}, the way you're computing the hash is: h = ∑ s[i] * p^i. In this case, given the prefix hash stored in h, the hash for a substring s[l..r] (inclusive) should be (h[r] - h[l - 1]) / p^(r-l+1), instead of what you wrote. This is also why using modular inverse (which is required to perform division under modulo) is correct.

I think a more common way to compute hashes is the other way around, i.e. h = ∑ s[i] * p^(n-i-1). This allows you to compute the substring hash as h[r] - h[l - 1] * p^(r-l+1), which does not require computing modular inverses.


text:
Q: Python Currency Converter The following code is a simple currency converter.  Everything works but the last if statement, which causes the code to break.  Whenever I put a number less than .25 in an if statement, it breaks the code.  I would greatly appreciate any input to why this is.  Thank you very much.
def currency_converter(amount):
        hundred = 0
        fifty = 0
        ten = 0
        five = 0
        one = 0
        quarter = 0
        dime = 0
        while amount > 0:
                if amount >= 100:
                        hundred+=1
                        amount-=100
                if 100 > amount >= 50:
                        fifty+=1
                        amount-=50
                if 50 > amount >= 10:
                        ten+=1
                        amount-=10
                if 10 > amount >= 5:
                        five+=1
                        amount-=5
                if 5 > amount >= 1:
                        one+=1
                        amount-=1
                if 1 > amount >= float(.25):
                        quarter+=1
                        amount-=float(.25)
                if float(.25) > amount >= float(.1):
                        dime+=1
                        amount-=float(.1)
        print(hundred, "Hundred-dollar bill")
        print(fifty, "Fifty-dollar bill")
        print(ten, "Ten-dollar bill")
        print(five, "Five-dollar bill")
        print(one, "One-dollar bill")
        print(quarter, "Quarter")
        print(dime, "Dime")
currency_converter(5.6)

A: def currency_converter(amount):
  amount = int(100*amount)
  hundred = (amount//10000)
  amount -= hundred*10000
  fifty = (amount//5000)
  amount -= fifty*5000
  ten = (amount//1000)
  amount -= ten*1000
  five = (amount//500)
  amount -= five*500
  one = (amount//100)
  amount -= one*100
  quarter = (amount//25)
  amount -= quarter*25
  dime = (amount//5)
  amount -= dime*5
  penny = amount
  return (hundred, fifty, ten, five, one, quarter, dime,penny)


text:
Q: Include model SequelizeJS I get an error when I try to include a model on an "findAll" action using SequelizeJS...
    Executing (default): SELECT `projects`.*, `Medias`.`id` AS `Medias.id`, `Medias`.`title` AS `Medias.title`, `Medias`.`image` AS `Medias.image`, `Medias`.`createdAt` AS `Medias.createdAt`, `Medias`.`updatedAt` AS `Medias.updatedAt`, `Medias`.`projectId` AS `Medias.projectId` FROM `projects` LEFT OUTER JOIN `media` AS `Medias` ON `projects`.`id` = `Medias`.`projectId` ORDER BY id DESC;

    TypeError: Cannot call method 'hasOwnProperty' of null
        at Function.Dot.transform (/Users/anthonycluse/Sites/Sbaf/Back-End/node_modules/sequelize/node_modules/dottie/dottie.js:102:50)
        at /Users/anthonycluse/Sites/Sbaf/Back-End/node_modules/sequelize/lib/dialects/abstract/query.js:366:17
        at Array.forEach (native)
        at module.exports.groupJoinData (/Users/anthonycluse/Sites/Sbaf/Back-End/node_modules/sequelize/lib/dialects/abstract/query.js:365:10)
        at module.exports.handleSelectQuery (/Users/anthonycluse/Sites/Sbaf/Back-End/node_modules/sequelize/lib/dialects/abstract/query.js:233:17)
        at module.exports.AbstractQuery.formatResults (/Users/anthonycluse/Sites/Sbaf/Back-End/node_modules/sequelize/lib/dialects/abstract/query.js:70:34)
        at null.<anonymous> (/Users/anthonycluse/Sites/Sbaf/Back-End/node_modules/sequelize/lib/dialects/mysql/query.js:33:35)
        at Query.Sequence.end (/Users/anthonycluse/Sites/Sbaf/Back-End/node_modules/mysql/lib/protocol/sequences/Sequence.js:78:24)
        aMacBook-Pro-de-Anthony:Back-End anthonycluse$

My action :
dbContext.project.findAll({order: 'id DESC', include: [{model: dbContext.media, as: 'Medias'}]}).success(function(projects) {
        callback(projects);
});

My dbContext :
(function () {

    var modelsPath = __dirname + '/../app/models/';

    /**
    * Constructor.
    * Add your entities 'DbSet' instance here like user.
    */
    function DbContext() {
        this.db = require('./dbConnection');
        this.entities();
        this.modelBuilder();
    }

    /**
     * Attach your model to DbContext like user to perform database sync.
     *
     */
    DbContext.prototype.entities = function() {
        this.project = this.db.import(modelsPath + 'project');
        this.media = this.db.import(modelsPath + 'media');
    };

    /**
    * Manage Database entities associations here.
    */
    DbContext.prototype.modelBuilder = function () {
        this.project.hasMany(this.media, {as: 'Medias'});
        this.media.belongsTo(this.project);
    };

    module.exports = DbContext;
})();


text:
Q: Laravel & Dropzone.js file request In my controller when I try dd($request->file('file')); return null... Any solution please!
More Info, I upload only 1 image without Ajax request, using the submit button autoProcessQueue: false because I have others inputs that need validation. When I turn auto process to true just for testing the upload works fine but the the file request still null.
The view:
<form role="form" action="{{ route('user::products::store') }}" method="POST" enctype="multipart/form-data">

{!! csrf_field() !!}

has('thumbnail') ? 'has-error' : '' }}">

Click or drag image here

</form>

Dropzone.js Config

A: Try add a input field:
<input type="file" name="file" />


text:
Q: Run non stop background task using asp.net core in linux container I have a asp.net core API microservice from which i want to send notification using kafka to another microservice to send emails. Email microservice should always remain up without sleep in linux docker container (IIS doesn't work in linux container). What should be used to fulfill this criteria ?

A: You can use the Worker Service template
IIS has a default recycling pool system so your app will be shutdown after X time of inactivity.
You need to host you application on a Kestrel server.
In an ideal world you will need a message broker system to manage your events and messages.


text:
Q: Using spread to renew a reference to an existing object? I have an object which its keys are defined in an interface. The object contains objects :
class S1  { n: number; }
class S2  { n: number; }
class S3  { n: number; }

interface State {
    s1: S1;
    s2: S2;
    s3: S3;
}

var Store: State =
    {
        s1: new S1(),
        s2: new S2(),
        s3: new S3(),
    }

I'm modifying an object and keep it in the store again :
var s1 = new S1(); //for example
s1.n = 4;
Store.s1 = s1;

But now I want to renew the s1 reference.
I know I can do it via :
Store["s1"] = { ...Store["s1"] };

But I want to do it via a method which all it accepts is the keys of the Store :
function refreshStore<K extends keyof State>(k: K) {
    Store[k] = {
        ...Store[k] //<---error
    };
}

But I get an error here ^ :

Spread types may only be created from object types

Question:
How can I make the refreshStore method to like the intended refreshStore('s1') ?
Basically I want this refreshStore('s1') to do
  Store["s1"] = { ...Store["s1"] };

Online Demo

A: Due to current limitations, object spread won't work with this generic function. While this will work:
function refreshStore(k: keyof State) {
    Store[k] = {...Store[k]};
}

Object spread is syntactic sugar for Object.assign({}, ...). It can be used instead:
function refreshStore<K extends keyof State>(k: K) {
    Store[k] = Object.assign({}, Store[k]);
}


text:
Q: elasticsearch.yml : will the configuration file be written on the fly? I am building my own docker image for the elasticsearch application.
One question I have : will the configuration file elasticsearch.yml be modified by the application on the fly?
I hope that will never happen even if the node is running in cluster. But some other application (like redis), they modify the config file on the fly when cluster status changes. And if the configuration file changes on the fly, I have to export it as volumn since docker image can not retain the changes done on the fly

A: No, you don't run any risk of overwriting your configuration file. The configuration will be read from that file and kept in memory. ES also allows to persistently change settings at runtime, but they are stored in another global cluster state file (in data/CLUSTER_NAME/nodes/N/_state, where N is the 0-based node index) and re-read on each restart.


text:
Q: In NodeJS, how to download files from S3 In ExpressJS, I would like to download files previously uploaded to an Amazon S3 bucket.
Here is my current route:
const express = require('express');
const AWS = require('aws-sdk');
const mammoth = require('mammoth');
const fs = require('fs').promises
const path = require('path')
const router = express.Router();

router.put('/:id/download', async (req, res, next) => {
  console.log('hitting download route')

  var id = req.params.id;
  let upload = await Upload.query().findById( id ).eager('user');

  console.log("file to download is: ", upload.name)

  AWS.config.update({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  });

  const s3 = new AWS.S3();

  // var fileStream = fs.createWriteStream('/tmp/file.docx');
  // var s3Stream = s3.getObject(params).createReadStream();

  const downloadFromS3 = async () => {
    const params = {
      Bucket: process.env.AWS_BUCKET,
      Key: upload.file_url.split("com/").reverse()[0]
    };
    const { Body } = await s3.getObject(params).promise()
    await fs.writeFile(`${ __dirname }/download.docx`, Body)

    return Body
  }

  // mammoth.convertToHtml({ path: '/Users/dariusgoore/Downloads/1585930968750.docx' })
  //   .then(async function(result) {
  //     await Upload.query().findById( id )
  //       .patch({
  //          html: result.value,
  //          conversion_messages: result.messages
  //       })
  //     res.json(result);
  //   })

    // .done();

  res.send(downloadFromS3)
});

I get no errors, but the file is not created, or if I manually create the file, it remains empty.

A: If I've understood you correctly the issue is that you're not waiting for the file to be written to the local file system, you're returning it in the response via express.
Give this code a go.
const express = require('express')
const AWS = require('aws-sdk')
const mammoth = require('mammoth')

const fs = require('fs').promises
const path = require('path')

const router = express.Router()

const s3 = new AWS.S3()

AWS.config.update({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
})

const downloadFromS3 = async (key, location) => {
    const params = {
        Bucket: process.env.AWS_BUCKET,
        Key: key,
    }

    const { Body } = await s3.getObject(params).promise()
    await fs.writeFile(location, Body)

    return true
}

router.put('/:id/download', async (req, res, next) => {
    console.log('hitting download route')

    const upload = await Upload.query()
        .findById(req.params.id)
        .eager('user')

    console.log('file to download is: ', upload.name)

    const key = upload.file_url.split('com/').reverse()[0]

    const location = `${__dirname}/${key}.docx`

    await downloadFromS3(key, location)

    res.send({ key, location })
})

A:

import { S3 } from 'aws-sdk';
import fs from 'fs';

export default class S3Service {
    s3: S3;
    constructor() {
        this.s3 = new S3({
            apiVersion: *****,
            region: ********
        });
    }

    //Download File
    async download(bucketName: string, keyName: string, localDest?: string): Promise<any> {
        if (typeof localDest == 'undefined') {
            localDest = keyName;
        }
        const params = {
            Bucket: bucketName,
            Key: keyName
        };
        console.log("params: ", params);

        let writeStream = fs.createWriteStream(localDest);

        return new Promise<any>((resolve, reject) => {
            const readStream = this.s3.getObject(params).createReadStream();

            // Error handling in read stream
            readStream.on("error", (e) => {
                console.error(e);
                reject(e);
            });

            // Resolve only if we are done writing
            writeStream.once('finish', () => {
                resolve(keyName);
            });

            // pipe will automatically finish the write stream once done
            readStream.pipe(writeStream);
        });
     }
  }


text:
Q: Build artifact retention setting being ignored I had a build be deleted from the retain policy and I want to increase the retain policy time.
I go to project settings->pipelines->settings and it says
'The artifacts and attachments retention setting is being ignored because the runs retention setting is evaluated first.'
and it won't let me change the 'days to keep artifacts and attachments'
I can't seem to find where this setting is...
I've looked under project settings -> Test -> Retention but I'm not sure that's the place.

A:
Build artifact retention setting being ignored

This behavior is by designed and is not a issue.
As we know, the artifacts and attachments are generated from the pipeline runs. If the build pipeline is deleted, the artifacts and attachments it generates will also be deleted.
That the reason why you set the value of Days to keep artifacts and attachments greater than or equal to the value of Days to keep runs, you will get that prompt:

When you set the value of Number of days to keep artifacts and attachments less than the value of Days to keep runs, that warning will disappear:

So, if you want to increase the retain policy time for Build artifact, you need increase the retain time for Days to keep runs.

it won't let me change the 'days to keep artifacts and attachments'

That because you don't have enough permissions, to change the Retention policy, you must be a member of the Project Collection Administrators Group.
Check the document Set permissions at the project- or collection-level for some more details.
Or you can ask someone in the PCA to change the Retention policy.
Hope this helps.


text:
Q: Connect to private github repository with libgit2 I'm trying to fetch a private github repository using libgit2. The repo belongs to an organization and I have read/write permissions. The program is written in Objective-C++. I have this:
- (int)fetchBranches
{
    git_remote *remote = NULL;
    int result = 0;
    if (!(result = git_remote_load(&remote, repo, "origin"))) {
        git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
        callbacks.credentials = cred_acquire_cb;
        git_remote_set_callbacks(remote, &callbacks);
        result = git_remote_fetch(remote);
    }
    return result;
}

int cred_acquire_cb(git_cred **out,
                    const char * url,
                    const char * username_from_url,
                    unsigned int allowed_types,
                    void * payload)
{
    return git_cred_ssh_key_new(out, "GITHUBUSERNAME", "/Users/admin/.ssh/id_rsa.pub", "/Users/admin/.ssh/id_rsa", "PASSPHRASE");
}

This creates the credentials but when I do the fetch it fails when trying to authenticate the session with libssh2. (libgit2/src/transports/ssh.c:302):
rc = libssh2_userauth_publickey_fromfile(
      session, c->username, c->publickey,
      c->privatekey, c->passphrase);

The error is -18, LIBSSH2_ERROR_AUTHENTICATION_FAILED. I've confirmed that the public key is added to Github and tried to change it for a new one too. Also the passphrase is correct and the username is my github username. I can do the fetch through the console too. The remote config is:
[remote "origin"]
    url = git@github.com:ORGNAME/REPONAME.git
    fetch = +refs/heads/*:refs/remotes/origin/*

I've also tried to get the key from the git-agent in OSX with the same result:
return git_cred_ssh_key_from_agent(out, "GITHUBUSERNAME");

Finally I tried using the plaintext authentication:
return git_cred_userpass_plaintext_new(out, username, password);

This last method works after changing the repo url to the HTTPS address. The problem is that it requires the user to input the password each time or store the git_cred struct which contains the password in blank (don't like that).
Anyone knows why the ssh authentication is failing? Is there a way to avoid having to input the username/password with each operation (with the plaintext authentication)?

A: The user when talking over ssh is "git" (thus all the urls are git@github.com:user/repo), so you should use that instead of the "real" username on GitHub. The key you send is what the server uses to determine which user it is dealing with.


text:
Q: Installing node.js with express module I'm on latest stable debian
I am able to do apt-get install nodejs but cannot install npm with apt, so I compiled from wget http://nodejs.org/dist/v0.8.16/node-v0.8.16.tar.gz and everything looks good.
Now I want to install the express module globally and did sudo npm install -g express
but I get this warning:
npm WARN engine express@4.11.1: wanted: {"node":">= 0.10.0"} (current: {"node":"v0.8.16","npm":"1.1.69"})

then typing express in the commandline says command not found. What am I doing wrong?

A: I was on the old version.
I needed to get the latest one from here:
http://nodejs.org/dist/latest/node-v0.10.36.tar.gz
Then running the commands after untaring
./configure
make
sudo make install

Then npm install -g express


text:
Q: "Access is denied (user is not anonymous)" with spring-security-oauth2 I'm new to Spring Security and Oauth, and I'm trying to set up a simple example protecting the access to resources in path "/api" with Oauth2. I'm using spring-security-oauth2-1.0.0.RC2.  After some time dealing with configuration, I'm able to get tokens, but when I try to send requests to "/api" resources, I'm facing two questions:

*

*Initially, I'm sending authorization header with "OAuth2" prefix, but spring-security-oauth2 seems to need headers with "Bearer" prefix in the tokens to find them. What's the difference between these tokens?

*After Spring validated the token, I'm getting a security error: "ExceptionTranslationFilter - Access is denied (user is not anonymous)" and I'm stuck with this problem. Since I'm using InMemory token store, I have to login each time to authorize client, then I'm getting this error. Here is the spring configuration:

<http pattern="/api/**" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint"
    access-decision-manager-ref="accessDecisionManager" xmlns="http://www.springframework.org/schema/security">
    <anonymous enabled="false" />
    <intercept-url pattern="/api/**" access="ROLE_CLIENT,SCOPE_READ" />
    <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
    <access-denied-handler ref="oauthAccessDeniedHandler" />
</http>

<http disable-url-rewriting="true" xmlns="http://www.springframework.org/schema/security">
    <intercept-url pattern="/oauth/**" access="ROLE_USER" />
    <!--intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" /-->
    <form-login/>
    <logout logout-success-url="/index.jsp" logout-url="/logout" />
</http>

<bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
    <property name="realmName" value="O2Server" />
</bean>

<bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />

<bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
    <property name="authenticationManager" ref="clientAuthenticationManager" />
</bean>

<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased" xmlns="http://www.springframework.org/schema/beans">
    <constructor-arg>
        <list>
            <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
            <bean class="org.springframework.security.access.vote.RoleVoter" />
            <bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
        </list>
    </constructor-arg>
</bean>

<authentication-manager id="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security">
    <authentication-provider user-service-ref="clientDetailsUserService" />
</authentication-manager>

<authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security">
    <authentication-provider>
        <user-service>
            <user name="test" password="test" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</authentication-manager>

<bean id="clientDetailsUserService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
    <constructor-arg ref="clientDetails" />
</bean>

<bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore" />

<bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
    <property name="tokenStore" ref="tokenStore" />
    <property name="supportRefreshToken" value="true" />
    <property name="clientDetailsService" ref="clientDetails"/>
</bean>

<bean id="userApprovalHandler" class="org.o2server.security.O2ServerUserApprovalHandler">
    <property name="tokenServices" ref="tokenServices" />
</bean>

<oauth:authorization-server client-details-service-ref="clientDetails" token-services-ref="tokenServices" user-approval-handler-ref="userApprovalHandler">
    <oauth:authorization-code />
    <oauth:implicit />
    <oauth:refresh-token />
    <oauth:client-credentials />
    <oauth:password />
</oauth:authorization-server>

<oauth:resource-server id="resourceServerFilter" resource-id="O2Server" token-services-ref="tokenServices" />

<oauth:client-details-service id="clientDetails">
    <oauth:client client-id="O2Client" resource-ids="O2Server" authorized-grant-types="authorization_code,refresh_token,implicit"
        authorities="ROLE_CLIENT" scope="read,write" secret="secret" />
</oauth:client-details-service>

<oauth:web-expression-handler id="oauthWebExpressionHandler" />

This is the log from the server:
11:58:30.366 [DEBUG] FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /api/user/; Attributes: [ROLE_CLIENT, SCOPE_READ]
11:58:30.366 [DEBUG] FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.oauth2.provider.OAuth2Authentication@48a94464: Principal: org.springframework.security.core.userdetails.User@346448: Username: paul; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails@43794494; Granted Authorities: ROLE_USER
11:58:30.366 [DEBUG] UnanimousBased - Voter: org.springframework.security.oauth2.provider.vote.ScopeVoter@4e857327, returned: 0
11:58:30.366 [DEBUG] UnanimousBased - Voter: org.springframework.security.access.vote.RoleVoter@1b4b2db7, returned: -1
11:58:30.367 [DEBUG] ExceptionTranslationFilter - Access is denied (user is not anonymous); delegating to AccessDeniedHandler <org.springframework.security.access.AccessDeniedException: Access is denied>org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.UnanimousBased.decide(UnanimousBased.java:90)

Please, could you give me some advice?
Thank you in advance.

A: I have never used oauth plugin but from reading debug output I can say that RoleVoter returned -1, which means access was denied by DecisionVoter. I see that you granted only ROLE_USER to principal which is trying to access url /api/user/, which is secured by [ROLE_CLIENT, SCOPE_READ] and that's the reason why access was denied.
Either grant ROLE_CLIENT and SCOPE_READ to principal or change <intercept-url pattern="/api/**" access="ROLE_CLIENT,SCOPE_READ" />.

A: As Xaerxess said, you should change your intercept-url access property to ROLE_USER.
<intercept-url pattern="/api/**" access="ROLE_CLIENT,SCOPE_READ" />

to
<intercept-url pattern="/api/**" access="ROLE_USER,SCOPE_READ" />

The access property controls the role of the user (which the client acts on behalf of).
The documentation of the authorities (ROLE_CLIENT) property of tag <oauth:client> states:

Authorities that are granted to the client (comma-separated). Distinct
  from the authorities granted to the user on behalf of whom the client
  is acting.

Also, according to user Dave Syer:

If you didn't change Tonr, it is not acting as a client, it is acting
  on behalf of a user (who will not have the required ROLE_CLIENT), so
  it is expected that you would get a 403. If you want to make an
  assertion about the request from tonr being from a client with a
  specific role (without changing the app) you can use an expression,
  e.g. "oauthClientHasRole('ROLE_CLIENT') and hasScope('trust')".

Source:
http://forum.springsource.org/showthread.php?125468-confusing-between-ROLE_USER-ROLE_CLIENT


text:
Q: Full integration of encrypted properties in Spring 4/Boot We're using Jasypt to encrypt some config properties (database passwords) but since the decryption key is stored on each environment's file system we have to do some manual @Bean configuration to load the password from the file then overlay loading properties with an EncryptablePropertiesPropertySource.
Because it is so manual we've had to run this code in @PostConstruct of the WebApplicationConfig class and (although this hasn't happened yet) it runs the risk of loading these after the datasource bean is configured with calls to the Environment - giving null pointer exception.  @Lazy loading would be an option but obviously this means we'd then be working with fragile config which we'd like to avoid.
Ultimately we want to be able to use the default classpath:application.properties so don't want to affect existing (default) setup, but we do want to be able to use an encryptable property source as a complete replacement to the Spring one, and to have Spring load the decryption code from a file before anything else happens. Is there a way to tighter integrate loading encryptable properties earlier in the application startup and configuration?

A: The link Dave provided in the comments section unfortunately points to nothing now, but navigating from its root I got to the following example project:
https://github.com/spring-cloud-samples/configserver (also written mostly by Dave, of course)
I think it serves as a great example for what was discussed in the comments until now.
Also, for future reference (maybe it will be done at some point), there's a Spring Framework Jira ticket for the feature of using encrypted properties: https://jira.spring.io/browse/SPR-12420

A: I'm "tailoring down" my previous answer since it got deleted because it was duplicate from a different question:
This library does exactly what you need jasypt-spring-boot which is basically to allow you use the @PropertySource annotation to define your properties the same way you're use to. You just have to add an extra annotation (@EnableEncryptableProperties) to your configuration file.
It is not only limited to that, every PropertySource present in Environment will be converted to EncryptablePropertySourceWrapper, a custom wrapper that checks when a property is encrypted and decrypts it on access.


text:
Q: Why does redux dispatch happen before hook values are updated? I have an interesting problem in my code and I am not sure why it happens. Hopefully someone can explain. Basically, I am using "setValues" for my hooks before I call the "dispatch"-method. However, it seems like dispatch is still triggered before the values in the hooks are updated. Even though to me it seems like it should be the other way around. Why does this happen? Here is some of the code:
import React, { useState } from 'react';
import Grid from '@material-ui/core/Grid';
import InputField from 'shared/components/form/Inputfield';
import DatePicker from 'shared/components/pickers/DatePicker';
import InfoButton from 'shared/components/buttons/InfoButton';
import CustomButton from 'shared/components/buttons/CustomButton';
import TextArea from 'shared/components/form/TextArea';
import { connect } from 'react-redux';

export function ProjectDetails(props) {
    const [values, setValues] = React.useState({
        full_project_name: ' ',
        short_name: ' ',
        associated_projects: ' ',
        short_description: ' ',
    });

    const handleInputFieldChange = field_name => event => {
        setValues({ ...values, [field_name]: event.target.value });
        //why does dispatch happen before values are updated?
        props.dispatch({ type: 'PLEASE_WORK', payload: values });

    };

    console.log('Project values', values);

    return (
        <>

Project Details

            <Grid container spacing={1}>
                <Grid item xs={12}>

Full project name *

                </Grid>
                <Grid item xs={12}>
                    <InputField
                        handler={handleInputFieldChange('full_project_name')}
                        placeHolderText="Please type the last letter two times"
                    />
                </Grid>
                <Grid item xs={12}>

Short name (Acronym)

                </Grid>
                <Grid item xs={12}>
                    <InputField handler={handleInputFieldChange('short_name')} />
                </Grid>
            </Grid>
        </>
    );
}

function mapStateToProps(state) {
    return {
        full_project_name: state.projectReducer.full_project_name,
        short_name: state.projectReducer.short_name,
    };
}

export default connect(mapStateToProps)(ProjectDetails);

A: React setState is asynchronous, this means that when you call setValues to set the state of values it initiates the process but proceeds to execute the next line before necessarily finishing.
You could call dispatch with the exact value as well to ensure it is correct, like props.dispatch({ type: 'PLEASE_WORK', payload: { ...values, [field_name]: event.target.value } });

A: To further add to Maddo's answer, if you think about it, the React Component, in the end, is actually just a regular function that got called at some point:
export function ProjectDetails(props)

So, when the function is called, the variables inside its scope simply hold the value of what was there when the function was called (let's say, on that run of the render):
const [ values, setValues ] = useState(...); // <-- values is const

Essentially, values won't change in the current "run" and only after the next time the component is rendered. Notice it's even declared as const to make sure we can't touch it ;)
What is the result of console.log(values) here?
If in doubt, console.log can be your friend (alert is even more fun to use!)
const handleInputFieldChange = field_name => event => {
  setValues({ ...values, [field_name]: event.target.value });

  // -> what is the result of values here ? (hint: values is const)
  console.log('values is:', JSON.stringify(values));

  props.dispatch({ type: 'PLEASE_WORK', payload: values });
};

The way I prefer to do it, is to simply put everything in a new variable to assure we are using that:
const handleInputFieldChange = field_name => event => {
  const newValues = { ...values, [field_name]: event.target.value };

  setValues(newValues);
  props.dispatch({ type: 'PLEASE_WORK', payload: newValues });
};

This makes skimming through the code easier to understand: you created a newValues, set it in the state, and then dispatched an action with it.
Hope this makes sense!

A: UseEffect can also help you to resolve the problem with async call "setValues".
You can set the "values" as dependencies to useEffect, then just simply trigger dispatch in useEffect.
I create here a DEMO:

Please have a look at the console logs.


text:
Q: Sort first dimension of two dimensional array only Google Script I am trying to sort only the first dimension of a two-dimensional array
I have
arr = [a,b,c,a,b,c,a,b,c]

arr1 = arr.sort() --> arr1 = [a,a,a,b,b,b,c,c,c]

result = transpose([arr1,arr])

Which gives
result = [[[a],[a]],[[a],[a]],[[a],[a]],[[b],[b]],[[b],[b]],[[b],[b]],[[c],[c]],[[c],[c]],[[c],[c]]]

But I need (and expected)
result = [[[a],[a]],[[a],[b]],[[a],[c]],[[b],[a]],[[b],[b]],[[b],[c]],[[c],[a]],[[c],[b]],[[c],[c]]]

Thanks

A: You need to make an actual clone of the array, arr is being sorted in what you are doing.
try this:
arr = [a,b,c,a,b,c,a,b,c]

arr1 = arr.slice(0);
arr1.sort();

result = transpose([arr1,arr])

My testing is limited because transpose isn't a GAS function and you didn't include it.
Actually with, this, it seems to work:
function transpose(a)
{
  return Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });
}


text:
Q: SharePoint solution deployment running forever - SharePoint 2007 I'm using following scripts to install/uninstall a solution
Uninstall.bat
@echo off

echo *****************************************************
echo Un-Installing <solution>  -
echo (C) <company>. All rights reserved.
echo *****************************************************

set stsadm="%programfiles%\common files\microsoft shared\web server extensions\12\bin\stsadm.exe"

echo Retracing solution.wsp
%stsadm% -o retractsolution -name solution.wsp -immediate -allContentURLs

%stsadm% -o execadmsvcjobs

echo Wait till the solution retraction is completed (check the central administration)
pause

echo Deleting solution from the solution store
%stsadm% -o deletesolution -name solution.wsp -override

%stsadm% -o execadmsvcjobs

echo - Restarting WSS Timer service
net stop "windows sharepoint services timer"
net start "windows sharepoint services timer"

echo Uninstallation completed successfully

echo.
pause

Install.bat
@echo off
set STSADM="C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe"

echo *****************************************************
echo Installing <solution>  -
echo (C) <company>. All rights reserved.
echo *****************************************************

echo Adding solution.wsp to the solution store
%STSADM% -o addsolution -filename solution.wsp

echo Deploying solution
%STSADM% -o deploysolution -name solution.wsp -force -immediate -allowGacDeployment -allContentURLs

%STSADM% -o execadmsvcjobs

echo Installation completed successfully

IISRESET

Restarting SharePoint Timer Service..

NET STOP SPTIMERV3
NET START SPTIMERV3

REM echo copying resources..
REM %STSADM% -o copyappbincontent

echo.
pause

But the install.bat is stuck at execadmsvcjobs after the deployment. When I checked the TaskManager the CPU usage spiked up to 100% and STSADM.EXE and OWSTIMER.EXE was consuming lot of memory. So the deployment is running forever.
Any ideas?

A: This is quite a common issue and unlikely to be a problem with the actual WSP file you are deploying. Have a look at the following resources.

A: i would suggest to go through the log bieng genrated in 12 hive log folder that will help you to find the cause of the problem.
this type of problem arises when any of the required resources for deployment is missing or down for maintenance. Like if you have multiple web servers in your farm and any one is down due to some issues and you have not detached it from your SharePoint farms it tries to find it and since it is not available job hangs. same case may happen when you are trying to deploy it in all web apps and either of the web app is not available.
to kill the job which is continuously running you can take help from following post
http://blog.hinshelwood.com/archive/2008/12/10/removing-a-dead-solution-deployment-from-moss-2007.aspx


text:
Q: Function name for square brackets creating list Apologies for the simple question - I've spent a while trying to answer it.
When [] is used for indexing, Python calls the function __getitem__. What function does Python call when [] is used to create a list?

A: Basically, Python is an interpreter and these brackets are interpreted, without any function or whatever. __getitem__ just pushes variable into raw interpreter.


text:
Q: Including categorical features along with text in wordvec approach- Python My data has mix of text and categorical features. It looks like:
cr_id   description                  business type                       status
    1   More robust system required secured loan    system  rejected
    2   More robust system required secured loan    system  rejected
    3   grant access to all products    mortgage    system  rejected
    4   EDAP Scenario   secured loan    regulatory           accepted
    5   grant access to all products    secured loan    regulatory  accepted

Now on description column I am applying word2vec approach. As a result I get a trained vector of 300 columns. Now my question is how to include categorical features in the model too. I mean how to combine the output of word2vec and one-hot coded vectors as they are of different shape.Code used to form wordvec is:
def review_to_wordlist(review, remove_stopwords=False):
    """
    Convert a review to a list of words. Removal of stop words is optional.
    """
    # remove non-letters
    review_text = re.sub("[^a-zA-Z]"," ", review)

    # convert to lower case and split at whitespace
    words = review_text.lower().split()

    # remove stop words (false by default)
    if remove_stopwords:
        stops = set(stopwords.words("english"))
        words = [w for w in words if not w in stops]

    return words

def review_to_sentences(review, tokenizer, remove_stopwords=False):
    """
    Split review into list of sentences where each sentence is a list of words.
    Removal of stop words is optional.
    """
    # use the NLTK tokenizer to split the paragraph into sentences
    raw_sentences = tokenizer.tokenize(review.strip())

    # each sentence is furthermore split into words
    sentences = []
    for raw_sentence in raw_sentences:
        # If a sentence is empty, skip it
        if len(raw_sentence) > 0:
            sentences.append(review_to_wordlist(raw_sentence, remove_stopwords))

    return sentences

train_sentences = []  # Initialize an empty list of sentences
for review in data['description']:
    train_sentences += review_to_sentences(review, tokenizer)

model_name = 'train_model'
# Set values for various word2vec parameters
num_features = 300    # Word vector dimensionality
min_word_count = 3   # Minimum word count
num_workers = 3       # Number of threads to run in parallel
context = 10          # Context window size
downsampling = 1e-3   # Downsample setting for frequent words
print 1
if not os.path.exists(model_name):
    # Initialize and train the model (this will take some time)
    model = word2vec.Word2Vec(train_sentences, workers=num_workers, \
                size=num_features, min_count = min_word_count, \
                window = context, sample = downsampling)
    print 10
    # If you don't plan to train the model any further, calling
    # init_sims will make the model much more memory-efficient.
    model.init_sims(replace=True)

    # It can be helpful to create a meaningful model name and
    # save the model for later use. You can load it later using Word2Vec.load()
    model.save(model_name)
else:
    print 11
#     model = Word2Vec.load(model_name)
    model=KeyedVectors.load(model_name)

def make_feature_vec(words, model, num_features):
    """
    Average the word vectors for a set of words
    """
    feature_vec = np.zeros((num_features,),dtype="float32")  # pre-initialize (for speed)
    nwords = 0
    index2word_set = set(model.wv.index2word)  # words known to the model

    for word in words:
        if word in index2word_set:
            nwords = nwords + 1.
            feature_vec = np.add(feature_vec,model[word])

    feature_vec = np.divide(feature_vec, nwords)
    return feature_vec

def get_avg_feature_vecs(reviews, model, num_features):
    """
    Calculate average feature vectors for all reviews
    """
    counter = 0
    review_feature_vecs = np.zeros((len(reviews),num_features), dtype='float32')  # pre-initialize (for speed)

    for review in reviews:
        review_feature_vecs[counter] = make_feature_vec(review, model, num_features)
        counter = counter + 1
    return review_feature_vecs

clean_train_reviews = []
for review in data['description']:
    clean_train_reviews.append(review_to_wordlist(review, remove_stopwords=True))
trainDataVecs = get_avg_feature_vecs(clean_train_reviews, model, num_features)

Now I can use these traineddatavecs to any classifier for prediction of status. Now as stated above I am confused how to include/append the categorical fetaures such as type with the trainedDataVecs as they are of different shapes.
Edit: As required to understand the problem better, the trainedDatavecs looks like below:
array([[-0.02591809, -0.04678563, -0.0401891 , ..., -0.00907444,
        -0.02070936, -0.02332937],
       [ 0.00098296, -0.00293253,  0.04667222, ...,  0.00685261,
        -0.01234391, -0.03822058],
       [ 0.01843361, -0.01345504, -0.01359649, ..., -0.04710409,
         0.04892955,  0.02135875],
       ...,
       [ 0.0304883 ,  0.08515919,  0.01928426, ..., -0.00903708,
        -0.00333895,  0.07550056],
       [ 0.01843361, -0.01345504, -0.01359649, ..., -0.04710409,
         0.04892955,  0.02135875],
       [ 0.01843361, -0.01345504, -0.01359649, ..., -0.04710409,
         0.04892955,  0.02135875]], dtype=float32)

Its dimensions are (40, 300) and the input training data has dimension of (40,5). 300 columns are coming from the number of features argument.

A: Looks like trainDataVecs is just a numpy matrix. You can generate the dummies and try concatenating them.
dummies = pd.get_dummies(df['business type']).iloc[:, 1:] # take n-1 columns
dummies = dummies.as_matrix()
X = np.concatenate((trainDataVecs, dummies), axis=1)

*

*Dummify the columns

*Create numpy matrix

*Concatenate them by column axis
Note:
There might be a dimension issue. Please post how trainDataVecs will look like in that case and I can update to reflect.


text:
Q: Signed .CAB results in "Unknown publisher" on windows mobile 6.5 I have purchased a certificate from http://www.ksoftware.net/ which I use to sign a .CAB file used for installation of our software on windows mobile 6.5 devices. However, even after signing the .CAB, when attempting to install the application on the device (via the CAB) the device alerts "Unknown publisher".  These CAB files are downloaded from a webservice and are supposed to be installed automatically using wceload and its silent install options, but this fails since the CAB is not recognized as signed (once I have manually installed a particular CAB file, wceload will succeed for that CAB in the future).
Initially I only had the certificate set in the visual studio 2008 deployment properties, and the applications signing properties.  I also tried using signtool.exe, and thereafter cabsigntool.exe to sign all the other files in the CAB too. None of these methods work.  When checking the CAB's properties in Windows 7, the file does have a security certificate attached, but any attempt to install on the device gives the annoying "unknown publisher" popup box.
Is there anything I am missing? What could be causing the devices to still see the CAB files as unsigned?  The signing does not seem to work with plain exe's either.
Please note I do know the security settings can be changed in order for the prompt not to come up, but I am interested in solving the security certificate problem.

A: I assume the root certificate of the sign is not know on the device:

Did you verify that the certs are WindowsMobile compatible?


text:
Q: Drupal 7 RewriteRule not working My basic page access i.e : mysite/aboutus, which is working perfectly fine.
But due to request, every page except for home needs to be prefixed with training.
So if I need to go to mysite/aboutus, instead now I need to go to mysite/training/aboutus.
I edited almost every page I needed by rewriting mypage.tpl.php, so to change all path would be troublesome.
I tried to edited .htaccess in project folder, below are some of my attempts :
RewriteRule ^/training/about$ /about
RewriteRule ^(.*)/training/about$ $1/about

None works.
Could someone point me to the right direction?
Cheers !
    #
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|themes|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  Order allow,deny
</FilesMatch>

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_environment_initialize() in
# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

A: The following works for Drupal 7
RewriteRule ^home/code/([^/]+) ?q=home/software/node/&code=$1

make sure to exclude your condition before RewriteRule ^ index.php [L]
RewriteCond %{REQUEST_URI} !yourCustomReWriteRuleCondition
RewriteRule ^ index.php [L]

See here:
https://drupal.stackexchange.com/questions/55006/rewrite-url-not-working/94372#94372

A: I found out that drupal does has it's own way to reroute page.
The function is located in yoursite/includes/bootstrap.inc and is called request_path().
And yes, I did manipulate that function to leave out any training/. I know this is a very ugly way to do things, but I don't have time to sit idle and do all htaccess possibilities.


text:
Q: VueJS add  after every 25 's - IE DOM not recognizing
A: One alternative solution, uses computed property to re-shape the dataset then get the desired result like below demo:

Vue.config.productionTip = false
app = new Vue({
  el: "#app",
  data: {
    dataset: Array.from({length: 10}, (v, i) => Array.from({length: 3}, (subV, subI) => {
      return i
    }) ),
    headerOccp: 4,
    headers: ['A', 'B', 'C']
  },
  computed: {
    computedDataset: function () {
      return this.dataset.reduce((pre, cur) => {
        if(pre.length % this.headerOccp === 0) {
          pre.push({'type':'header', 'data':this.headers})
        }
        pre.push({'type':'row', 'data':cur})
        return pre
      }, [])
    }
  }
})
.header {
  background-color: green;
  font-weight: bold;
}
.row {
  color: red;
}

          {{ cell }}

Data:

    {{computedDataset}}


text:
Q: Output link from mySQL database into table below is my PHP code, I just can't figure out how to make the "INFO" text appear as a clickable url. I've seen the echo method but not one that works for the below. This method needs to create a link using the data and also set the link as the text used inside the table.
  <?php
        if(isset($data) && !empty($data)) {
            foreach ($data as $row) {

                @$count += 1;
                $keyword = htmlspecialchars($row['Keyword']);
                $suburb = htmlspecialchars($row['Suburb']);
                $postcode = htmlspecialchars($row['Postcode']);
                $status = htmlspecialchars($row['Status']);
                $info = htmlspecialchars($row['Info']);

                @$table_row .= "
$count	$keyword	$suburb	$postcode	$status	$info
";
            }
            echo @$table_row;
        }
        ?>

It's the 'Info' column that i want to pull in as a url.
Cheers,
Curtis
http://www.homegiraffe.com.au

A: $info = '' . htmlspecialchars($row['Info']) . '';

This is the answer. Thanks to Chris85 for the help!

A: you can use this

<?php
        if(isset($data) && !empty($data)) {
            foreach ($data as $row) {

                @$count += 1;
                $keyword = htmlspecialchars($row['Keyword']);
                $suburb = htmlspecialchars($row['Suburb']);
                $postcode = htmlspecialchars($row['Postcode']);
                $status = htmlspecialchars($row['Status']);
                $info = htmlspecialchars($row['Info']);
?>

<?php echo $count;?>	<?php echo $keyword;?>	<?php echo $suburb;?>	<?php echo $postcode?>	<?php echo $status;?>	<a href="<?php echo $row['Info'];?>"><?php echo $info;?>
;
<?php
            }
        }
        ?>

and it work very good :)


text:
Q: My Bluetooth problem I had a friend who Bluetooth me a website, but I can't seem to find it. I have checked my documents, videos, pictures and download section. Any suggestions where it might be?

A: I found some of my Bluetooth files in the /Public folder in my Home directory. Don't know how or why, but they were there.


text:
Q: In place usage of C++  algorithms Several STL algorithms have the general form:
Algorithm(InputIterator first1, InputIterator last1, OutputIterator result,...)

or
Algorithm(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result,...)

My question is - when can the OutputIterator result be in the range (first1,last1) or (first2,last2)?
For transform the answer I found here: http://www.cplusplus.com/reference/algorithm/transform/
But there are multiple others that may make sense, e.g. set_difference should theoretically be safe for such a usage and also it works in code with GCC 4.7.1.
Any references?

A: There is no general answer for all algorithms. For set_difference you can learn from C++11 25.4.5.4/2 that:
Requires: The resulting range shall not overlap with either of the original ranges. This seems to make your code undefined behavior that seems to do what you want.
You'll just have to look at the requirements for a particular algorithm before you decide what iterator ranges to use.


text:
Q: Property of finite structure inexpressibiliy in first-order logic I want two show that a certain property $u$ of some finite structure is not definable in first-order logic.
Is the following reasoning correct?
Let $\mathcal{S}$ denote a finite structure. Further, we can "transform" $\mathcal{S}$ to another finite structure $\mathcal{S'}$ (through some kind of bijection).
We already know that a property $p$ of $\mathcal{S}$ is not definable in first-order logic. Now we assume that $u$ is definable by a sentence $\varphi$. Further, we can show that
$$
\mathcal{S'} \models \varphi \iff \mathcal{S} \text{ has property } p.
$$
That this prove that property $u$ of $\mathcal{S}$ of is not definable in first-order logic?

A: I have given a couple of examples of this technique here and here.
The basic idea is in these two answers was the following:  First assume that some first order formula $\varphi ( \bar{x} )$ defines yur relation/function/whatever in the structure $\mathcal{N}$ you are interested in.  Then you want to apply an automorphism of $\mathcal{N}$ to show that there are $\bar{a}$ in the universe of $\mathcal{N}$ such that looking at things in one direction you have that $\mathcal{N} \models \varphi ( \bar{a} )$, but looking at it from another direction you get that $\mathcal{N} \models \neg \varphi ( \bar{a} )$.  (One direction will come from the definition of property in question, the other from the fact that automorphisms of $\mathcal{N}$ must preserve first-order properties.)
In the two examples I have linked to, there were not enough automorphisms of the structures we were really interested in.  We then went to elementary extensions of these structures, which are rich in automorphisms, and show that similar contradictory consequences hold.  We went to elementary extensions because if $\varphi ( \bar{x} )$ is supposed to define a relation with certain first-order properties in  $\mathcal{N}$, then it must also define a relation with the same first-order properties in every elementary extension of $\mathcal{N}$.


text:
Q: Rename column name in the whole database (all schemas) I would like to rename a column currently named deviceID into a more eloquent style device_id. Doing it into MySQL then in my code base with a sed s/deviceID/device_id seems to be the best solution.
So I wrote this helper:
SELECT
    CONCAT('ALTER TABLE `', TABLE_SCHEMA, '`.`', TABLE_NAME,
            '` CHANGE COLUMN `', COLUMN_NAME, '` `device_id` ',
            COLUMN_TYPE, IF(IS_NULLABLE = 'YES', ' NULL', ' NOT NULL'),
            IF (COLUMN_DEFAULT IS NULL, '', CONCAT('DEFAULT ', COLUMN_DEFAULT)), ';')
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    COLUMN_NAME LIKE 'deviceID';

Then I can pipe the output into mysql.
Is there a simpler and safer solution?