text:
Q: Hover affecting only single element in nested set I can't change the following HTML structure which has nested
 elements that all have the same class block. I want to enable a hover behavior that only affects the element that the mouse is over at the moment, not any of the other nested elements.

                Text

            Text

        Text

    Text

Here's the fiddle to demonstrate: http://jsfiddle.net/FqKCY/3/
I tried to use this:
$( ".block" ).hover(
    function() {
        $( this ).addClass( "hover" );
    }, function() {
        $( this ).removeClass( "hover" );
    }
);

But it didn't help. Maybe I shall add if statement with .hasClass checker?
Is the effect I'm trying for possible?

A: I tried to change the markup a bit. Check this fiddle.
HTML:

                Text

            Text

       Text

    Text

A: This solution utilizes the .hover() function you started with. A better solution might be to write your own handler that prevents event propagation using .on(). You'll note that the text for the entire stack is changed because the .css inherits, but you could modify the .css so that this doesn't happen.
The technique used is to remove all hovering on entry, and then apply it only to the current element. On exit remove from all, and then only apply to a parent element if it exists.
$(".block").hover(function () {
    $(".block").removeClass("hover");
    $(this).addClass("hover");
}, function () {
    $(".block").removeClass("hover");
    $(this).parent(".block").addClass("hover");
});

JSFiddle: http://jsfiddle.net/FqKCY/5/


text:
Q: Ajax call not getting data which is in json format from API I am trying to call api function from asp.net core razor page from news.cshtml page using below ajax function.
Its giving undefined error for console.log(len);... if i remove this then nothing happens no data, no error
 $.ajax({
                url: "api/news/getallnews/1",
                type: "GET",
                dataType: "json",
                success: function (response) {
                    //console.log(response);
                    var len = response.length;
                    console.log(len);
                    var table = $("

Details
");
                    for (var i = 0; i < len; i++) {
                       // console.log("i "+i);
                        table.append("
Title:	" + response[i].newsHeading + "
");
                    }
                    table.append("
");
                    $("#news").html(table);
                }
            });

json Data returnet by api, i am just showing one row while my api returns around 36
    {"data":[
    {
    "newsID":2076,
"newsHeading":"New Title is here",
    "newsBrief":"New Brief is here",
    "newsDetails":"\u003Cp\u003E\r\n\t\u003Cem\u003E New details in HTML format are here.\u003C/p\u003E\r\n",
    "newsDate":"2020-01-28T00:00:00",
    "languageID":1
    }]}

A: Try this:
var len = response.data.length;
console.log(len);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to watch for a property change in a directive I have an angular directive (with isolate scope) set up like this

(which actually gets rendered multiple times because it's inside an ng-repeat.)
Following the instructions of this SO answer, I tried to observe myprop for changes in the directive, however, the code inside the $scope.watch never runs even when the property changes (on a click event). I also tried scope.$watch(attrs.myprop, function(a,b){...)and it never ran either. How do I watch for the change in myprop
myapp.directive('somedirective', function () {
  return {
    restrict: 'AE',
    scope: {
      datajson: '=',
      myprop: '@'
    },
    link: function (scope, elem, attrs) {
      scope.$watch(scope.myprop, function (a, b) {
        if (a != b) {
          console.log("doesn't get called when a not equal b");
        } else {

        }
      });
    }
  };
}

Update: the click event that changes the property is handle in the controller and I'm guessing this isn't reflected back in the isolate scope directive so that $watch is never getting triggered. Is there a way to handle that?

A: When you use an interpolation binding (@) you cannot use scope.$watch, which is reserved for two-way bindings (=) or internal scope properties.
Instead, you need to use attrs.$observe which does a similar job:
link: function(scope, elem, attrs){
   attrs.$observe('myprop', function(newVal, oldVal) {
     // For debug purposes
     console.log('new', newVal, 'old', oldVal);
     if (newVal != oldVal){
          console.log("doesn't get called when newVal not equal oldVal");
      } else {
          // ...
     }
   });
 }

Also, everytime myprop change, the newVal will be different from its oldVal, so it is a bit weird that you skip that case which is the only one which will happen.
NOTE: you also forgot doublequotes for the datajson two-way binding: datajson="mydata"

A: Intead of passing a string, try it as variable
scope: {
     datajson: '=',
     myprop: '=' //change to equal so you can watch it (it has more sense i think)
  }

then change html, removing braces from mydata.myspecialprop


text:
Q: Dynamic order Numbering based on the view in sharepoint library 2010? We are trying to do in this library, is create a column that will provide the "order" number of the listed item, per view.
So in one view there may be five items that show and they need to be numbered 1 through 5.
Then in another view there may be 15 items that show and in this case they would need to display the numbering 1 through 15.
We have 12 views in total that would need the dynamic order numbering.
Please advise.
We are not able to use Visual Studio to work on this, only SharePoint Designer.

A: You can use SPD. On a page add the list view, then create a column and insert the following code:
<xsl:value-of select="count($thisNode/../*[not($thisNode/@ID=preceding-sibling::*/@ID)])" />

It should render the row number, no matter if you change the view order or filter some information.

Hope this helps

A: I have a list MyTestList. It has currently two views TestView1 and TestView2. To add serial number in the front follow the following steps:

*

*Open the site in SPD

*Open the List

*Edit the view in Split mode

*Select the List, Go to 'List View Tools' in the Ribbon > 'Design' > 'Customize XSLT' > 'Customize Entire View'

*This will convert the view in detail xslt

*Now click on the attachment column. Right Click > Insert > Column To The Left

*Save the Page

*Come to the Browser, Go to the List and Go to the View

*Edit the Page of the View

*Add a Content Editor WebPart in the Page.

*Change the Content Editor Webpart's Chorme Type to 'None'. So web part's tool should not be shown in the page.

*Click the Content Editor WebPart and go the HTML and paste the following lines showing in the Image to refer the Script.js and jquery-1.11.1.min.js. This will refer the Script, which will show the serial number

*Go to the 'Site Assets' and upload jquery-1.11.1.min.js and Script.js which will contain the following code:
$(document).ready(function () {
    var count=0;
    $('.ms-listviewtable tr td:nth-child(2)').each(function( index ) {
                count++;
                $(this).text(count);
            });
});
Above steps needs to be repeated in all the views you have. Best of luck.


text:
Q: Is NativeBase pure React Native? I'm trying to fully understand the meaning of this statement:

NativeBase is a mobile application development framework which enables
  developers to use React Native to build native mobile applications
  running on the major mobile platforms - Apple iOS and Google Android.

What does "development framework" mean exactly? If I were to get one of the NativeBase Starter Kits, am I getting pure React Native code or is it like Expo and isn't pure React Native?

A: Nativebase is actually a ui kit for react-native. As you know react is a frameworks which is used to build reusable components.Nativebase provides a lot of ready to use components which makes your development process faster & you don't have to put great efforts in developing complex UI components.
We can say nativebase is not a development framework but its a library & react is a development framework.


text:
Q: Understanding numpy's any function I came across a function named any with numpy and I could not understand its usage in some context which is given as folllows:
if np.subtract(original.shape, duplicate.shape).any():
   # Do something
else:
   # Carry on with the usual tasks

Could someone help me understand what is happening here? What is being checked? The documentation says,

Tests whether any array element along a given axis evaluates to True.

Is it being checked for equality? To understand this better, how could I rewrite the any call?

A: It's being checked for "True"ness.
Try this:
import numpy

print(numpy.any([0, 0, 0, 0, 0]))
print(numpy.any([0, 0, 0, 0, 1]))

A: np.any(x) checks if any of the elements in x is true. In your case, it checks if the arrays original and duplicate have at least a different dimension.
You could rewrite this as:
res = False
for so, sd in zip(original.shape, duplicate.shape):
    if so != sd:
        res = True

if res:
    # Do something
else:
   # Carry on with the usual tasks

A: The any method checks if at least on element in the given data is evaluated as True.
In python the following things are evaluated False:

*

*None

*False

*any numeric zero

*empty strings, sets, lists, dictionaries ...

*anything that has a __len__ method which returns 0 or a __bool__ method that returns False
Everything else is evaluated True.
If the data checked by the any method contains at least one item that does not meet these requirements, it returns True else False


text:
Q: Calculus - limit of a function with logarithms Compute $$\lim_{x \to {0_+}} {\ln (x \ln a) \ln \left({{\ln (ax)}\over{\ln({x\over a})}}\right)}$$ where $a>1$
I am trying to get to a result withou using any advanced methods or even things such as l'Hospital's rule etc..
I got to a phase where I took the limit of the first logarithm which we can see tends to $0$ from rewriting it as $\ln a^x$. Then I wanted to make some adjustments to the second part of the expression and I got to the stage where I have the limit of $$(\ln a^2) \left({x-a\over a}\right)$$ That wont give me exact result but I should be able to justify that it the expression is defined and by multiplying it with the first limit which is $0$, the result should also be $0$.
Can somebody please tell me how correct or wrong I am? Thanks.

A: Let $b = \ln a, y = -\ln x$.  Then the limit in question is
\begin{align}
L & = \lim_{y \to \infty} (-y+\ln b) \ln\left(\frac{-y+b}{-y-b}\right) \\
  & = \lim_{y \to \infty} (-y+\ln b) \ln\left(\frac{y-b}{y+b}\right)
\end{align}
If this limit exists, then
\begin{align}
e^L & = \lim_{y \to \infty} \left(\frac{y-b}{y+b}\right)^{-y+\ln b} \\
    & = \lim_{y \to \infty} \left(1-\frac{2b}{y+b}\right)^{-y+\ln b} \\
    & = e^{2b}
\end{align}
So, $L = 2b = 2\ln a$.

A: Rewrite the expression as
$$\ln x\cdot\ln\Bigl(1+ \frac{\ln x}{\ln a}\Bigr)-\ln x\cdot\ln\Bigl(1-\frac{\ln x}{\ln a}\Bigr)=\frac{\ln\Bigl(1+ \cfrac{\ln a}{\ln x}\Bigr)}{\ln x}-\frac{\ln\Bigl(1-\cfrac{\ln a}{\ln x}\Bigr)}{\ln x}$$
Now a standard limit is $\;\displaystyle\lim_{u\to 0}\frac{\ln(1+cu)}u=c$, hence
$$\lim_{x\to 0^+}{\ln (x \ln a)\ln \biggl({{\ln (ax)}\over{\ln({x\over a})}}\biggr)}=2\ln a.$$


text:
Q: Save the result of a JSONP callback to an outer object after few days to break my mind and trying to solve my issue myself, I've decided to ask some help. Here is my code :
// -----------
// Global object
// -----------
window.myObj = window.myObj || {};
function getLocation(myObj) {
    // Location test
    // -- Mobile connection test/fix
    // -- First step => Ask on client IP
    $.getJSON( "//freegeoip.net/json/?callback=?", function(data) {
        console.warn('Fetching Accurate JSON data...');
        if (data.city !== '') {
            // Log output to console
            console.info('Location found from client ip');
            console.info(JSON.stringify(data, null, 2));
            // myObj = data;
            // myObj.toString = function(data) {
            //  return JSON.stringify(data, null, 2);
            // }
        } else {
            // -- Second step => Ask on server IP using server name
            $.getJSON( "//freegeoip.net/json/" + window.location.host + "?callback=?", function(data) {
                // Log output to console
                console.info('Location found from server ip');
                console.info(JSON.stringify(data, null, 2));
                // myObj = data;
                // myObj.toString = function(data) {
                //  return JSON.stringify(data, null, 2);
                // }
            });
        }
    });

    return myObj;
}
console.info(getLocation(myObj));

What I want, is to store the result of the JSONP callback to the outer object named myObj.
I've tried to create the function as a closure this way:
window.myObj = (function () {
    // Location test
    // -- Mobile connection test/fix
    // -- First step => Ask on client IP
    $.getJSON( "//freegeoip.net/json/?callback=?", function(data) {
        console.warn('Fetching Accurate JSON data...');
        if (data.city !== '') {
            // Log output to console
            console.info('Location found from client ip');
            return data;
        } else {
            // -- Second step => Ask on server IP using server name
            $.getJSON( "//freegeoip.net/json/" + window.location.host + "?callback=?", function(data) {
                // Log output to console
                console.info('Location found from server ip');
                return data;
            });
        }
    });
}());

but it returns undefined everytime... As you may see my javascript skills are not so good, as my English too.
I thank you all in advance for your help.

A: So... I've found the solution by myself after a lot of study regarding Javascript language. Here is how I've managed my issue:
// -----------
// Global JS Object
// -----------
var myObj = myObj || {};

// Dependency
// Object size count function. Thanks to:
// http://stackoverflow.com/a/24457767
myObj.objSize = function(obj) {
    var count = 0;
    var key;

    if (typeof obj == "object") {
        if (Object.keys) {
            count = Object.keys(obj).length;
        } else if (window._) {
            count = _.keys(obj).length;
        } else if (window.$) {
            count = $.map(obj, function() { return 1; }).length;
        } else {
            for (key in obj) if (obj.hasOwnProperty(key)) count++;
        }
    }

    return count;
}

// Setter method
myObj.setUserDetails = function(data) {
    this.user = {};
    this.user.details = data;
    this.user.location = {lat: data.latitude, lng: data.longitude};
    this.user.location.toString = function() {
        // Returns data as same format as Google use...
        return '(' + this.user.location.lat + ', ' + this.user.location.lng + ')';
    }.bind(this);
}

// Getter method
myObj.getUserDetails = function() {
    var _this = this;

    // -- Mobile connection test/fix
    var valid_region_codes = ['GE', 'BE', 'FR', 'VD', 'VS', 'NE', 'JU'];

    // Checking if you we've not already some user data
    if (typeof _this.user !== 'object') {
        // -- First step => Ask on client IP
        $.getJSON( "//freegeoip.net/json/?callback=?", function(first_fetch) {
            console.warn('Fetching Accurate JSON data...');
            if (first_fetch.region_code === '') {
                // -- Empty 'region_code' => Ask on server IP using server name
                $.getJSON( "//freegeoip.net/json/" + window.location.host + "?callback=?", function(second_fetch) {
                    // Log output to console
                    console.info('Fetch: 2');
                    console.info('Location based on server ip');
                    console.info(JSON.stringify(second_fetch, null, 2));
                    console.info(this); console.info(_this);
                    _this.setUserDetails(second_fetch);
                });
            } else {
                // -- Have 'region_code', let's proceed...
                if (valid_region_codes.indexOf(first_fetch.region_code) !== -1) {
                    // Checked 'region_code'... Valid, using client IP
                    console.info('Fetch: 1');
                    console.info('Location based on client ip');
                    console.info(JSON.stringify(first_fetch, null, 2));
                    console.info(this); console.info(_this);
                    _this.setUserDetails(first_fetch);
                } else {
                    // Checked 'region_code'... not valid, falling back to server IP
                    $.getJSON( "//freegeoip.net/json/" + window.location.host + "?callback=?", function(third_fetch) {
                        // Log output to console
                        console.info('Fetch: 3');
                        console.info('Location based on server ip');
                        console.info(JSON.stringify(third_fetch, null, 2));
                        console.info(this); console.info(_this);
                        _this.setUserDetails(third_fetch);
                    });
                }
            }
        });
    } else {
        console.warn('Using previously fetched user data...');
    }
}

// The Holy Grail method (^_^)
myObj.waitForProps = function(prop, type, timer, callback) {
    var check = setInterval(function() {
        var evil = eval(prop), evilSize = masalle.objSize(evil);
        console.info('Checking [prop] as: ' + prop + '\nTo type: ' + type +
                     '\nEach: ' + timer + 'ms\nThen exec callback:\n\t\t\t' + callback);
        if (typeof evil === type) {
            console.info('[' + prop + '] found, checking size...');
            if (evilSize > 0) {
                console.info('[' + prop + '] size: ' + evilSize);
                clearInterval(check);
                if (callback && typeof callback === 'function') {
                    callback();
                }
            }
        }
    }, timer);
}

Explanations
First, I'm calling the getter method myObj.getUserDetails() which use the setter method myObj.setUserDetails() to insert the content of the JSONP request into an object named myObj.user
Then, I'm calling my magic method (which is like a waiting method) to check the existence of the object myObj.user
If it's already available, I'm using it and execute the specified callback OR I'm iterating a wait timer based on the specified duration till the requested object became available then it executes the callback
Usage
// Grab the user location
myObj.getUserDetails();

// Wait the time the required object to be created / filed
myObj.waitForProps('myObj.user', 'object', 600, function() {
    // Execute what you need there
});

I hope this could be useful for someone. Feel free to contact me if you know a better (and faster) way to do the same thing.

Known issues:
I know I've used the evil eval function in my magic method which
  could led to some security issues. I hope I've used it correctly, if
  not, please correct my code.
If you're using the method myObj.waitForProps() in a
  ReactJS project, you'll see that the specified duration is not respected
  and the method iterates as fast as possible till your requested object
  is available. Let me know if you have a tips to this issue, maybe my
  code is just working wrong...


text:
Q: MethodAccessException when connecting to Oracle When I am trying to connect to the db(Oracle 11), I have an exception MethodAccessException.
System.MethodAccessException was unhandled by user code
  Message=Методу "e4.a(Int32)", прозрачному для безопасности, не удалось получить доступ к критически важному методу безопасности "System.Threading.Thread.Abort()".
  StackTrace:
       в e4.a(Int32 A_0)
       в e4.a(Int32 A_0, String A_1, Int32 A_2)
       в lx.a(String A_0, String A_1, String A_2, String A_3)
       в fs.b(em A_0, Boolean A_1)
       в fs.jh(em A_0, o9 A_1)
       в nl..ctor(em A_0, nl A_1)
       в el.h5(cg A_0, Object A_1, DbConnectionBase A_2)
       в sz.a(or A_0, cg A_1, DbConnectionBase A_2)
       в ny.a(or A_0, DbConnectionBase A_1)
       в or.a(DbConnectionBase A_0)
       в or.b(DbConnectionBase A_0)
       в sz.c(DbConnectionBase A_0)
       в am.ba(DbConnectionBase A_0)
       в Devart.Common.DbConnectionBase.Open()
       в Devart.Data.Oracle.OracleConnection.Open()
       в Devart.Data.Oracle.Linq.Provider.OracleDataProvider.Initialize(Object connection)
       в Devart.Data.Linq.DataProvider.Devart.Data.Linq.Engine.IProvider.Initialize(IDataServices dataServices, Object connection)
       в Devart.Data.Linq.DataContext.a(Object A_0, MappingSource A_1, Type A_2)
       в Devart.Data.Linq.DataContext..ctor(String connectionString, MappingSource mapping)
       в ITContext.ITDataContext..ctor()
       в SLWP.MainPage.Button_Click_1(Object sender, RoutedEventArgs e)
       в System.Windows.Controls.Primitives.ButtonBase.OnClick()
       в System.Windows.Controls.Button.OnClick()
       в System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
       в System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
       в MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName, UInt32 flags)

I'm making the web part for sharepoint 2010, using linqconnect for oracle. I read that the problem is solved by attribute [assembly: AllowPartiallyTrustedCallers], but that attribute is missing for silverlight. How do I solve this?


text:
Q: How to repeat audio in Java? This is all i have so far. But im not sure if this is the best way to play an audio file, and I also want to know how to repeat an audio file. Any advice?
package ponggame;

import java.applet.Applet;

import java.applet.AudioClip;

public class Sound {

    public static final Sound bgMusic = new Sound("/pong.wav");
    public static final Sound hitPaddle = new Sound("/bounce.wav");

    private AudioClip clip;

    public Sound(String fileName) {
        try {
            // gets the sound file that is passed in the constructor
            clip = Applet.newAudioClip(Sound.class.getResource(fileName));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // plays the music, obviously
    public void play() {
        try {
            new Thread() { //multi-tasking stuff
                public void run(){
                        clip.play();

                }
            }.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

A:
im not sure if this is the best way to play an audio

Yup, you're doing it right, presuming this is for an applet. Also, given that you are uncertain of the use of AudioClip, your abstraction of it behind a Sound is a good use of abstraction -- although you do not need to start the audio on a separate thread, unless you find the latency in play start time unacceptable (play() will return immediately and the clip will play asynchronously).

and also want to know how to repeat an audio.

See AudioClip.loop(). It will start looping the audio when you call it, until you call stop().

A: Have a look at the code I made to do this:
import java.net.URL;

import javax.sound.sampled.*;
/**
 * This class is designed to take the filename of a .wav
 * inside of the com.Game package and turn it into a Clip with a playClip()
 * method
 * @author michaelsnowden
 *
 */
public class Audio
{
    URL url;
    Clip clip;
    AudioInputStream ais;

    public Audio(String st)
    {
        clip = null;

        try{
            AudioInputStream audioIn = AudioSystem.getAudioInputStream( getClass().getResource(st));
            clip = AudioSystem.getClip();
            clip.open(audioIn);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    public void playClip()
    {
        if( clip.isRunning() )
        {
            clip.stop();
        }
        clip.setFramePosition( 0 );
        clip.start();
    }
}

It's honestly not that much different than what you're doing, but it's just more efficient, and the methods you want are built in.
Put this class into your package, and then put the .wav files into your package also. Just drag and drop them. Then, in your Applet, just instantiate objects of this class with the name of your .wav file as a string. For example, Audio catMeow = new Audio("loud_meow.wav"). Then, later on, catMeow.playClip();

A: If you just mean play the audio more than once, you could use a while or for loop that calls your play() method. Here is an example of both:
    for(int i = 5; i > 0; i--) {   //For loops work like this: int i = 5 (declare the
          play();//temporary variable); i > 0 (the condition, so as long as i is
                //larger than 0, the loop will execute); i-- (what to do after each iteration of the loop).
    }

int j = 5;
while(j > 0) {
      play();
      j--;
}

In each case, the sound should play five times.
AudioClip.loop(); also works.


text:
Q: How to add numeric value to value without adding or subtracting it in php I would like to post a value to my MySQL database in this format;
01, 02, 03...
011, 012, 013...
0101, 0102, 0103,
etc.
(with a 0 before each value).
If I do it like this "01+1" I (understandable) get the value 2 and not "02".
is there a default php function that let's me set the default amount of characters or is there an other option?
I'm using laravel combined with eloquent and some own functions like so;
$lastSKU = $data->GetData('get', 'products', 'filter')->max('SKU');
$newValue = $lastSKU+1;

Thanks in advance.

A: It sounds like you won't know how the format will be, if there is always a 0 in front it is easy enough to do
$value = '0'. ( $value + 1 );

PHP will automatically convert it to a number between the brackets and by adding a string to it it will become a string again.
Now if you do not know the the length or the padding in advance but you do need to keep the current padding I would suggest something like
$value = str_pad(($value + 1), strlen($value), '0', STR_PAD_LEFT);

Edit, str_pad is a bit slow these days, sprintf can do the same trick but much faster
$value = sprintf("%'.0" . strlen($value) . "d\n", ($value +1));


text:
Q: ember-cordova - Invalid or unexpected token on __dirname I'm trying to build Android app using my Ember frontend and Cordova.

*

*I've configured project as described in ember-cordova docs (changed rootURL and locationType),

*I installed ember-cordova via ember install ember-cordova,

*Changed app name and widget id in cordova/config.xml,

*Added required platform - ember cdv:platform add android,

*And I'm trying to build first version of my app using ember cdv:build --platform=android --environment=production.

Unfortunatelly, build fails with error:
EmberCordovaError: Invalid or unexpected token

Stack Trace and Error Report: /tmp/error.dump.0bfefb855ac286c6b6600c600e92d126.log

It happens both on Ubuntu 21.10 and macOS Monterey. I'm using node v12.22.7 installed via node version manager (tried using node from apt packages on Ubuntu, but it didn't help), ember-cordova v1.0.9, and ember v3.12.1.
Full error log:
=================================================================================

ENV Summary:

  TIME: Fri Dec 03 2021 12:37:28 GMT+0100 (GMT+01:00)
  TITLE: ember
  ARGV:
  - /home/tomasz/.nvm/versions/node/v12.22.7/bin/node
  - /home/tomasz/.nvm/versions/node/v12.22.7/bin/ember
  - cdv:build
  - --platform=android
  - --environment=production
  EXEC_PATH: /home/tomasz/.nvm/versions/node/v12.22.7/bin/node
  TMPDIR: /tmp
  SHELL: /bin/bash
  PATH:
  - /home/tomasz/.rvm/gems/ruby-3.0.3/bin
  - /home/tomasz/.rvm/gems/ruby-3.0.3@global/bin
  - /home/tomasz/.rvm/rubies/ruby-3.0.3/bin
  - /home/tomasz/.rvm/bin
  - /home/tomasz/.local/bin
  - /home/tomasz/bin
  - /home/tomasz/.nvm/versions/node/v12.22.7/bin
  - /home/tomasz/.local/bin
  - /home/tomasz/bin
  - /usr/local/sbin
  - /usr/local/bin
  - /usr/sbin
  - /usr/bin
  - /sbin
  - /bin
  - /usr/games
  - /usr/local/games
  - /snap/bin
  - /home/tomasz/.rvm/bin
  PLATFORM: linux x64
  FREEMEM: 18971971584
  TOTALMEM: 33553645568
  UPTIME: 4862
  LOADAVG: 6.15,4.98,3.74
  CPUS:
  - Intel(R) Core(TM) i5-4670 CPU @ 3.40GHz - 3505
  - Intel(R) Core(TM) i5-4670 CPU @ 3.40GHz - 3565
  - Intel(R) Core(TM) i5-4670 CPU @ 3.40GHz - 3800
  - Intel(R) Core(TM) i5-4670 CPU @ 3.40GHz - 3800
  ENDIANNESS: LE
  VERSIONS:
  - ares: 1.17.2
  - brotli: 1.0.9
  - cldr: 37.0
  - http_parser: 2.9.4
  - icu: 67.1
  - llhttp: 2.1.4
  - modules: 72
  - napi: 8
  - nghttp2: 1.41.0
  - node: 12.22.7
  - openssl: 1.1.1l
  - tz: 2019c
  - unicode: 13.0
  - uv: 1.40.0
  - v8: 7.8.279.23-node.56
  - zlib: 1.2.11

ERROR Summary:

  - broccoliBuilderErrorStack: [undefined]
  - code: [undefined]
  - codeFrame: [undefined]
  - errorMessage: EmberCordovaError: Invalid or unexpected token
  - errorType: [undefined]
  - location:
    - column: [undefined]
    - file: [undefined]
    - line: [undefined]
  - message: EmberCordovaError: Invalid or unexpected token
  - name: EmberCordovaError
  - nodeAnnotation: [undefined]
  - nodeName: [undefined]
  - originalErrorMessage: [undefined]
  - stack: (function (exports, require, module, __filename, __dirname) { #!/usr/bin/env node
                                                              ^

SyntaxError: Invalid or unexpected token
    at new Script (vm.js:88:7)
    at createScript (vm.js:261:10)
    at Object.runInThisContext (vm.js:309:10)
    at wrapSafe (internal/modules/cjs/loader.js:902:15)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Api.getPlatformInfo (/home/tomasz/Projects/app-ember/ember-cordova/cordova/platforms/android/cordova/Api.js:174:22)
    at /home/tomasz/Projects/app-ember/node_modules/cordova-lib/src/cordova/prepare.js:53:67
    at Array.map (<anonymous>:null:null)
    at /home/tomasz/Projects/app-ember/node_modules/cordova-lib/src/cordova/prepare.js:51:43
    at _fulfilled (/home/tomasz/Projects/app-ember/node_modules/cordova-lib/node_modules/q/q.js:787:54)
    at /home/tomasz/Projects/app-ember/node_modules/cordova-lib/node_modules/q/q.js:816:30
    at Promise.promise.promiseDispatch (/home/tomasz/Projects/app-ember/node_modules/cordova-lib/node_modules/q/q.js:749:13)
    at /home/tomasz/Projects/app-ember/node_modules/cordova-lib/node_modules/q/q.js:557:44
    at flush (/home/tomasz/Projects/app-ember/node_modules/cordova-lib/node_modules/q/q.js:108:17)
    at processTicksAndRejections (internal/process/task_queues.js:79:11)

=================================================================================

What could be a reason of such a failure?


text:
Q: Expectation of a transformation of normal random variable X does not depend on the mean of X I want to know if there exist a function $g$ and $\mu \ne \mu'$ such that
$$ \int g(x)\phi(x;\mu)\,dx = \int g(x)\phi(x;\mu')\, dx$$
Where $\phi(x;\mu)$ is the pdf of normal random variable with mean $\mu$ and unit variance.
All I can find is that if $g$ is symmetric — $g(x) = g(-x)$, then the above condition holds.
Could there be other functions that satisfy the above equation?

A: There is such a function $g$. Take $g(x)=x-\frac 1{\mu+\mu'} x^{2}$. The case $\mu+\mu'=0$ is left to you.


text:
Q: PHP Deprecated: Non-static method RestrictAllowedPlugins::filter() should not be called statically in /wp-includes/class-wp-hook.php on line 292 using PHP 7.4.21, wordpress core5.7.2. Found the two pieces of code the deprecation warning mentions, but why is there an issue and how to fix it?
The issue is with this line of code in the below lines of code:
$value = call_user_func_array( $the_['function'], $args );

Here's the snippet from class-wp-hook.php on line 292....
// Avoid the array_slice() if possible.
if ( 0 == $the_['accepted_args'] ) {
    $value = call_user_func( $the_['function'] );
} elseif ( $the_['accepted_args'] >= $num_args ) {
    $value = call_user_func_array( $the_['function'], $args );
} else {
    $value = call_user_func_array( $the_['function'], array_slice( $args, 0, (int) $the_['accepted_args'] ) );
}

The RestrictAllowedPlugins plugin's filter function of issue is here:
if( !class_exists('RestrictAllowedPlugins') ) {
class RestrictAllowedPlugins {

function filter($plugins) {
    if( current_user_can( 'manage_network_plugins' ) ) // Disable restrictions for network admins
        return $plugins;

    $allowed_plugins = get_site_option( 'allowedplugins' );

    if( !is_array( $allowed_plugins ) )
        return $plugins;

    unset( $plugins[ plugin_basename(__FILE__) ] );

    foreach( array_keys($plugins) as $key ) {
        $plugin_key = str_replace( '/', ':', $key );
        if( !isset( $allowed_plugins[ $plugin_key ] ) )
            unset( $plugins[ $key ] );
    }

    return $plugins;
}

This is a filter with the callback:
add_filter( 'all_plugins', array('RestrictAllowedPlugins','filter') );


text:
Q: Unable to launch Android Emulator on Windows 11 pro I am trying to run an Android emulator on my Windows 11 pro pc that supports virtualization.
When running the following command:
"C:\Program Files (x86)\Android\android-sdk\emulator\emulator-check.exe" accel

I get this response:
accel:
0
Please disable Hyper-V before using the Android Emulator.  Start a command prompt as Administrator, run 'bcdedit /set hypervisorlaunchtype off', reboot.WHPX (10.0.22000) is installed and usable.
accel

So then I run 'bcdedit /set hypervisorlaunchtype off' I get the following response from the '"C:\Program Files (x86)\Android\android-sdk\emulator\emulator-check.exe" accel' command:
accel:
6
HAXM is not installed on this machine
accel

This message means that it can't find any acceleration on the machine! It's going round in circles and it's driving my crazy!
Things I have checked:
I have enabled Virtualization from the BIOS
Correct windows features enabled-

Uninstalled HAXM from Android SDK manager-

Correct advancedFeatures.ini file-

Any help would be much appreciated!

A: I had to update VS to the latest version to resolve this issue.


text:
Q: Changing SKPhysicsBody while changing SKSpriteNode position I've got quite simple game. It's like the classic Labyrinth game which uses accelereometer but user is also able to change the size of the rectangle using 3D Touch.
The player's node is rectangle which moves thanks to the world's physics which gets data from the accelerometer (nothing special here):
motionManager.startAccelerometerUpdates(to: OperationQueue.current!) { (data, error) in
    if let motionData = data{
        self.physicsWorld.gravity = CGVector(dx: motionData.acceleration.x * 7, dy: motionData.acceleration.y * 7)
    }
}

and touchesMoved :
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first{
            let maxForce = touch.maximumPossibleForce
            let force = touch.force

            let forceValue = force/maxForce

            player.size = CGSize(width: 26-forceValue*16, height: 26-forceValue*16)
            player.physicsBody = SKPhysicsBody(rectangleOf: player.size)
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    resetSize()
}

func resetSize(){
    player.size = CGSize(width: 26, height: 26)
}

So when I was changing player's size it worked fine: the node was moving around the screen based on device's orientation and while pressing harder it was getting smaller. The problem was that the physicsBody (I've set view.showsPhysics = true in GameViewController.swift) was always the same so I've added player.physicsBody = SKPhysicsBody(rectangleOf: player.size) but now when I'm pressing the screen the player's node resizes but it also stops moving. How to change the node's size and physicsBody simultaneously and keep it in motion?

A: When you change the physicsBody you lost all physics parameters that invoved your previous physicsBody: you can copy velocity or angularVelocity or other available parameters but it's not enough, you will never have a continuity because the SpriteKit framework (on the actual version) don't have this option: dynamically change the physicsBody during the game.
You can also change the scaling of you node to modify the physicsBody but you always lost physics variables as for example the accumulated speed due to gravity : this happened because SpriteKit change automatically the physicsBody during the scaling to create others bodies without preserve the accumulated properties.
So my advice is to create a kind of "freezing time" when you touch your ball, where you can change you physicsBody when the ball is stopped.


text:
Q: serial device output looks fine in gnu screen but garbled using cat I have a serial device (Omega RDXL4SD thermocouple reader, comms details p 22 here) connected to a USB port on my Raspberry Pi running Raspbian via an FTDI cable. It appears at /dev/ttyUSB0 and the output looks perfect if I display it by calling
pi@raspberrypi:~ $ screen /dev/ttyUSB0 9600
The output is a few numbers. Each time it spits out a line, the cursor returns to the beginning of the line and overwrites it, so that there is only ever one line of numbers on the screen at a time.
Now, I want to use cat, not screen to achieve the same effect, but when I do I get boxes with question marks in them:
pi@raspberrypi:~ $ cat /dev/ttyUSB0
4401010000

I presume this is some kind of encoding problem. Can you explain what might be different about how these characters are being interpreted in screen versus cat, or suggest other troubleshooting steps?
In case it helps:
pi@raspberrypi:~ $ uname -a
Linux raspberrypi 4.9.41-v7+ #1023 SMP Tue Aug 8 16:00:15 BST 2017 armv7l
GNU/Linux

pi@raspberrypi:~ $ stty -F /dev/ttyUSB0
speed 9600 baud; line = 0;
min = 100; time = 2;
-icrnl -imaxbel
-opost -onlcr
-isig -icanon -echo

Edit: @meuh suggested adding -vet to display special characters. Now that I know about those flags, my particular problem is effectively solved! I still wouldn't mind an explanation of exactly what's going on here though.
pi@raspberrypi:~ $ cat -vet /dev/ttyUSB0
^M^B4201010000^X^X^X^X^M^B4301010000^X^X^X^X^M^B4401010000^X^X^X^X^M^B41010100000245^M^B4201010000^X^X^X^X^M^B4301010000^X^X^X^X^M^B4401010000^X^X^X^X^M^B41010100000245^M^B4201010000^X^X^X^X^M^B4301010000^X^X^X^X^M^B4401010000^X^X^X^X^M^B41010100000245^M^B4201010000

A: Turns out the ^X characters, which are bytes of 0x18, are a sort of undocumented NaN in this protocol. There are multiple thermocouple ports, and if you only plug in one thermocouple you get one line with a temperature value and then a bunch of lines ending with ^X.
For some reason, cat in my terminal displays these characters as boxes but screen doesn't display them at all.


text:
Q: Ruby on Rails 4: options value in form_for helper I want to make a helper for the bootstrap, and for controls (text_field, label ...) I need to use the options of the form_for.
There is a form
<%= form_for(@user, url: signup_path, layout: :horizontal) do |user_f| %>
  <%= user_f.fields_for :person do |person_f| %>
    <%= person_f.text_field(:last_name) %>
    <%= person_f.options %>
  <% end %>
  <%= user_f.text_field(:last_name) %>
  <%= user_f.options %>
<% end %>

I need to get the value :layout in the control from the form_for
I do not understand why <%= user_f.options %> displays:
{:url=>"/signup?locale=ru", :layout=>:horizontal, :html=>{:class=>"new_user", :id=>"new_user", :method=>:post, :authenticity_token=>nil}}

And <%= person_f.options %> displays:
{:builder=>nil, :namespace=>nil, :parent_builder=>#<ActionView::Helpers::FormBuilder:0x007fd338058c60 @nested_child_index={}, @options={:url=>"/signup?locale=ru", :layout=>:horizontal, :html=>{:class=>"new_user", :id=>"new_user", :method=>:post, :authenticity_token=>nil}}, @template=#<#<Class:0x007fd338030738>:0x007fd3375e2268 @_routes=nil, @_config={}, @view_renderer=#<ActionView::Renderer:0x007fd3375e2510 @lookup_context=#<ActionView::LookupContext:0x007fd3375d31a0 @details_key=#<ActionView::LookupContext::DetailsKey:0x007fd3371da5f8 @hash=-3796700121417373084>, @details={:locale=>[:ru], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder]}, @skip_default_locale=false, @cache=true, @prefixes=["signup", "application"], @rendered_format=:html, @view_paths=#<ActionView::PathSet:0x007fd3375d3970 @paths=[#<ActionView::OptimizedFileSystemResolver:0x007fd33720f3e8 @pattern=":prefix/:action{.:locale,}{.:formats,}{.:handlers,}", @cache=#<ActionView::Resolver::Cache:0x007fd33720f3c0 @data=#<ActionView::Resolver::Cache::SmallCache:0x007fd33720f398 @backend={#<ActionView::LookupContext::DetailsKey:0x007fd3371da5f8 @hash=-3796700121417373084>=>#<ActionView::Resolver::Cache::SmallCache:0x007fd3371d9810 @backend={"new"=>#<ActionView::Resolver::Cache::SmallCache:0x007fd3371d96d0 @backend={"signup"=>#<ActionView::Resolver::Cache::SmallCache:0x007fd3371d9540 @backend={false=>#<ActionView::Resolver::Cache::SmallCache:0x007fd3371d9450 @backend={[]=>[app/views/signup/new.html.erb]}, @default_proc=nil>}, @default_proc=#<Proc:0x007fd33438afe0@/Users/NikolayLipovtsev/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.2/lib/action_view/template/resolver.rb:45 (lambda)>>}, @default_proc=#<Proc:0x007fd33438afb8@/Users/NikolayLipovtsev/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.2/lib/action_view/template/resolver.rb:46 (lambda)>>,

...and there is more still large hash.
How I can get :layout from person_f and user_f?


text:
Q: Proving $X$ is compact using a function $f\colon X \to Y$? Let's suppose I have a topological space $X$, for which I am trying to prove its compactness. If I construct a function $f: X \to Y$ to another topological space $Y$, what are some examples of conditions on $f$ and $Y$ that could guarantee that $X$ is compact?
E.g. if $f$ is open and injective, and $f(X)$ is compact, then $X$ is compact [1]. One could prove the compactness of $f(X)$ by showing $Y$ is compact and $f(X) \subseteq Y$ is closed.
Does assuming that either $X$ or $Y$ are Hausdorff / metrisable help?
[1] This seems dual to the theorem that continuous images of compact spaces are compact.

A: The other way round is easier: if we can have a continuous $f: Y \to X$ that is onto and continuous and $Y$ is compact then so is $X$. E.g. that's why the image of a path is always compact.
For your case $f: X \to Y$ we could use $f$ perfect: continuous, closed, onto and all fibres compact (so all sets of the form $f^{-1}[\{y\}]$ are compact); then $Y$ compact implies $X$ is too. This can be used to see that $X \times Y$ is compact whenever $X$ and $Y$ are (using the projection maps).


text:
Q: Vue: Don't close dialog on invalid login I'm a complete beginner to Vue and I have an extremely basic question that is tripping me up.
I have a Dialog that opens up and asks for user input. When the user clicks okay, it makes a call to an API and tries to add the user input to a database. This works fine and I'm able to successfully hit the database. The issue I'm having is if the API doesn't return a 200. I want to persist the dialog and add text that says "Invalid Input. Try again." However, everything I've tried just closes the dialog automatically.
The code I have looks like:
           <v-dialog v-model="show" width="500">
              <template v-slot:activator="{ on, attrs }">
                <v-btn text color="green" v-bind="attrs" v-on="on"> Add User </v-btn>
              </template>
              <v-card>
                <v-card-title class="text-h5 grey lighten-2"> Add User </v-card-title>
                <v-spacer></v-spacer>
                <v-card-text>
                  <v-text-field label="User to add" v-model="addUser"></v-text-field>
                </v-card-text>

                <v-spacer></v-spacer>
                <v-divider></v-divider>
                <v-card-actions>
                  <v-spacer></v-spacer>
                  <v-btn
                    color="primary"
                    text
                    @click="
                      show = false
                      addUser(index)
                    "
                  >
                    Add
                  </v-btn>
                </v-card-actions>
              </v-card>
            </v-dialog>

How do I persist a dialog conditionally such that it stays open if addUser returns False and otherwise closes normally?


text:
Q: Is there any way to check the security setting of a Chrome browser? I want to access some code from an http:// source from an https:// website. I have a popup that prompts  the user to change their security setting but I don't want the popup to show every time I go to the homepage of the site. Is there any way to check their Google Chrome browser settings to indicate if they already enabled the insecure elements to show?
Currently I have:
function alertLoadData() {
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    var secure = isSecure();
    if (is_chrome && secure) {
    alert('Please click on the shield to the right of the address bar to show the contents of the site. NOTE: the contents come from an insecure http:// address.');
    }
}

Where isSecure() checks that they are in the https:// part of the website. I want something like: alreadyEnabledSecurity() which checks whether the user has already enabled the insecure contents to show and if so:
function alertLoadData() {
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    var secure = isSecure();
    var settings = alreadyEnabledSecurity();
    if (is_chrome && secure && !settings) {
    alert('Please click on the shield to the right of the address bar to show the contents of the site. NOTE: the contents come from an insecure http:// address.');
    }
}


text:
Q: jqGrid - jsonString datatype - Displaying nested json element values All,
I'm having a JSON object which is being returned from a webservice. I'm using the Stringify method to convert it to a string object.
While I try to integrate this with my jqGrid, (using datatype:'jsonstring', datastr:myJSONstringobject). I'm able to map the JSON columns with the grid if it is straightforward (ie. 'index:customerName')
But if it is a nested JSON value (ie 'index:customer.customerAddress.street'), it is not getting loaded in the grid.
Can someone help?.
Thanks in advance!

A: If I understand your question correct you should use jsonmap property of column which contains dots (like jsonmap: customer.customerAddress.street) instead of index. If you use datatype: 'jsonstring' you should use name and index parameters with the same value which don't contains dots, spaces or any other meta-characters. Probably you can reduce the need to use jsonmap if you define jsonReader which corresponds your data. Because you don't posted the example of your JSON data I can't explain you more.
Mostly in case of the usage of webservices your don't need to use datatype: 'jsonstring'. Instead of that the usage of datatype: 'json' with some additional parameters would be better.

A: If you have nested JSON and you would like to display row data that it is in one of the children notes, you just use, for example if you have data for the "jqGrid" in the the "Data" node:
        jsonReader: {
            root: "data.rows",
            page: "data.page",
            total: "data.total",
            records: "data.records"
        }

Note: this is valid 100% on jqGrid version 4.4.4


text:
Q: Altium Varied Polygon Connections I want to change the connection rules for a few polygons in my board. for experimentation purposes I set the default rule to have direct connects on all polygons. Then created a second rule with higher priority that used thermal relief connect for that named polygon.

In the end I plan on making either a class or just adding an 'OR' clause for the other polygons.
But to get to my question is that the polygon named TOP_GND_LEFT still has direct connects even after a repour.
I though maybe pour order but this poly is not on top of another?
Any suggestions?

A: You need to use the term "IsNamedPolygon" not "InNamedPolygon" which is what i was using above.


text:
Q: SQL Server - After Insert/ For Insert - Rollback I have the below trigger:
  CREATE Trigger instructor_expertise on CourseSections
     After Insert
     As Begin
     ......

     If (Not Exists(Select AreaName From AreasOfInstructor Where (InstructorNo = @InstructorNo AND AreaName = @AreaName)))
     Begin
     RAISERROR('Course not in instructors expertise', 16, 1)
     rollback transaction
     End
     GO

My question is, does 'rollback transaction' remove the row?
What if it's 'For Insert' instead, does 'rollback transaction' remove the row in that case?
Thanks!!!

A: Your INSERT statement always runs in a transaction - either you've explicitly defined one, or if not, then SQL Server will use an implicit transaction.
You're inserting one (or multiple) row into your table. Then - still inside the transaction - the AFTER INSERT trigger runs and checks certain conditions - typically using the Inserted pseudo table available inside the trigger, which contains the rows that have been inserted.
If you call ROLLBACK TRANSACTION in your trigger, then yes - your transaction, with everything it's been doing, is rolled back and it's as if that INSERT never happened - nothing shows up in your database table.
Also: FOR INSERT is the same as AFTER INSERT in SQL Server - the trigger is executed after the INSERT statement has done its job.
One thing to keep in mind (which a lot of programmers get wrong): the trigger is fired once per statement - NOT once per row! So if you insert 20 rows at once, the trigger is fired once and the Inserted pseudo table inside the trigger contains 20 rows. You need to take that into account when writing the trigger - you're not always dealing with just a single row being inserted!

A: no it is not possible because when their is no row exist then it will go in begin block ...


text:
Q: Migrate GitHub repo files to Azure DevOps Wikis from different project I have a repository in GitHub and have a bunch of documentation(.md) files there.
I want to migrate the documentations into one of the Azure DevOps Wikis.
I am referring this link.
When I am using the option Publish code as Wiki,it only shows the repositories which are available inside the Azure DevOps project.
Is there a way I can publish the GitHub documentations in repositories which are from another project into the Azure DevOps Wikis?

A: Consider approaching this differently. If you are using git for your Azure DevOps project, then the Azure DevOps Wiki should be persisted to a hidden, but locatable, git repository. Git clone the source and target repositories locally. Then copy what you want to the target (Azure DevOps Wiki, local clone). Git add, commit, and push the added target files.
Attached images/files, if any, may be more problematic depending on how exactly they are represented in the source GitHub repo. In Azure DevOps Wiki ALL attachments are simply stored in a root .attachments folder. So, you'll need to migrate them there and "fix up" your links.
I've done this going the other direction, Azure DevOps Wiki -> GitHub Enterprise repo. You should know that you'll likely need to "fix up" page links and that the two markdown styles have slight variations you may have to address.

A:
Is there a way I can publish the GitHub documentations into the Azure DevOps Wikis?

*

*for copying documents from GitHub you need to use Import repository from your devops project.

how to import an existing Git repo from GitHub, Bitbucket, GitLab, or other location into a new or empty existing repo in your Azure DevOps project.

*

*For complete information you can go through the Import Git repo link.


text:
Q: Loading New Document Versions Can we select an existing document and load a new version rather than just loading a document with the same name and advising to replace the current document?
I am concerned that new versions of existing doc's won't be picked up if the filename is slightly different; to avoid this we would rather select an existing doc and choose to upload a new version.


text:
Q: VSTS Database Edition Schema Comparison We use VSTS Database Edition to version control our database schemas. I like the idea of how it is supposed to work but have a big issue with the Schema Comparison feature. I like to use it for my deployments to see what has changed in the project vs a target database. Unfortunately, it shows many changes for objects that have not been changed. That happens even if I do it immidiately after re-creating a db project from the database.
The differences it finds are mostly white space. Some are caused by a different representation of the same thing, for example default constraints, "DEFAULT ((0))" vs "DEFAULT (0)". While I can go ahead and deploy the changes anyway and it does not cause any problems, it is definitely not ideal because it is hard to find actual changes when at least 50% of all objects are shown as modified. Is there any way to make this work better?

A: I keep hoping VSTS Database Edition will get more reliable. In the meantime, I still trust and use redgate's SQL Compare to diff databases. You can tell it how you want it to treat white space, comments, etc. on a very granular level.
I have been using SQL Compare around 5 years and it has always been very reliable. I have automated build scripts that use the SQL Compare engine APIs to diff our production and dev database and generate change scripts automatically.
PS. I am not affiliated with redgate. I am just stating my opinion based on my experience. Also, there is nothing wrong with rooting for the little guy.

A: The solution to this was upgrading to the Database Edition GDR R2 release, which was suggested by Mitch Wheat in his comment. I was using the standard version that came with VS2008 before. GDR release appears to have some nice usability features and it fixed all my problems with the Schema Comparison.
General info on VSTS Database Edition GDR: http://msdn.microsoft.com/en-us/magazine/dd483214.aspx.
Latest version download is here.


text:
Q: How to limit load of Array depending on switch position I load my annotations from plist and loop categories
NSMutableArray *annotations = [[NSMutableArray alloc]init];

NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];

for(path in dict){

NSString *theCategory;

theCategory = [NSString stringWithFormat:@"%@", path];
NSLog(@"%@", path);

NSArray *ann = [dict objectForKey:theCategory];

for(int i = 0; i < [ann count]; i++) {

    NSString *coordinates = [[ann objectAtIndex:i] objectForKey:@"Coordinates"];

    double realLatitude = [[[coordinates componentsSeparatedByString:@","] objectAtIndex:1] doubleValue];
    double realLongitude = [[[coordinates componentsSeparatedByString:@","] objectAtIndex:0] doubleValue];

    MyAnnotation *myAnnotation = [[MyAnnotation alloc] init];
    CLLocationCoordinate2D theCoordinate;
    theCoordinate.latitude = realLatitude;
    theCoordinate.longitude = realLongitude;

    myAnnotation.coordinate=CLLocationCoordinate2DMake(realLatitude,realLongitude);
    myAnnotation.title = [[ann objectAtIndex:i] objectForKey:@"Name"];
    myAnnotation.subtitle = [[ann objectAtIndex:i] objectForKey:@"Address"];
    myAnnotation.icon = [[ann objectAtIndex:0] objectForKey:@"Icon"];

    [mapView addAnnotation:myAnnotation];
    [annotations addObject:myAnnotation];

}

}

Then I have an switch in my settings
- (IBAction)saveSwitch:(id)sender
{
    NSUserDefaults *defs1 = [NSUserDefaults standardUserDefaults];
    [defs1 setBool: blackSwitch.on forKey: @"blackKey"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

I need to limit display of annotations from specific category by this switch. How it can be done, if I loop categories?

A: Inside your first loop, do this:
for(NSString *category in dict){
    if ([category isEqualToString:@"Whatever"]) {
        //continue?
        NSArray *ann = [dict objectForKey:category];
        BOOL blackKeyStatus = [[NSUserDefaults standardUserDefaults]boolForKey:@"blackKey"];

        if (blackKeyStatus) {
            //switch ON
            //act appropriatelyForOnValue
            //begin Loop 2 here?
        } else {
            //switch OFF
            //act appropriately
        }

    } else {
        //do something else?
    }

If you're needing to test for a specific condition, do whatever is necessary to identify if that condition is met.


text:
Q: How to set Json PropertyNamingStrategy on Controller Response time I have a REST controller that returns an Object. I want to set the PropertyNamingStrategy at the time of controller action response. For instance, based on who calls this controller, I wanna respond by sending a Camel case naming convention, and in another case return a Snake case naming style. I can use an object mapper in my controller action but that only returns a String type. I still want my Object type but with different naming convention. Any suggestions?
I'm using Springboot 2.x.

A: I figured out how to solve this problem. I extended the naming strategy like:
 public class GetSnakeCaseSetCamelCaseNamingStrategy
    extends PropertyNamingStrategy.PropertyNamingStrategyBase {

  @Override
  public String translate(String propertyName) {
    return propertyName;
  }

  @Override
  public String nameForGetterMethod(
      MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
    return PropertyNamingStrategy.SNAKE_CASE.nameForGetterMethod(config, method, defaultName);
  }

  @Override
  public String nameForSetterMethod(
      MapperConfig<?> config, AnnotatedMethod method, String defaultName) {

    return PropertyNamingStrategy.UPPER_CAMEL_CASE.nameForSetterMethod(config, method, defaultName);
  }
}

Then annotated my Pojo with my own naming strategy and it worked!

A: If your rest controller returns a POJO and that POJO needs to be converted to JSON with different naming strategy eg SNAKE_CASE for a given type of user and CAMEL_CASE for other type of user based on your requirement, then you need to create your own HttpMessageConverter and register it with Spring.

*

*Your Custom HttpMessageConverter looks like this:-

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.exc.InvalidDefinitionException;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.util.TypeUtils;

import java.io.IOException;
import java.lang.reflect.Type;

class CustomJackson2HttpMessageConverter
        extends MappingJackson2HttpMessageConverter {

    private static final ObjectMapper snakeCaseObjectMapper = new ObjectMapper()
            .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

    ObjectMapper defaultObjectMapper = new ObjectMapper();

    @Override
    protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        MediaType contentType = outputMessage.getHeaders().getContentType();
        JsonEncoding encoding = getJsonEncoding(contentType);
        //Note:- Get the appropriate ObjectMapper and use them to write Object to Json string accordingly
        ObjectMapper objectMapper = getObjectMapper(outputMessage);
        JsonGenerator generator = objectMapper.getFactory().createGenerator(outputMessage.getBody(), encoding);
        try {
            writePrefix(generator, object);

            Class<?> serializationView = null;
            FilterProvider filters = null;
            Object value = object;
            JavaType javaType = null;
            if (object instanceof MappingJacksonValue) {
                MappingJacksonValue container = (MappingJacksonValue) object;
                value = container.getValue();
                serializationView = container.getSerializationView();
                filters = container.getFilters();
            }
            if (type != null && TypeUtils.isAssignable(type, value.getClass())) {
                javaType = getJavaType(type, null);
            }
            ObjectWriter objectWriter;
            if (serializationView != null) {
                objectWriter = objectMapper.writerWithView(serializationView);
            } else if (filters != null) {
                objectWriter = objectMapper.writer(filters);
            } else {
                objectWriter = objectMapper.writer();
            }
            if (javaType != null && javaType.isContainerType()) {
                objectWriter = objectWriter.forType(javaType);
            }
            SerializationConfig config = objectWriter.getConfig();
            if (contentType != null && contentType.isCompatibleWith(MediaType.TEXT_EVENT_STREAM) &&
                    config.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
                objectWriter = objectWriter.with(this.ssePrettyPrinter);
            }
            objectWriter.writeValue(generator, value);

            writeSuffix(generator, object);
            generator.flush();

        } catch (InvalidDefinitionException ex) {
            throw new HttpMessageConversionException("Type definition error: " + ex.getType(), ex);
        } catch (JsonProcessingException ex) {
            throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getOriginalMessage(), ex);
        }
    }

    ObjectMapper getObjectMapper(HttpOutputMessage outputMessage) {
        HttpHeaders responseHeaders = outputMessage.getHeaders();
        /** TODO:- Check in responseHeaders if it is a specific user demanding
         * response with PropertyNamingStrategy as PropertyNamingStrategy.SNAKE_CASE
         * For eg:- you can have a header with name- jsonNamingStrategy=SNAKE_CASE or any default value or empty
         * Based on jsonNamingStrategy you can decide if user wants response in SnakeCase or default one
         * Return appropriately based on your check. For now returning snakeCaseObjectMapper
         **/
        return snakeCaseObjectMapper;
    }
}

*And you need to register your CustomJackson2HttpMessageConverter with Spring as:-

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@EnableWebMvc
@Configuration
class WebConfig implements WebMvcConfigurer {

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        final MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter = new CustomJackson2HttpMessageConverter();
        //Replace the default MappingJackson2HttpMessageConverter with the CustomJackson2HttpMessageConverter
        converters.replaceAll(it -> it instanceof MappingJackson2HttpMessageConverter ? customJackson2HttpMessageConverter : it);
        if (!converters.contains(customJackson2HttpMessageConverter)) {
            converters.add(customJackson2HttpMessageConverter);
        }
    }
}

*Similarly if you want to handle the scenario where you want to parse JSON with different naming strategy to POJO, then you can override method readInternal() of the CustomJackson2HttpMessageConverter.


text:
Q: A question about Comparatives As I understand it, comparatives compare with something. But which of the following sentences is correct.

*

*It wasn't busy tonight at the club? can you say next week will be busier?

*It wasn't busy tonight at the club? can you say next week will be busy?

Both are correct right?

A: Yes, I would say that both are correct. In #1, you're asking whether the club will be busier than not busy at all. In #2, you're asking if the club will be busy, as opposed to not busy. I think they come down to the same thing, and neither is incorrect.


text:
Q: How can entropy always be increasing, while each microstate (among which low-entropy micro states) is equally likely to occur? The reasoning in my statistical physics book is as follows:
$\cdot$ The basic postulate of Statistical Mechanics is that for a system with a fixed energy, particle number and volume, each microstate is equally likely to occur.
$\cdot$ For a certain physical quantity A, the entropy (and multiplicity) will have a maximum at A* of A.
$\cdot$ Starting at A different from A*, the system will explore other available states and automatically end up in configurations with the value A*, because a large majority of microstates has a value for A very near A* due to the high multiplicity at A*.
$\cdot$ Conclusion is that a system starting in A will always end up in a state where S has its maximum (at A*)/the entropy always increases if we leave a system alone.
I do not understand that, when the system explores all available states and when every microstate is equally likely to occur, that the entropy necessarily increases all the time. Isn't there a small chance that the system will end up in a state with significantly lower entropy and that it immediately gets in to a high entropy state again after?

A: Firstly, great question.
You are correct in saying that the law is inherently probabilistic. Every outcome is equally likely, but there are vastly more states of disorder than there are of order. In terms of coarse-graining regions, the states representing disordered outcomes are much larger than those representing order. Hence, in the evolution of any system, there is an overwhelming likelihood that the system evolves such that entropy increases.
In theory, there will eventually be an exception to this law. However, that exception would require churning through enough states that, in principle, it will never happen for times up to and well beyond the age of the universe.
The fact that entropy always increases accounts for the arrow of time we experience. To give you some idea of the rigidity of the Second Law, think in terms of how definitely time moves in one direction, for this is a consequence of the evolution of states according to the Second Law.
It is interesting to think about the fact that the Second Law accounts for the arrow of time. If this law were to be momentarily broken in the very distant future, would the arrow of time be instantaneously reversed?

A:
I do not understand that, when the system explores all available states and when every microstate is equally likely to occur, that the entropy necessarily increases all the time. Isn't there a small chance that the system will end up in a state with significantly lower entropy and that it immediately gets in to a high entropy state again after?

There's a common misconception here: microstates do not have entropy. Entropy is a measure of our ignorance of which microstate a system is in. If we did know the microstate, the entropy would be exactly zero. (This doesn't contradict the common intuition that "entropy is disorder". That happens because a high entropy means many possible microstates, and the vast majority of all microstates look very disordered. So they're related but not exactly the same.)
The two statements in your book aren't contradictory. In equilibrium, entropy is maximized. Accordingly, we have the least possible amount of information about which microstate is occupied, so the probability is uniform.


text:
Q: When making a branch in TortoiseSVN, what do "head", "working copy", and "specific" revisions mean? A new user of Tortoise SVN, working over source control.
I have a Visual Studio solution which consists of 5 webAppliation projects.
I need to take one out and work over it in a branch.
When I try to branch it, It is asking me of one of these options

*

*head revision in repository

*specific revision in repository

*working copy revision

alt text http://img25.imageshack.us/img25/3747/svnfile.jpg
Problem 1: What exactly are these ? I am confused with "head revision" and "working copy", as they appear same to me.
alt text http://img34.imageshack.us/img34/8079/svn2.jpg
EDIT:
Problem 2: Why cant we branch from Repository GUI itself, (would be head revision) ?
Problem 3: Can you list the steps, needed to branch from a directory !

A: *

*HEAD revision means the latest
revision in the repository.

*specific revision in the repository : here you can enter any revision you like. TortoiseSVN fill in the revision your working copy is at automatically. But you can of course change that (maybe you want to tag from a revision you created a week ago). The revision TortoiseSVN fills in automatically often is the revision your repository is at (i.e., HEAD), especially if you update often. But: While you are preparing to do the branch/tag, someone else could commit something which you might not want to have included in the branch/tag. That's why it's safer to use that revision instead of HEAD. However if you're sure that no one else is committing at this time, you can use HEAD here.

*working copy : use this if you're working copy has local modifications which you want to have included in the branch/tag. This option is useful if you want to save your work in a branch (also known as shelving).

A: Your working copy can use a different revision as the repository's head revision. I.e. you check-out a particular revision which is not the newest or people commit to the repository while you're dealing with your working copy.

A: To answer question #2, you can create a branch from the TortoiseSVN GUI. Use the Repository Browser and find the path that you want to branch from and then right-click on the folder and select "Copy To...". The URL you enter will be the URL you want to branch to (typically rooted at the "branches" folder).
This will create a branch remotely in the repository without requiring you to create a working copy first. The reason the operation is called "Copy" instead of "Branch" is that a branching operation in svn is really the same creating a copy (it's not a distinct operation).

A: The head revision in the repository is the most recent revision that has been committed to source control. Your working copy revision is the revision reflected by the current tree you have. Since people may have committed things while you're working, your working copy revision may not necessarily equal the HEAD revision.
When you branch, you're being asked to branch from a specific point. TSVN is asking you what you would like that point to be, and you have one of three choices:

*

*where you're working from right now (your working copy revision)

*where the repository is currently at right now (repository's HEAD revision)

*some other arbitrary revision (specific revision)

Update: The OP added some additional questions that weren't part of the original, so I've amended my answer.

Why cant we branch from Repository GUI itself, (would be head revision) ?

The TortoiseSVN GUI doesn't represent the complete set of operations that is possible with Subversion. Subversion is really just a set of command-line tools, and TSVN is a wrapper around them. If you wanted to make a new branch completely on the server, just use:
svn copy svn://example.com/repo/trunk/ svn://example.com/repo/branches/1.4

Can you list the steps needed to branch from a directory?

The TortoiseSVN manual is quite explicit in how to do this. See here.


text:
Q: Set title text attributes for landscape navigation bar Is there a way to set the title text attributes for a navigation bar in landscape mode using the appearance API?
On iPhone (except iPhone 6 Plus) the navigation bar shrinks in size in landscape.  I want to switch to a smaller font in this state but I'm not sure how to detect this change especially when the iPhone 6 Plus keeps the navigation bar the same size in landscape mode.


text:
Q: Plotting massive amount of data I have to plot a huge amount of data. I have only one file, I've already imported it. The file contains the following:
48 separate smaller fractions.
Every fraction begins with six numbers (which are unnecessary, for now) and it is followed by four larger vectors, the first three has nineteen (x,y) elements and the last one has eightteen (x,y) pairs inside them.
It looks something like this:
data={{a,b,c,d,e,f,{{x1,y1},{x2,y2},...,{x19,y19}},{...},{...},{...}},{a1,b1,...}}
I'd like to plot every vector ({{x1,y1},{x2,y2},...,{x19,y19}}) in a separate subplot with ListLinePlot, but all four in one row. For all of the 48 fractions. So, as a result, the whole plot would contain 48 rows and 4 columns of subplots.
{a,b,c,d,e,f} are needed in naming every graph, but that's a separate problem.
I'm relatively new to Mathematica. Can anyone help me how to plot this monster?

A: Generate data in the same format as what you have:
gen[l_] := RandomFunction[RandomWalkProcess[.5], {0, l}]["Path"]
dat = Table[{1, 2, 3, 4, 5, 6, gen[19], gen[19], gen[19], gen[18]},
  48]

Plot:
plots = Map[ListLinePlot[#[[{7, 8, 9, 10}]],
   PlotLabel -> #[[{1, 2, 3, 4, 5, 6}]]] &, dat]

Since you have all these, you may consider something like TabView[plots] to make it easier to see individual lists.
You may also want to do something like:
Grid[Partition[plots, 6]]

to display the data in a uniform grid, like so:

The upside to this is that the plots will more-or-less scale to fit into your notebook window.
It occurs to me that you may want 4 columns and 48 rows.
First we define a function to create plots with the same label (this is for each of the 4 vectors within each dataset):
p[dataarr_, label_] := Map[ListLinePlot[#, PlotLabel -> label] &, dataarr]

Now we use this function on all the 48 datasets:
plots = Map[p[#[[{7, 8, 9, 10}]], #[[{1, 2, 3, 4, 5, 6}]]] &, dat]

Then we can use Grid to display the data nicely:


text:
Q: Is it possible to shrink a log file on a linked server using DBCC SHRINKFILE? I am doing a large archival of data from one DB to another DB on a linked server.  I am copying from MS sql server 2000 to MS sql server 2005.
This involves copying millions of records and then deleting them.  This all happens via a dynamic script. I would like to incorporate the shrinking of the log file for this process, but I am unable to get the DBCC SHRINKFILE to work for the linked server.  Is this even possible?

A: You should be able to do it by calling sp_executesql through the linked server:
EXEC [LINKED_SERVER].MyDatabase.dbo.sp_executesql
    @statement = N'DBCC SHRINKFILE(''LogFileName'',0)'

You should probably rethink automatically shrinking the log file, though, especially if this script will be run so often that you need to automate it.  You'll be better off backing up the log or switching the recovery model to Simple so you can reuse the space.  (If it's going to grow back to the same size, did you really accomplish anything by shrinking it?  In fact, you can make things worse by inadvertently introducing filesystem fragmentation.)
I'm not saying you never need to shrink a file programmatically, but wanting to do so is usually a sign something else is wrong -- the disk is too small for your expected volume, you have the wrong recovery model, etc.


text:
Q: Why drawing a line in OpenGL is not working? GLfloat vertices[NUM_VERTICES][3] = {

{ -0.5, -0.4, 0.0 },
    {  0.5, -0.4, 0.0 },
    {  0.5,  0.4, 0.0 },
    {  0.0,  0.8, 0.0 },
    { -0.5,  0.4, 0.0 }
};
void init() {
  glClearColor(0.0, 0.0, 0.0, 0.0);
  glShadeModel(GL_FLAT);
}

void display() {
  glClear(GL_COLOR_BUFFER_BIT);
  glBegin(GL_POLYGON);
  for (int i = 0; i < NUM_VERTICES; i++) {

    glColor3fv(colors[i]);
    glVertex3fv(vertices[i]);
    }
  glEnd();
  glutSwapBuffers();
  glClear(GL_COLOR_BUFFER_BIT);
  //glClearColor(0.0, 0.0, 0.0, 0.0);
  glShadeModel(GL_FLAT);
  glColor3ub(1.0, 1.0, 1.0);
  glLineWidth(10);
  glBegin(GL_LINES);
  glVertex2f(0.0, -0.4);
  glVertex2f(0.0, 0.8);
  glEnd();
}

I drew a pentagon using OpenGL. I want to draw a line from one point to another inside the pentagon but it doesn't work. How to make it work?

A: glClear clears the entire framebuffer and must be called once before drawing all of the geometry. If you call it in between, all previous drawings will be cleared. glutSwapBuffers() swaps the buffers and updates the display and must be called after drawing all the objects in the scene:
void display() {
  glClear(GL_COLOR_BUFFER_BIT);

  glBegin(GL_POLYGON);
  for (int i = 0; i < NUM_VERTICES; i++) {
    glColor3fv(colors[i]);
    glVertex3fv(vertices[i]);
  }
  glEnd();

  glColor3ub(1.0, 1.0, 1.0);
  glLineWidth(10);
  glBegin(GL_LINES);
  glVertex2f(0.0, -0.4);
  glVertex2f(0.0, 0.8);
  glEnd();

  glutSwapBuffers();
}


text:
Q: how to know which zones have the vCPU capacity I am trying to configure a compute engine instance. No matter which zone/region I pick, it says the region is limited to 24 cores. I have an instance that somehow I edited to 32 cores, but whenever I try to start it, it says no resources available.
How do you get a high core instance ?
Thanks.

A: This sounds like it might be a quota issue. I assume that you have billing enabled; if you do not then you should sort that out first :-)
You can see your quotas by zone by going to the console and in the sidebar select "IAM & admin" > "Quotas" then in the drop down menus select Service "Compute Engine API" and Metric "CPUs."
I for example have a max of 24 cores in some zones, and 72 cores in other zones.
Note: if you have a quota of 72 cores elsewhere, and don't really care what zone you use, this would be the time to migrate to a zone with higher quota.
Assuming that the issue is that your quota is 24 in a zone you need 32 cores in, do the following:

*

*Select the zone with the checkbox on the left

*Click "Edit Quotas" at the top

*Fill out the form on the right

*Wait

Ideally, if you need 32 cores, approval should be quick. If you have a brand new project, or lots of cores in other zones, it might go to a human. In either case, please put in a reasonable justification.

A: It seems you have reached your quota limit for cores in that specific region. In my case I have some regions with a limit of 72 and others with a limit of 8.
I suggest under the IAM page in your project where it says "Quotas" verify your limit. For example you can filter it so it's much faster and easier to read.
Go to IAM -> Quotas then to filter:

*

*Quota type = All quotas

*Service = Compute Engine API

*Metrics = CPUs

*Location = All locations

There you can see the limits for CPUs(cores) for all of your regions and select one that has a limit of more than 32.
Just an FYI, If you need to ask for a quota increase your project needs to not be in free trial, so basically you would need to upgrade your account.


text:
Q: Typescript Declare Class Type In Javascript I have:
var session = require('express-session');
var SequelizeStore = require('connect-session-sequelize')(session.Store);
new SequelizeStore({
    db: sequelize
});

I set these types:
function ConnectSessionSequelize(store: expressSession.IBaseStore): expressSession.IBaseStore;

This fails because expressSession.IBaseStore refers to an instance type, not a class type. Is there a way to specify class types, similar to Java: Class<expressSession.IBaseStore>?
Currently I'm using function CoSeSe(store: Function): Function, but this has major type leakage!

A: The syntax typeof SomeClass will give you the type of the constructor function SomeClass (e.g. the type of x if you wrote let x = SomeClass) rather than the instance side (e.g. the type of y if you wrote let y = new SomeClass()).


text:
Q: ISNULL() in LINQ to XML SELECT * FROM CUSTOMERS WHERE RTRIM(ISNULL([SHORTNAME],'')) LIKE '%john%'
I want to write this using Linq,
var persons = from person in xmlDoc.Descendants("Table")
where
person.Element("SHORTNAME").Value.Contains("123")
select new
{
  shortName = person.Element("SHORTNAME").Value,
  longName = person.Element("LONGNAME").Value,
  address = person.Element("ADDRESS").Value,
  Phone = person.Element("PHONE") != null ? person.Element("PHONE").Value : "",
  zip = person.Element("ZIPCODE") != null ? person.Element("ZIPCODE").Value : "",
};

This works fine when [SHORTNAME] is not null, if [SHORTNAME] is a null value this breakes the code and pops up a "Null Reference Exception"
Please help me...

A: Assuming you're trying to avoid picking up anything where there isn't a short name...
var persons = from person in xmlDoc.Descendants("Table")
    let shortNameElement = person.Element("SHORTNAME")
    where shortNameElement != null && shortNameElement.Value.Contains("123")
    select new
    {
        shortName = person.Element("SHORTNAME").Value,
        longName = person.Element("LONGNAME").Value,
        address = person.Element("ADDRESS").Value,
        Phone = person.Element("PHONE") != null ?
            person.Element("PHONE").Value : "",
        zip = person.Element("ZIPCODE") != null ?
            person.Element("ZIPCODE").Value : "",
    };

Alternatively, you can use the null coalescing operator to make all of these a bit simpler:
var emptyElement = new XElement("ignored", "");

var persons = from person in xmlDoc.Descendants("Table")
    where (person.Element("SHORTNAME") ?? emptyElement).Value.Contains("123")
    select new
    {
        shortName = person.Element("SHORTNAME").Value,
        longName = person.Element("LONGNAME").Value,
        address = person.Element("ADDRESS").Value,
        Phone = (person.Element("PHONE") ?? emptyElement).Value
        zip = (person.Element("ZIPCODE") ?? emptyElement).Value
    };

Or alternatively, you could write an extension method:
public static string ValueOrEmpty(this XElement element)
{
    return element == null ? "" : element.Value;
}

and then use it like this:
var persons = from person in xmlDoc.Descendants("Table")
    where person.Element("SHORTNAME").ValueOrEmpty().Contains("123")
    select new
    {
        shortName = person.Element("SHORTNAME").Value,
        longName = person.Element("LONGNAME").Value,
        address = person.Element("ADDRESS").Value,
        Phone = person.Element("PHONE").ValueOrEmpty(),
        zip = person.Element("ZIPCODE").ValueOrEmpty()
    };

A: Use the null coalescing operator:
Phone = person.Element("PHONE") ?? String.Empty;


text:
Q: How to compute the variance for this biased random walk. Suppose over each time increment $\Delta t$ our process X increases by $h$ with probability $p$ and decreases by $h$ with probability $1-p$. Lets call $\Delta X=X(t+\Delta t)-X(t)$ the increment of X. Then it is clear to me that the variance will be $E(\Delta X)=(2p-1)h$. I don't see how the variance is $$var(\Delta X)= (1-(2p-1)^2)h^2.$$
I tried using the variance formula to recover the above, however I get stuck when I have to compute $E((\Delta X)^2)$.

A: Since squaring $h$ and $-h$ gives the same thing, $\Delta X^2 = h^2$ with probability 1. So $E(\Delta X^2) = h^2.$
You can also calculate it like $$ E(\Delta X^2) = ph^2 + (1-p)h^2 = h^2.$$
Then you can use the formula $\mathrm{Var}(\Delta X) = E(\Delta X^2)-E(\Delta X)^2$ to get the answer.

A: It holds $\Delta X \in \{-h,h\}$ and so $(\Delta X)^2 \equiv h^2$ and it follows $$var(\Delta X) = E((\Delta X)^2) - E^2(\Delta X) = h^2 - (2p-1)^2h^2 = (1-(2p-1)^2)h^2$$


text:
Q: Depth of monomial ideal Let $S=K[X_1,...,X_n]$, $K$ a field, and $I \subset S$ a nontrivial monomial ideal generated by squarefree monomials of degree $\geq d$. Then show that depth$_S I \geq d$.

A: The property is not trivial. You can find a proof, using filtrations, here: https://arxiv.org/pdf/0712.2308.pdf (see Proposition 3.1)


text:
Q: Apollo Server - Confusion about cache/datasource options The docs (https://www.apollographql.com/docs/apollo-server/features/data-sources.html#Using-Memcached-Redis-as-a-cache-storage-backend) show code like this:
const { RedisCache } = require('apollo-server-cache-redis');

const server = new ApolloServer({
  typeDefs,
  resolvers,
  cache: new RedisCache({
    host: 'redis-server',
    // Options are passed through to the Redis client
  }),
  dataSources: () => ({
    moviesAPI: new MoviesAPI(),
  }),
});

I was wondering how that cache key is used, considering it seems like the caching is actually custom implemented in something like MoviesAPI() and then used via context.dataSources.moviesAPI.someFunc(). For example, say I wanted to implement my own cache for a SQL database. It'd look like
  cache: new RedisCache({
    host: 'redis-server',
  }),
  dataSources: () => ({
    SQL: new SQLCache(),
  }),
});

where SQLCache has my own function that connects to the RedisCache like:
  getCached(id, query, ttl) {
    const cacheKey = `sqlcache:${id}`;

    return redisCache.get(cacheKey).then(entry => {
      if (entry) {
        console.log('CACHE HIT!');
        return Promise.resolve(JSON.parse(entry));
      }
      console.log('CACHE MISS!');
      return query.then(rows => {
        if (rows) redisCache.set(cacheKey, JSON.stringify(rows), ttl);
        return Promise.resolve(rows);
      });
    });
  }

So that means I have RedisCache in both the ApolloServer cache key and dataSource implementation. Clearly, the RedisCache is used in the dataSource implementation, but then what does that ApolloServer cache key do exactly?
Also on the client, examples mostly show use of InMemoryCache instead of Redis cache. Should the client Apollo cache be a different cache from the server cache or should the same cache like RedisCache be in both places?

A: The cache passed to the ApolloServer is, to my knowledge, strictly used in the context of a RESTDataSource. When fetching resources from the REST endpoint, the server will examine the Cache-Control header on the response, and if one exists, will cache the resource appropriately. That means if the header is max-age=86400, the response will be cached with a TTL of 24 hours, and until the cache entry expires, it will be used instead of calling the same REST url.
This is different than the caching mechanism you've implemented, since your code caches the response from the database. Their intent is the same, but they work with different resources. The only way your code would effectively duplicate what ApolloServer's cache already does is if you had written a similar DataSource for a REST endpoint instead.
While both of these caches reduce the time it takes to process your GraphQL response (fetching from cache is noticeably faster than from the database), client-side caching reduces the number of requests that have to be made to your server. Most notably, the InMemoryCache lets you reuse one query across different places in your site (like different components in React) while only fetching the query once.
Because the client-side cache is normalized, it also means if a resource is already cached when fetched through one query, you can potentially avoid refetching it when it's requested with another query. For example, if you fetch a list of Users with one query and then fetch a user with another query, your client can be configured to look for the user in the cache instead of making the second query.
It's important to note that while resources cached server-side typically have a TTL, the InMemoryCache does not. Instead, it uses "fetch policies" to determine the behavior of individual queries. This lets you, for example, have a query that always fetches from the server, regardless of what's in the cache.
Hopefully that helps to illustrate that both server-side and client-side caching are useful but in very different ways.


text:
Q: What's the elegant way of writing CombineLatest with conditional arguments? In a non-async code, I do the following:
    const x = [
        ...(isY ? [Y]: []),
        ...(isZ ? [Z] : [])
    ];

How would you elegantly write this structure when isY and isZ are Observables<boolean>, and x to be an Observable<Object[]>.
I can do this with al kinds of mappings, but nothing looks clean or elegant.

A: combineLatest operator is best used when you have multiple, long-lived observables that rely on each other for some calculation or determination.
Be aware that combineLatest will not emit an initial value until each observable emits at least one value.
You can have a look at the explanation for combineLatest.
const x: Observable<any[]> = combineLatest(isY$, isZ$).pipe(
    map([isY, isZ] => {
        return [
            ...(isY ? [Y]: []),
            ...(isZ ? [Z]: [])
        ]
    })
)

EDIT:
You can also use the combineLatest project-function, so it can even be terser by doing
const x: Observable<any[]> = combineLatest(isY$, isZ$, (isY, isZ) => [
   ...(isY ? [Y]: []),
   ...(isZ ? [Z]: [])
])


text:
Q: Regex Find string if it comes after another string Can anyone please help me find a regex for the following. I am trying to match the number after "Processed" but ONLY if the previous line contains the string "Backed".
I have been using "(?<=Processed )(.*?)(?= bytes)" to get the number, but I would like to use preg-match-all and ONLY match the Backed up numbers, not the verified numbers....
Here is an example string:
Backed up 77914 files in 16615 directories.
Processed 19,500,663,915 bytes in  10 minutes and  27 seconds.
Throughput rate: 1780 MB/min*

Contents verified.
Processed 13,694,118,197 bytes in  1 minute and  41 seconds.
Throughput rate: 7758 MB/min*

A: this is the closest I can get based on your requirements:
(?<=Backed)[^\n]+[\n\r]+.*Processed\s(?<num>(\d+\,*)+)\sbytes

The result is in group num
I have tested it with the following input:

Backed up 77914 files in 16615 directories. Processed 19,500,663,915 bytes in 10 minutes and 27 seconds. Throughput rate: 1780 MB/min
Contents verified. Processed 13,694,118,197 bytes in 1 minute and 41 seconds. Throughput rate: 7758 MB/min
up 77914 files in 16615 directories. Processed 19,500,663,915 bytes in 10 minutes and 27 seconds. Throughput rate: 1780 MB/min
Contents verified. Processed 13,694,118,197 bytes in 1 minute and 41 seconds. Throughput rate: 7758 MB/min

..and it matches only the first occurrence of 13,694,118,197

A: Give this a try
(?<=.*Backed.*)[\d,]+(?= bytes)

given the input
Backed up 77914 files in 16615 directories. Processed 19,500,663,915 bytes in 10 minutes and 27 seconds. Throughput rate: 1780 MB/min
Contents verified. Processed 13,694,118,197 bytes in 1 minute and 41 seconds. Throughput rate: 7758 MB/min
Backed up 77914 files in 16615 directories. Processed 19,500,663,915 bytes in 10 minutes and 27 seconds. Throughput rate: 1780 MB/min
Contents verified. Processed 13,694,118,197 bytes in 1 minute and 41 seconds. Throughput rate: 7758 MB/min

It will match
19,500,663,915
19,500,663,915

It can be that PCRE library does not support infinite repetition inside lookbehind. If thats the case we can look for an alternative


text:
Q: Where to put VueJS components common across the application In my nuxtjs application, I have few features that are used across the application viz Login/Signup dialog, a snackbar to show alerts etc. Since, I want these features on every page and v-app-bar component is already added to all the pages. I have included the components for these features inside v-app-bar component.
<template>
  <v-app-bar app id="app-bar">
    <LoginJoinDialog />
    <AlertSnackbar />

    <!-- Code for App bar -->

  </v-app-bar>
</template>

But I am not happy with this approach for following reasons

*

*I know these common components does not belong to the v-app-bar component. And just for the sake of DRY and maintenance headaches I have included them. So from design perspective this is not very intuitive.

*Secondly, What if in future I have pages that do not have a v-app-bar component. In that case I will be repeating code for these common components anyway. So, the pain of maintaining the code at multiple places will still be there.

Considering the above points, I am looking for a more elegant approach than what I have implemented. If there is a vuejs recommendation on this, even better. What suggestions do you have for component structuring for these common features?

A: You can acheive what you are looking for using layouts. What you need to do is make layouts folder inside src directory. And then you can create as many
 layout components(*.vue files) and use them as you like.
For an example, this is default.vue component inside layouts folder:
<template>
  <main>
    <!-- Your app bar component -->
    <v-app-bar app id="app-bar">
      <LoginJoinDialog />
      <AlertSnackbar />
      <!-- Code for App bar -->
    </v-app-bar>

    <!-- Page Content (This tag will automatically embed the page content into layouts)-->
    <nuxt />

  </main>
</template>

<script>
export default {};
</script>

Now, on your pages folder, you can add index.vue file where you can reference the default layout, as a property in this manner: layout: 'default'
The index.vue file should look something like this:
<template>
  <!-- page content goes here -->
</template>

<script>
export default {
  name: 'HomePage',
  layout: 'default',
};
</script>

I also have created an example project in nuxt with layouts.
For a working prototype of the project: Visit this link.
I hope it helps to solve your issue.

A: You can use global component registration trick by Chris Fritz. You just to need to modify it a bit so it's more fitting for a nuxt.js app. So you can create a base folder under your components folder and keep all these shared components there. Then create a new plugin and change the path to your @/components/base folder and modify the regex so it grabs all the files, no matter what the name is:
globalComponents.js
import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

export default () => {
  const requireComponent = require.context(
    '@/components/base', false, /[\w-]+\.vue$/
  )

  requireComponent.keys().forEach(fileName => {
    const componentConfig = requireComponent(fileName)

    const componentName = upperFirst(
      camelCase(fileName.replace(/^\.\/(.*)\.\w+$/, '$1'))
    )

    Vue.component(componentName, componentConfig.default || componentConfig)
  })
}

nuxt.config.js
plugins: [
  '~/plugins/globalComponents.js'
],


text:
Q: How to draw a directed graph with arrows showing vertically from bottom to top If I have a directed graph, how can I draw it with arrows showing in general vertically from bottom to top, like showing a class inheritance pattern in OOP(object oriented programming)?

A: If the graph is acyclic, you can use topological sorting to assign a vertical level to every vertex.


text:
Q: Displaying HTML pages in an ASP.Net MVC Web App I have a simple MVC site but I need to add in some static HTML pages, I have tried to add an IgnoreRoute in for .html files but this didn't work.

A: routes.IgnoreRoute("{resource}.html/{*pathInfo}"); worked for me. And place it before all other route definitions in your global.asax.


text:
Q: XMLDocument going deep Right now I have my code similar to this (actually one level deeper).  If the company name is equal to the node of company then create a node list from it (as I need to populate a drop down box with all of the details) ---Not using 3.5 for this project :(
XmlNodeList elemList = xmlDoc.GetElementsByTagName("company");
foreach (XmlNode node in elemList)
{
    if (node.Attributes[0].Value == company)
    {
        foreach (XmlNode child in node.ChildNodes)
        {
            foreach (XmlNode detail in child.ChildNodes)
            {
                ddlCodes.Items.Add(detail.Value.ToString());
            }
        }
    }
}

Not really liking all those foreach statements, just wondering if there is a cleaner way. Here is how my xml looks like
<companies>
    <company id="company1">
       12
       <detail>detail of 12 code</detail>
    </company>
    <company id="company2">
       15
       <detail>detail of 15 code</detail>
    </company>
</companies>

A: Have a look at XPath and the XPathNavigator class, it provides you with a query language for XML
Or you could use Linq to XML if you want but that depends on the .net framework you're using.

A: How about this?
[XmlRoot("companies")]
public class Root
{
    [XmlElement("company")]
    public company[] companies;
}

public class company
{
    [XmlAttribute("id")]
    public string id;
    public string code;
    public string detail;
}

XmlSerializer xml = new XmlSerializer(typeof(Root));
Root r = (Root)xml.Deserialize(new StringReader(xmlstr));