text:
Q: JavaScript String concatenation behavior with null or undefined values As you may know, in JavaScript '' + null = "null" and '' + undefined = "undefined" (in most browsers I can test: Firefox, Chrome and IE). I would like to know the origin of this oddity (what the heck was in the head on Brendan Eich?!) and if there is any aim for changing it in a future version of ECMA. It's indeed pretty frustrating having to do 'sthg' + (var || '') for concatenating Strings with variables and using a third party framework like Underscore or other for that is using a hammer for jelly nail pounding.
Edit:
To meet the criteria required by StackOverflow and clarify my question, it is a threefold one:

*

*What is the history behind the oddity that makes JS converting null or undefined to their string value in String concatenation?

*Is there any chance for a change in this behavior in future ECMAScript versions?

*What is the prettiest way to concatenate String with potential null or undefined object without falling into this problem (getting some "undefined" of "null" in the middle of the String)? By the subjective criteria prettiest, I mean: short, clean and effective. No need to say that '' + (obj ? obj : '') is not really pretty…

A:
What is the prettiest way to concatenate String with potential null or undefined object without falling into this problem [...]?

There are several ways, and you partly mentioned them yourself. To make it short, the only clean way I can think of is a function:
const Strings = {};
Strings.orEmpty = function( entity ) {
    return entity || "";
};

// usage
const message = "This is a " + Strings.orEmpty( test );

Of course, you can (and should) change the actual implementation to suit your needs. And this is already why I think this method is superior: it introduced encapsulation.
Really, you only have to ask what the "prettiest" way is, if you don't have encapsulation. You ask yourself this question because you already know that you are going to get yourself into a place where you cannot change the implementation anymore, so you want it to be perfect right away. But that's the thing: requirements, views and even envrionments change. They evolve. So why not allow yourself to change the implementation with as little as adapting one line and perhaps one or two tests?
You could call this cheating, because it doesn't really answer how to implement the actual logic. But that's my point: it doesn't matter. Well, maybe a little. But really, there is no need to worry because of how simple it would be to change. And since it's not inlined, it also looks a lot prettier – whether or not you implement it this way or in a more sophisticated way.
If, throughout your code, you keep repeating the || inline, you run into two problems:

*

*You duplicate code.

*And because you duplicate code, you make it hard to maintain and change in the future.

And these are two points commonly known to be anti-patterns when it comes to high-quality software development.
Some people will say that this is too much overhead; they will talk about performance. It's non-sense. For one, this barely adds overhead. If this is what you are worried about, you chose the wrong language. Even jQuery uses functions. People need to get over micro-optimization.
The other thing is: you can use a code "compiler" = minifier. Good tools in this area will try to detect which statements to inline during the compilation step. This way, you keep your code clean and maintainable and can still get that last drop of performance if you still believe in it or really do have an environment where this matters.
Lastly, have some faith in browsers. They will optimize code and they do a pretty darn good job at it these days.

A: Why not filter to check for truthyness and then join?
const concatObject = (obj, separator) =>
    Object.values(obj)
        .filter((val) => val)
        .join(separator);

let myAddress = {
    street1: '123 Happy St',
    street2: undefined,
    city: null,
    state: 'DC',
    zip: '20003'
}

concatObject(myAddress, ', ')

> "123 Happy St, DC, 20003"

A:
Is there any chance for a change in this behavior in future ECMAScript versions?

I would say the chances are very slim. And there are several reasons:
We already know what ES5 and ES6 look like
The future ES versions are already done or in draft. Neither one, afaik, changes this behavior. And the thing to keep in mind here is that it will take years for these standards to be established in browsers in the sense that you can write applications with these standards without relying on proxy tools that compile it to actual Javascript.
Just try to estimate the duration. Not even ES5 is fully supported by the majority of browsers out there and it will probably take another few years. ES6 is not even fully specified yet. Out of the blue, we are looking at at least another five years.
Browsers do their own things
Browsers are known to make their own decisions on certain topics. You don't know whether all browsers will fully support this feature in exactly the same way. Of course you would know once it is part of the standard, but as of now, even if it was announced to become part of ES7, it would only be speculation at best.
And browsers may make their own decision here especially because:
This change is breaking
One of the biggest things about standards is that they usually try to be backwards compatible. This is especially true for the web where the same code has to run on all kinds of envrionments.
If the standard introduces a new feature and it's not supported in old browsers, that's one thing. Tell your client to update their browser to use the site. But if you update your browser and suddenly half the internet breaks for you, that's a bug uhm-no.
Sure, this particular change is unlikely to break a lot of scripts. But that's usually a poor arguments because a standard is universal and has to take every chance into account. Just consider
"use strict";

as the instruction to switch to strict mode. It goes to show huw much effort a standard puts into trying to make everything compatible, because they could've made strict mode the default (and even only mode). But with this clever instruction, you allow old code to run without a change and still can take advantage of the new, stricter mode.
Another example for backwards compatibility: the === operator. == is fundamentally flawed (though some people disagree) and it could've just changed its meaning. Instead, === was introduced, allowing old code to still run without breaking; at the same time allowing new programs to be written using a more strict check.
And for a standard to break compatibility, there has to be a very good reason. Which brings us to
There is just no good reason
Yes, it bugs you. That's understandable. But ultimately, it is nothing that can't be solved very easily. Use ||, write a function – whatever. You can make it work at almost no cost. So what is really the benefit for investing all the time and effort into analyzing this change which we know is breaking anyway? I just don't see the point.
Javascript has several weak points in its design. And it has increasingly become a bigger issue as the language became more and more important and powerful. But while there are very good reasons to change a lot of its design, other things just arent't meant to be changed.

Disclaimer: This answer is partly opinion-based.

A: The ECMA Specification
Just to flesh out the reason it behaves this way in terms of the spec, this behavior has been present since version one.  The definition there and in 5.1 are semantically equivalent, I'll show the 5.1 definitions.
Section 11.6.1: The Addition operator ( + )

The addition operator either performs string concatenation or numeric
  addition.
The production AdditiveExpression : AdditiveExpression +
  MultiplicativeExpression is evaluated as follows:

*

*Let lref be the result of evaluating AdditiveExpression.

*Let lval be GetValue(lref).

*Let rref be the result of evaluating
  MultiplicativeExpression.

*Let rval be GetValue(rref).

*Let lprim be
  ToPrimitive(lval).

*Let rprim be ToPrimitive(rval).

*If Type(lprim) is
  String or Type(rprim) is String, then
  a. Return the String that is the
  result of concatenating ToString(lprim) followed by ToString(rprim)

*Return the result of applying the addition operation to
  ToNumber(lprim) and ToNumber(rprim). See the Note below 11.6.3.

So, if either value ends up being a String, then ToString is used on both arguments (line 7) and those are concatenated (line 7a).  ToPrimitive returns all non-object values unchanged, so null and undefined are untouched:
Section 9.1 ToPrimitive

The abstract operation ToPrimitive takes an input argument and an optional argument PreferredType. The abstract operation ToPrimitive converts its input argument to a non-Object type ...  Conversion occurs according to Table 10:

For all non-Object types, including both Null and Undefined, [t]he result equals the input argument (no conversion).  So ToPrimitive does nothing here.
Finally, Section 9.8 ToString

The abstract operation ToString converts its argument to a value of type String according to Table 13:

Table 13 gives "undefined" for the Undefined type and "null" for the Null type.
Will it change? Is it even an "oddity"?
As others have pointed out, this is very unlikely to change as it would break backward compatibility (and bring no real benefit), even more so given that this behavior is the same since the 1997 version of the spec.  I would also not really consider it an oddity.
If you were to change this behavior, would you change the definition of ToString for null and undefined or would you special-case the addition operator for these values?  ToString is used many, many places throughout the spec and
"null" seems like an uncontroversial choice for representing null.  Just to give a couple of examples, in Java "" + null is the string "null" and in Python str(None) is the string "None".
Workaround
Others have given good workarounds, but I would add that I doubt you want to use entity || "" as your strategy since it resolves true to "true" but false to "".  The array join in this answer has the more expected behavior, or you could change the implementation of this answer to check entity == null (both null == null and undefined == null are true).

A: Use coalescing - syntax is ??
Examples, can test in your browser console:

*

*"Hello " + (null ?? "")

*"Hello " + (undefined ?? "")
Both will yield: 'Hello '

A: You can use Array.prototype.join to ignore undefined and null:
['a', 'b', void 0, null, 6].join(''); // 'ab6'

According to the spec:

If element is undefined or null, Let next be the empty String;
  otherwise, let next be ToString(element).

Given that,

*

*

    What is the history behind the oddity that makes JS converting null or undefined to their string value in String concatenation?
In fact, in some cases, the current behavior makes sense.
function showSum(a,b) {
    alert(a + ' + ' + b + ' = ' + (+a + +b));
}
For example, if the function above is called without arguments, undefined + undefined = NaN is probably better than  +  = NaN.
In general, I think that if you want to insert some variables in a string, displaying undefined or null makes sense. Probably, Eich thought that too.
Of course, there are cases in which ignoring those would be better, such as when joining strings together. But for those cases you can use Array.prototype.join.

*

    Is there any chance for a change in this behavior in future ECMAScript versions?
Most likely not.
Since there already is Array.prototype.join, modifying the behavior of string concatenation would only cause disadvantages, but no advantages. Moreover, it would break old codes, so it wouldn't be backwards compatible.

*

    What is the prettiest way to concatenate String with potential null or undefined?
Array.prototype.join seems to be the simplest one. Whether it's the prettiest or not may be opinion-based.

A: To add null and '' they need to meet a minimum common type criterium which in this case is a string type.
null is converted to "null" for this reason and as they are string the two are concatenated.
The same happens with numbers:
4 + '' = '4'
as there is a string in there which can't be converted to any number, so the 4 will be converted to string instead.


text:
Q: Not using vertex attributes based on push constants I have a GLSL vertex shader where one of the attributes is only used if a push constant is set:
layout(location = 0) in ivec2 a_pos;
layout(location = 1) in ivec2 a_nrm;
layout(location = 2) in float a_Height;

void main()
{
<...>
float Offset = ( u_enabling_flag > 0.0 ) ? a_Height : 0.0;
< some calculation involving Offset >

I get the following validation error:
vkDebug: Validation: 0: Validation Error: [ UNASSIGNED-CoreValidation-Shader-InputNotProduced ] Object 0: handle = 0x3a000000003a, type = VK_OBJECT_TYPE_SHADER_MODULE; | MessageID = 0x23e43bb7 | Vertex shader consumes input at location 2 but not provided
The graphical output looks fine but is there a possibility to get rid of the error?
Regards.

A:
The graphical output looks fine but is there a possibility to get rid of the error?

"Vertex shader consumes input at location 2 but not provided"

Remove the input at location 2 from the shader, or attach a buffer binding at that location.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Want to implement jquery-ui-daterangepicker in Angular Hi Friend I want to use jquery ui datepicker plugin in my app
I am using http://tamble.github.io/jquery-ui-daterangepicker/ this plugin and want same functionality without any change
I have tried something like this code below
(function(){
angular.module('publisher-portal').directive('dateRangePicker', function () {
    return {
         restrict : 'A',
         require: 'ngModel',
         link : function (scope, element, attr, ngModel) {

            element.daterangepicker();
         }
    };
});
})();
<input id="e2" type="text" ng-model="mydate" dateRangePicker/>

Please suggest me some solution

A: this is a working snippet (that a close look of how i'm making sure that the jQuery loaded before i call .daterangepiker
more few think you miss on the way

*

*you forgot to put an empty array after you install the module app.module('publisher-portal',[])

*you didn't warp the element in $() statement

(function($){
angular.module('publisher-portal',[]).directive('dateRangePicker', function () {
    return {
         restrict : 'A',
         require: 'ngModel',
         link : function (scope, element, attr, ngModel) {

            $(element).daterangepicker();
         }
    };
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.js"></script>
    <script src="https://cdn.jsdelivr.net/momentjs/2.3.1/moment.min.js"></script>
<script src="http://tamble.github.io/jquery-ui-daterangepicker/daterangepicker-master/jquery.comiseo.daterangepicker.js"></script>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/bootstrap/3.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/bootstrap/3.1.1/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="http://tamble.github.io/jquery-ui-daterangepicker/assets/css/styles.css">
    <link rel="stylesheet" href="http://tamble.github.io/jquery-ui-daterangepicker/prettify/prettify.css">
    <link rel="stylesheet" href="http://tamble.github.io/jquery-ui-daterangepicker/daterangepicker-master/jquery.comiseo.daterangepicker.css">
<div ng-app='publisher-portal'>

<input id="e2" type="text" ng-model="mydate" date-range-picker />
  </div>

A: Check out this pure Angular (no jquery required) date range picker.
https://github.com/tawani/taDateRangePicker


text:
Q: how to load graph after loading other data I'm using rails 3.2.1
My page is divided into 5 parts
part-1 header
part-2 div area
part-3 graph part
part-4 data in tabular format
part-5 footer
Now my problem is that graph take too much time to upload.
Due to which this page take too much time to load.
Please tell me any method so that my graph load in the last but other data will display.

A: If the problem is that the graph data is taking too long to download, then you'll need to download it separately with an AJAX call instead of including it directly in the page. Something like:
$.getJSON("/url/to/your/data", function(data){$.jqplot('chart1', data)});

...which you'll have to support on the server by making /url/to/your/data provide the same graph data that you currently embed in the page. That code will start downloading and then rendering the graph data separately from the rest of the page.
If that causes problems with the DOM not quite being ready (not sure why it would), then wrap your call so that it only happens when the doc is fully rendered:
$(function(){
    $.getJSON("/url/to/your/data", function(data){$.jqplot('chart1', data)});
});

A: The first thing that you can do is to call the function that draws the graph when condition is true. For example:
(function isMyDataLoaded(){

    //if the table is rendered
    if($('#TableData').length==0){
         setTimeout(isMyDataLoaded,100);
    }else{
          DrawGraphFunction();
    }
 })();

Note: I do not know your logic, so you can use other condition.


text:
Q: How to find memory used by each object in a program? How do I find out about the memory used by each object in a program?
For example : I want to know how much memory(in Kb) is used by this object "someclassinstance"..
someclass someclassinstance=new someclass();
I can see the total memory used by the application in the task manager...But Is there a way to see detailed report about memory usage for each object instance?
Note:I've tried CLR profiler..but it only shows total memory used by strings as far as i know...It does not show the memory used by each string object.
Thanks

A: .NET Memory Profiler is excellent  It's got a 14 day trial and is pretty cheap after that.  It lets you track all the instances you have, graph them and see how much memory each is taking.  It gives you a tremendous amount of insight into exactly what is happening in your application.

A: Red Gate Software makes Ants Profiler which I believe will give you the information you want. It's decidedly non-free but there is a 15 day trial and depending on whether or not your lucky enough to have a budget for software at your job you might be able to buy it.

A: CLR profiler is free and can do this. It has a learning curve, but comes with the documentation you will need.

A: The mount of memory allocated is for a new someclass is sizeof(someclass) rounded up; the rounding up is probabably something like sizeof(someclass) + sizeof(void*) rounded to 32.
This won't tell you what, if any, memory someclass allocates for its members.
The best way to do this might be to replace global operator new with a wrapper that records bytes allocated. Note that as alluded to above, the bytes requested are less than the bytes actually allocated, for book-keeping and alignment reasons.
This can be done in C++, I don't know about C#.

A: The free, extremely powerful and fairly tricky way of doing this is with Windbg + SOS
This blog post should be enough to start you off.


text:
Q: Create a random audio sound generator Thanks for replying.
I am trying to make a program when I press a button once, two random sounds will play. I can get the random sounds to play if I press the button, but I am looking that if I press the button, the random sound will play differently each time.
I can paste the sounds together to hear them in the sequence I want them, but I would like swift to generate the sounds.
I thought of the AVqueplayer to make it as a playlist. I was thinking this can be like a pair of dice in an analogy. For example, if I were to throw the dice down, the random sounds will occur.
I am still a newbie, and tried to figure this out on my own, because it seemed so simple, but I am out of options now.
Here is what I got so far. This will play a random sound when I press the button each time.
import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player: AVAudioPlayer = AVAudioPlayer()

    var sounds = ["sound1", "sound2", "sound3"]

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
        if event!.subtype == UIEventSubtype.motionShake {

            let randomNumber = Int(arc4random_uniform(UInt32(sounds.count)))
            let fileLocation = Bundle.main.path(forResource: sounds[randomNumber], ofType: "mp3")
            var error: NSError? = nil
            do { try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation!))
            player.play()
            } catch {}
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

A: Using the same code, and adding a second random number with matching file location will allow the sounds to play back to back, both being random:
import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player: AVAudioPlayer = AVAudioPlayer()

    var sounds = ["sound1", "sound2", "sound3"]

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
        if event!.subtype == UIEventSubtype.motionShake {

            let randomNumber1 = Int(arc4random_uniform(UInt32(sounds.count)))
            let randomNumber2 = Int(arc4random_uniform(UInt32(sounds.count)))
            let fileLocation1 = Bundle.main.path(forResource: sounds[randomNumber1], ofType: "mp3")
            let fileLocation2 = Bundle.main.path(forResource: sounds[randomNumber2], ofType: "mp3")
            //var error: NSError? = nil
            do {
                try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation1!))
                player.play()
                try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation2!))
                player.play()
            } catch {}
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


text:
Q: How can I reduce panic in a country? I had to ignore a call for help from India because the one from Germany had a better reward. Now India is at 4 out of 5 panic bar thingies, and I don't know what I can do to get that back down.
They are not funding me currently, but it seems like it would be bad if that bar fills up. What can I do to get the bar to go back down to normal levels?
Does panic ever go down over time?

A: Here's my aggregated understanding of panic changes.  There is still a good bit of uncertainty on some of the more rare cases.  Please edit this post if you have more detailed or more correct information!  Also feel free to fix my crappy formatting.

Reducing Panic

*

*Successfully assault a UFO landing site or crash site

*

*-2 panic in the nation the UFO landed/crashed in

*

*Complete a council mission (VIP escort, bomb defuse, etc)

*

*-1 panic in all nations in all continents?

*This seems to vary occasionally and may even be random.  If it were random I would guess it's a panic reduction between 0 and 2 for each nation

*

*Complete a major combat mission objective (i.e. Assault the Alien Base)

*

*-2 panic in all nations in all continents

*This may be different for other mission objectives

*

*Build a satellite over a nation

*

*-2 panic in the associated nation (-3 or even -4 if the nation specifically requested a satellite)

*

*Successfully stop a terror attack

*

*-2 panic in all nations on the continent the terror attack occurred in

Mixed Panic Response

*

*Successfully respond to an abduction (the 3-choice scenario that happens frequently)

*

*-2 panic in the nation you responded to

*NO panic change in other nations in the continent you responded to

*+1 panic in every nation in the continents which had an abduction you did not respond to

*

*In some cases, I have seen +2 panic in the specific nations that I didn't respond to instead of just +1.  I think this may depend on either a) the intensity of the attack or b) the panic level before the abduction took place.

Increase Panic

*

*Fail to stop a terror attack

*

*+1 (or 2?) panic in all nations on the continent which was attacked

*The attacked nation leaves the XCOM funding council instantly

*

*Fail any other type of mission

*

*I haven't actually had this happen yet, but at the least it has no benefit and probably increases panic further than just ignoring the mission would have.

I believe there are slight variations in a lot of these, and panic may even go up somewhat randomly in individual nations which weren't attacked.  My justification for this is that I often have individual nations which haven't been targeted by specific activity being at a higher panic level than the other nations on their continent.

Many of the events above aren't directly under the player's control.  The things that the player can affect are:

*

*When and in what nations you build satellites.

*

*It's actually "wasteful" on potential panic reduction to put up a satellite in a nation with less than 3 panic.  Consider this carefully.

*You may be better off waiting until near the end of the month to put up satellites.  Unless you're finishing coverage on a continent, you don't get any immediate benefit, and unless you fail a mission a nation won't leave the council (they leave if the report comes in and they're at 5 panic).  A nation that's at panic level 3+ might end up getting attacked, and you can reduce its panic level by responding to it.  If you had already put the satellite down you've lost that opportunity.

*You have to aggressively go after engineers and satellite uplinks to have enough satellites to keep everyone calm.  Putting your HQ in Africa for the 30% funding bonus helps in this.

*Funding from an affluent nation like the United States can provide as much as $120 MORE than the poorer nations, which is the cost of two satellites, so keep it in mind.

*When you do major combat missions like the alien base assault

*

*Seems advisable to save these for when you can really get a lot of use out of the panic reduction.

*Obviously you have to have gone through the main mission objectives to get to this point at all, which can be challenging as you're focusing on satellites.

*Which nation you respond to when abductions happen

*

*Can be a tough choice.  Engineers are really important.  Money is too.  And panic rises in the two continents you don't respond to.  Scientists and new soldiers are almost certainly bad choices in the first few months of the game.

A: You can place a satellite over them so you can have better coverage there (and to do missions there) or do some of the council missions, they sometimes reduce every country's panic.
UPDATE: Also after finishing major events (Shooting down first UFO and assaulting it, assaulting base, etc) you reduce global panic levels.

A: Any mission you do in India should lower the panic meter for India. This could be a council mission (bomb, abduction, etc) or a downed UFO.


text:
Q: Iphone accelerometer sampling frequency Some applications are available for measuring frequencies of alternating currents up to 200 Hz using magnetometers and designed for iPhones.
I collected data from Iphone 5s magnetometers and the minimum average value of the acquisition period I recorded was about 0,02 sec, in other words  the average sampling frequency was 50 Hz.
In my opinion and in this case, it's possible to measure only upto 25 Hz.
How is possible to measure alternating current up to 200 Hz?
Did I write something wrong?
Is there a trick to decrease the acqusition period?

A: Since the iPhone 6, Apple has actually included two separate accelerometers. It appears that one has a refresh rate of 2000hz, and the other is 4000hz.
Here's an article detailing the capabilities of the two chips.
http://www.macrumors.com/2014/09/26/iphone-6-6-plus-two-accelerometers/

A: Try experimenting with the CMMotionManager's property magnetometerUpdateInterval, which is in units of seconds. Like others have said: I'm not sure what the actual sensor's data frequency is, you could also run into energy issues with such a high call rate. Let us know how it goes, happy experimenting!


text:
Q: NHibernate QueryOver Subjective Where? So in SQL I can write a query like this:
SELECT
  A,
  B,
  C
FROM
  myTABLE
WHERE
  (@X is NULL OR A = @X) AND
  (@Y is NULL OR B = @Y) AND
  (@Z is NULL OR C = @Z)

in order create a single query that returns all entries if no filtering parameters are specified, or a subset if any of them are specified. But how would I go about doing this using Nhibernate's QueryOver? I'm not even fully sure how to do an OR with QueryOvery at all...

A: In order to subjectively query (based on the parameter), the accepted method would be to build the where clause in pieces as such:
var qry = session.QueryOver<obj>();
if (!String.IsNullOrEmpty(A)) { qry.Where(x => x.a == A); }
if (!String.IsNullOrEmpty(B)) { qry.Where(x => x.b == B); }
if (!String.IsNullOrEmpty(C)) { qry.Where(x => x.c == C); }
List<obj> data = qry.List<obj>().ToList();

So that the final result is the exact query to run for a given set of parameters, rather the generalized SQL query specified in the original post.


text:
Q: Matlab sort and get ranking of the oringal matrix Please help me find an efficient way (no for loop) to get the ranking for a matrix.
Example:
orig_matrix = [-1 2 nan 2 3 4 -2; 100 nan nan -100 300 1000 0]';
[matrix_sorted, id] = sort(orig_matrix ,1,'ascend');

I know 'id' is the location of the elements of  matrix_sorted in the orig_matrix. But I want to get the ranking of all elements in orig_matrix, something like this:
ranking = [2 3 7 4 5 6 1; 3 6 7 1 4 5 2]

Many thanks!

A: Simply adding to OmG's post, you can also specify which dimension to sort individually so you don't need to transpose:
[B, Result] = sort(orig_matrix, 2);

A: You can do it by a simple trick using transposing:
[B, I] = sort(orig_matrix.');
Result = I.';


text:
Q: Coldfusion 2021 Update 5 breaks xml I just applied update 5 and now I am getting XML errors:
"Error","ajp-nio-127.0.0.1-8020-exec-10","10/13/22","11:28:42","Medlists3","coldfusion.runtime.CFPage.XmlSearch(Lcoldfusion/xml/XmlNodeList;Ljava/lang/String;)Ljava/lang/Object;
https://helpx.adobe.com/coldfusion/kb/coldfusion-2021-update-5.html  says

CHANGE IN XML
If the XML path contains a forward slash or backslash, it will be
blocked. The flag, coldfusion.xml.allowPathCharacters, must be set to
true to allow the same.

But I don't know where to make this change.

A: This question was asked on CFML Slack and it was said that you needed to manually clear all .class files from disk since the bytecode is not binary compatible.

A: A legacy Fusebox 5 coldfusion application got this exact error. Following up on gabriel's note: after deleting the contents of cfclasses, I had to restart the Coldfusion 2021 Application in services (Windows Server 2019) in order for the contents of cfclasses to refresh. After the restart, the application worked as normal.

A: Adobe added the following comment for the patch notes for CF2018 Update 15, but they said that this shouldn't be an issue in ColdFusion 2021-
https://helpx.adobe.com/coldfusion/kb/coldfusion-2018-update-15.html
--
Known issues in this release
If you encounter the following error message, clear the classes in <CF_HOME>/instance/wwwroot/WEB-INF/cfclasses.
"coldfusion.runtime.CFPage.XmlSearch(Lcoldfusion/xml/XmlNodeList;Ljava/lang/String;)Ljava/lang/Object; The specific sequence of files included or processed is: \<filepath>, line: 34 "
java.lang.NoSuchMethodError: coldfusion.runtime.CFPage.XmlSearch(Lcoldfusion/xml/XmlNodeList;Ljava/lang/String;)Ljava/lang/Object;

*

*If the Uninstall button is disabled on Update 15, uninstall the
update using the uninstaller.jar present in the hf-updates folder.

*your application uses the functions XmlSearch and XmlTransform,
you'll have to recompile the files after applying Update 15.

--

A: I added the variable "-Dcoldfusion.xml.allowPathCharacters=true" in Java JVM arguments and it worked.

A: In your Coldfusion Administrator, under Server Settings, Java and JVM, in the JVM Arguments box, append the following to the end (make sure there is a space after the last entry:
-Dcoldfusion.xml.allowPathCharacters=true
Then restart the CF Service.
Took care of the problem for us.


text:
Q: how to Run spring Boot Application with out providing "spring.application.json" I have built a Spring Boot application with 2.1.3.BUILD-SNAPSHOT using an initializer. While running in eclipse getting JSON parse exception.
When I use the --spring.application.json={\"foo\":\"bar\"} argument on the command line, it works. How can I make it work without having to type that every time?`

4.0.0

org.springframework.boot
spring-boot-starter-parent
2.1.15.RELEASE

com.gktechtalks.blog
services
0.0.1-SNAPSHOT
services
GKTechTalks Blog Services
<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>false</optional>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

`
it is a brand new spring-boot project. Created from "https://start.spring.io/"
I imported the project into eclipse and ran Then I got below exception.
No configuration added from my side.
Got below exception
After then I have provided
--spring.application.json={\"foo\":\"bar\"}

Then Application starting without any exceptions. That is why I got a question why can't we run without that property in the command line.


text:
Q: MySQL query to search for items with parent items tag So I followed what they did here:
MySQL query to search for items with certain tags
But have an additional requirement, lets say we had the following data:
items:
id | item    | parent_id
------------------------
1  | banana  |  0
2  | orange  |  1
3  | tomato  |  0

items_tags:

id | item_id | tag_id
---------------------
1  | 1       | 1
2  | 1       | 2
3  | 2       | 3
4  | 3       | 4

tags:

id | tag
--------------
1  | yellow
2  | fruit
3  | orange
4  | red

I am looking to run a search for items that are tagged with id 2 (fruit) and am expecting to return back item banana and orange. First is this the best way to store the information and if so what would be the most efficient query I can run to get back banana and its child orange.
Thanks

A: A better way to store the data could be to remove the redundant columns from item_tags table (normalization):
items:
id | item    | parent_id
------------------------
1  | banana  |  0
2  | orange  |  1
3  | tomato  |  0

items_tags:

item_id | tag_id
------------------
1       | 1
1       | 2
2       | 3
3       | 4

tags:

id | tag
--------------
1  | yellow
2  | fruit
3  | orange
4  | red

Then your query to get the fruits, bringing only the items directly connected with the "fruit" tag, could be:
select items.id, items.item from items
inner join item_tags on (items.id=item_id)
inner join tags on (tags.id=tag_id)
where tag = 'fruit'

To include also items connected by parent:
select items.id, items.item from items
inner join items parents on (parents.id=items.parent_id)
inner join item_tags on (item_id=items.id OR item_id=parents.id )
inner join tags on (tags.id=tag_id)
where tag = 'fruit'


text:
Q: Installing older version of gcc I want to install gcc 4.1.2 on my Ubuntu 64 bit system, which currentcly has gcc 4.4. I want to keep on using the current gcc, but want to add gcc 4.1.2 as well. Any simple way to do it, that is install gcc 4.1.2 on my system?

A: Easy, just take it from an archive of the older Ubuntu releases. For example, my machine (still running natty) has
edd@max:~$ ls -l /usr/bin/g++-*
-rwxr-xr-x 1 root root 242752 2010-09-10 04:16 /usr/bin/g++-4.3
-rwxr-xr-x 1 root root 263240 2011-03-31 15:22 /usr/bin/g++-4.4
-rwxr-xr-x 1 root root 275856 2011-04-18 09:25 /usr/bin/g++-4.5
edd@max:~$

The 4.1.* series had some issues.  Even g++-4.2.1, the default on OS X, is not all that great.   But you should definitely have the option of installing this.
When you do this, by all means go the package management route of installing proper dependencies.  You will get matching packages for the other dependencies too.
In other words, you need to adjust /etc/apt/sources.list to point to an older release that had this version.

A: sudo apt-get install gcc-4.1=4.1.2 gcc-4.4

seems the straightforward solution to me. Since @DirkEddelbuettel noted that newer Ubuntu distributions dropped it, add an older distribution that has gcc-4.1 to your /etc/apt/sources.list. The Ubuntu people maintain a great website for looking that up; hardy, lucid and maverick seem great.

A: This should do :
sudo apt-get install gcc-4.1=4.1.2-27ubuntu1 gcc-4.1-base=4.1.2-27ubuntu1 cpp-4.1=4.1.2-27ubuntu1 g++-4.1

Other way is to download gcc 4.1.2 and dependent libraries, and compile it yourself.

A: Once installed see others:
Use the -V flag to run a particular version:
-V <version>             Run gcc version number <version>, if installed


text:
Q: findOne deosn't work, i change to findById but i got a problem in return type i got an error in return type cp:Type mismatch: cannot convert from Optional to Compte
this is in spring boot using eclipse
''Java
@Service
@Transactional
public class BanqueMetierImpl implements IBanqueMetier{
@Autowired
 private COmpteRepository compteRepository;
 @Override
  public Compte ConsulterCompte(String codeCpte){
  Optional<Compte> cp=compteRepository.findById(codeCpte);
  if(cp==null)throw new RuntimeException("Compte Introuvable");
   return cp;

i'm trying to use findOne but doesn't work, so i use findById when did that i got an error in return type cp;

A: This code should works.
return cp.orElseThrow(()-> new RuntimeException("Compte Introuvable"));

I recommend you take a look at this guide to understand how Optional works.

A: Newer Spring Data versions use findById instead of findOne and instead of returning null it now returns an Optional. It will never return null but rather an Optional.empty() instead.
Rewrite your code to properly use the Optional
@Override
public Compte ConsulterCompte(String codeCpte) {
  return compteRepository.findById(codeCpte)
           .orElseThrow(() -> new RuntimeException("Compte Introuvable"));
}

Also you probably shouldn't be throwing a general RuntimeException but a more specific one.


text:
Q: React Project Directory created in an Express.js Directory I'm relatively new to Node.js and wanted to make a Crud Application using the MERN stack. Working on the backend has gone really well and I've had no problems working with express or mongo.
Recently I tried to create a react app in the project. I'm working on a small team using github so for simplicity I put all of the express files into a folder called backend and wanted to put the react files in the same repository. I ran npx create-react-app frontend within the express app directory and now I have new copies of node_modules, .gitignore, package-lock.json, and package.json within the frontend folder.
This has caused some confusion because now I have some overlapping dependencies, so I'm not sure if that will cause any issues. Also for people to update 2 different node_modules folders on local they need to run npm i in both directories.
I'm mainly just curious as to what the industry standard is here. Does it make sense to keep it how it is? Is there a way I can combine the package.json files, node_module folders and .gitignore files. Or was trying to combine repositories a mistake and I should keep the repositories seperate?
I've also never deployed a web app with a back-end which I intend to do for this project, will any of these options affect the deployment process as well?

A: open your main folder in your terminal and then execute this command:
npx create-react-app frontend  # this is your client side folder name with react


text:
Q: Renaming dependent library in Android NDK causes UnsatisfiedLinkError I'm developing an android app using Android NDK. The JNI layer of app depends on a shared library 'libDependentLib.so'. My android.mk looks like:
LOCAL_PATH := $(call my-dir)
include $(call all-subdir-makefiles)
include $(CLEAR_VARS)
TARGET_PLATFORM := 'android-10'
LOCAL_CPP_EXTENSION := .cpp
LOCAL_CPPFLAGS += -fno-exceptions -fno-rtti
MY_LOCAL_PATH := $(LOCAL_PATH)/../
LOCAL_LDLIBS := -L$(call host-path, $(MY_LOCAL_PATH)/libs) -lDependentLib
LOCAL_C_INCLUDES := $(MY_LOCAL_PATH)/include-all $(MY_LOCAL_PATH)/include
MY_FILES := abc.cpp xyz.cpp
LOCAL_LDLIBS    += -lm -llog  -lstdc++
LOCAL_SRC_FILES += $(MY_FILES)
LOCAL_MODULE    := jniLayer
include $(BUILD_SHARED_LIBRARY)

My directory structure for libs is:
<Android_Project>
       |
     libs----armeabi-----libjniLayer.so
       |       |---------libstlport_shared.so
       |-----------------libDependentLib.so

Every time I copy libDependentLib.so to armeabi before running the app. Loading of libs is done as:
static {
    try {
        /* loading the libraries */
        System.loadLibrary("stlport_shared");
        System.loadLibrary("DependentLib");
        System.loadLibrary("jniLayer");
    } catch (Throwable th) {
        th.printStackTrace();
    }
}

This runs fine. But due to some requirement, I'm forced to change the external lib name to DependentLib_1. I renamed the same in Android.mk, while loading libs in java and the library name in AndroidProject. But the application fails at System.loadLibrary("jniLayer"); saying
java.lang.UnsatisfiedLinkError: Cannot load library: link_image[1966]:88 could not load needed library 'libDependentLib.so' for 'libjniLayer.so'    (load_library[1108]: Library 'libDependentLib.so' not found)

I'm not able to figure out why still libDependentLib.so is being searched for. I've renamed everything to libDependentLib_1.so. So the same should be looked for. Apart from Andorid.mk and jni loading where libDependentLib.so is being referenced?
Note:Android project contains the new lib

A: Does your libjniLayer.so is dependent on libDependentLib.so? If so you can't rename libDependentLib.so because when libjniLayer.so is built linker puts name of the dependent .so (libDependentLib.so) in the object code. So if you rename libDepenedentLib.so, jniLayer.so will still be looking for libDependentLib.so.


text:
Q: Access the replied/forwarded/etc state from REST I am trying to get and set the forwarded/replied state of an email message in the Graph API. This is the represented in OWA by the little icon in the right column.
It seems there is not a first class way to access this information, at least it does not come out in the unfiltered JSON dump.
Google suggests this is stored in the extended properties for PidTagLastVerbExecuted or PidTagIconIndex, however attempts to access these just give back 404:
https://graph.microsoft.com/beta/me/mailFolders/{id}/messages?$select=SingleValueExtendedProperties&$expand=SingleValueExtendedProperties($filter%3Did+eq+'String+0x1081')

Other extended properties like 0x0070 do work, so it seems the syntax is correct, and 0x1081 comes from here https://learn.microsoft.com/en-us/office/client-developer/outlook/mapi/pidtaglastverbexecuted-canonical-property
This information is stored, you can see it in OWA, the Outlook apps, and you can see it in IMAP.
Is there some way to do this? It seems strange this basic information about the email state is not made available.

A: Your specifying the wrong datatype that property is defined as a Long in the documentation (but the doco is for MAPI) so its actually an Integer in EWS and Graph eg this is something i used to return both PidTagLastVerbExecuted  and PidTagLastVerbExecutedTime (which gives you the time of the last action)for a particular message
/v1.0/users('user@domaincom')/MailFolders/AllItems/messages/?$select=ReceivedDateTime,Sender,Subject,IsRead,inferenceClassification,InternetMessageId,parentFolderId,hasAttachments,webLink,InternetMessageHeaders&$Top=1000&$filter=internetMessageId+eq+%27%3cSG2PR04MB3223962312D5B46D0C9CA1B5C89C0%40SG2PR04MB3223.apcprd04.prod.outlook.com%3e%27&$expand=SingleValueExtendedProperties($filter=(Id%20eq%20'Integer%200x1081')%20or%20(Id%20eq%20'SystemTime%200x1082'))


text:
Q: Azure Fluent API - AppServicePlanOperations.ListMetricsWithHttpMessagesAsync Returns InternalServerError The documentation for this method can be found here
Here is my code:
        var appServiceManager = AppServiceManager.Authenticate(credentials, subscriptionId);
        var filter = "(name.value eq 'CpuPercentage') and startTime eq '2017-10-06T08:00:00Z' and endTime eq '2017-10-06T09:00:00Z' and timeGrain eq duration'PT1H'";
        var metrics = appServiceManager.AppServicePlans.Inner.ListMetricsWithHttpMessagesAsync("myResourceGroupName", "myAppServicePlanName", false, filter).Result;

This is the only detailed exception I get:

One or more errors occurred. (Operation returned an invalid status code 'InternalServerError') ---> Microsoft.Rest.Azure.CloudException: Operation returned an invalid status code 'InternalServerError'

The documentation says that filter is optional, which it's not (I get a BadRequest if I pass in null). I'm now providing one and now it throws an internal server error.
I've opened an issue on the azure-sdk-for-net repo but I'm hoping someone else can see if I'm making any mistakes in my filter string.

A: I also can reproduce this issue on my side when using the code you mentioned. I find another Microsoft.Azure.Management.Monitor.Fluent SDK could be used for list the metrics of the resource, it is a beta version. I do a demo on my side, it works correctly on my side.
using Microsoft.Azure.Management.Fluent.ServiceBus;
using Microsoft.Azure.Management.Fluent.ServiceBus.Models;
using Microsoft.Rest.Azure.Authentication;
using Microsoft.Rest.Azure.OData;

namespace MonitorDemo
{
    class Program
    {
        static void Main(string[] args)
        {

            var azureTenantId = "tenant Id";
            var azureSecretKey = "secret key";
            var azureAppId = "azure AD application Id";
            var subscriptionId = "subscription Id";
            var resourceGroup = "resource group name";
            var servicePlanName = "service plan name";
            var serviceCreds = ApplicationTokenProvider.LoginSilentAsync(azureTenantId, azureAppId, azureSecretKey).Result;
            MonitorClient monitorClient = new MonitorClient(serviceCreds) { SubscriptionId = subscriptionId };
            var resourceUri = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Web/serverfarms/{servicePlanName}"; // resource id
            var metricNames = "name.value eq 'CpuPercentage'"; // could be concatenated with " or name.value eq '<another name>'" ... inside parentheses for more than one name.

            // The $filter can include time grain, which is optional when metricNames is present. The is forms a conjunction with the list of metric names described above.
            string timeGrain = " and timeGrain eq duration'PT5M'";

            // The $filter can also include a time range for the query; also a conjunction with the list of metrics and/or the time grain. Defaulting to 3 hours before the time of execution for these datetimes
            string startDate = " and startTime eq 2017-10-06T08:00:00Z";
            string endDate = " and endTime eq 2017-10-06T09:00:00Z";

            var odataFilterMetrics = new ODataQuery<MetricInner>(
                $"{metricNames}{timeGrain}{startDate}{endDate}");

            var metrics = monitorClient.Metrics.ListWithHttpMessagesAsync(resourceUri, odataFilterMetrics).Result;
        }
    }
}

packages.config
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.Azure.Management.Monitor.Fluent" version="1.3.0-beta" targetFramework="net47" />
  <package id="Microsoft.Azure.Management.ResourceManager.Fluent" version="1.3.0" targetFramework="net47" />
  <package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="2.28.3" targetFramework="net47" />
  <package id="Microsoft.Rest.ClientRuntime" version="2.3.9" targetFramework="net47" />
  <package id="Microsoft.Rest.ClientRuntime.Azure" version="3.3.10" targetFramework="net47" />
  <package id="Microsoft.Rest.ClientRuntime.Azure.Authentication" version="2.3.1" targetFramework="net47" />
  <package id="Newtonsoft.Json" version="6.0.8" targetFramework="net47" />
</packages>


text:
Q: Can't pass the chosen data from the table rows in the modal to the parent view I have a checkbox which whenever i check it, a modal popup will appear.
<input type="checkbox" name="inputNewBornKMC" value="inputNewBornKMC" id="inputNewBornKMCCheckbox"> New Born

I have no trouble loading the modal and doing a search query inside it, but i'm having a problem to pass the chosen data from the table rows in the modal to the parent view.
$('#inputNewBornKMCCheckbox').on('change', function (e) {
        var _this = $(this);

        // if checked
        if (_this.is(':checked')) {
            $('#inputNewBornKMC').modal('show');

        $("#SearchMother").on('click', function () {
                $.ajax({
                    url: '/consultation/GetMothersDetailList',
                    type: 'GET',
                    data: $('#frmSearchMother').serialize(), // it will serialize the form data
                    dataType: 'json',
                    success: function (data) {
                        $('.firstDL').remove();
                        $('.subsequentPL').remove();

                        var rowNo = 0;
                        for (var i = 0; i < data.length; i++) {
                            rowNo += 1;
                            $("#LoadMotherDetailsTable tbody").append("
" +
                                        "" + rowNo + "	" +
                                        "" + data[i].paid + "	" +
                                        "" + data[i].pidno + "	" +
                                        "" + data[i].pname + "	" +
                                        "<button type='button' class='select btn btn-default' data-paid='" + data[i].paid + "'>Select</button>	" +
                            "
");
                        }

                        alert('LoadMotherDetailsTable list has been loaded.');

                    },
                    error: function () {
                        alert('Ajax Submit Failed ...');
                    }
                }); // end ajax

            });

            var baseUrl = '@Url.Action("GetMotherDetails", "consultation")';
            $("#LoadMotherDetailsTable tbody").on('click', '.select', function () {

                $.getJSON(baseUrl, { paid: $(this).data('paid') }, function (data) {

                    document.getElementById('#inputMotherMRN').style.display = 'block';
                    document.getElementById('#inputMotherMRNlabel').style.display = 'block';
                    $('#inputMotherMRN').val(data.paid);
                    $('#inputMotherName').val(data.pname);
                    $('#inputNewBornKMC').modal('hide');

                });
            });
}

Supposedly, after i click on the select button in the table row, the modal will hide, a label and a textbox will appear and the concerned data will be displayed in the label and textbox in the parent page.
But the modal won't close, the textbox and label won't appear and the data aren't passed either. Why is this happening? Could anyone lend me a hand please?
UPDATE
$.getJSON(baseUrl, { paid: $(this).data('paid') }, function (data) {

                    $('#inputMotherMRN').val(data.paid);
                    $('#inputMotherName').val(data.pname);
                });

document.getElementById('#inputMotherMRN').style.display = 'block';
document.getElementById('#inputMotherMRNlabel').style.display = 'block';
$('#inputNewBornKMC').modal('hide');

The data is passed but the modal won't close and the hidden textbox and label does not appear. When i check the debugger console, even after the line is moved, the problem seems to be still this document.getElementById('#inputMotherMRN').style.display = 'block'; specific line.
This is the hidden textbox and label:
Mother's MRN

     <input type="text" class="form-control input-sm" id="inputMotherMRN" name="inputMotherMRN" style="display:none" readonly>


text:
Q: get vocabulary id by name I can retrieve a vocabulary id directly from DB,
but is there a built in function for this?
for example:
i have a vocabulary called "listing",
i need that built in function takes "listing" as function argument, and return
a vid.
i am using drupal 6

A: There is no built in function for this, afaik. You can roll your own by calling taxonomy_get_vocabularies() and search for your name in the resulting array, but this will do a database request on every call.
If you have a vocabulary that you often use from code, it might be easier/more effective to store the vid in a Drupal variable via variable_set() once and get it back via variable_get() (Many modules that create a vocabulary on install do it this way).
Edit: here is some sample code to do this on module install.
function mymodule_install() {
  $ret = array();
  $vocabulary = array(
      'name' => t('myvocab'),
      'multiple' => '1',
      'required' => '0',
      'hierarchy' => '1',
      'relations' => '0',
      'module' => 'mymodule',
      'nodes' => array('article' => 1),
    );
  taxonomy_save_vocabulary($vocabulary);
  $vid = $vocabulary['vid'];
  variable_set('mymodule_myvocab', $vid);
  return $ret
 }

A: Should help.
function _my_module_vid($name) {
  $names = taxonomy_vocabulary_get_names();
  return $names[$name]->vid;
}

A: I have a function for this, well almost..
 /**
 * This function will return a vocabulary object which matches the
 * given name. Will return null if no such vocabulary exists.
 *
 * @param String $vocabulary_name
 *   This is the name of the section which is required
 * @return Object
 *   This is the vocabulary object with the name
 *   or null if no such vocabulary exists
 */
function mymodule_get_vocabulary_by_name($vocabulary_name) {
  $vocabs = taxonomy_get_vocabularies(NULL);
  foreach ($vocabs as $vocab_object) {
    if ($vocab_object->name == $vocabulary_name) {
      return $vocab_object;
    }
  }
  return NULL;
}

If you want the vid just get the vid property of the returned object and.
$vocab_object = mymodule_get_vocabulary_by_name("listing");
$my_vid = $vocab_object->vid;

Henriks point about storing it in a variable is very valid as the above code you won't want to be running on every request.
Edit
Also worth noting that in Drupal 7 you can use taxonomy_vocabulary_get_names() which makes this a little easier.

A: For Drupal 7 if you know the vocabulary machine name this is the way:
$vid = taxonomy_vocabulary_machine_name_load('your_vocabulary_name')->vid;

If you know only the Real name of vocabulary, you can use this function:
function _get_vocabulary_by_name($vocabulary_name) {
  // Get vocabulary by vocabulary name.
  $query = db_select('taxonomy_vocabulary', 'tv');
  $query->fields('tv', [
    'machine_name',
    'vid',
  ]);
  $query->condition('tv.name', $vocabulary_name, '=');
  $vocabulary = $query->execute()->fetchObject();
  return $vocabulary;
}

A: You know the node type to which the vocaulbary is associated. So just use taxonomy_get_vocabularies() and pass the node type as argument and you will get the details you want!

A: In Drupal 7 you could use:
$vocab_object = taxonomy_vocabulary_machine_name_load('vocabulary_name');
$my_vid = $vocab_object->vid;


text:
Q: Converting date timestamp from 12 hour into 24 using awk I am working with a csv file which contains data in the following structure:
"12345","BLAH","DEDA","0.000","1.111","2.22222","3.3333333,"15/12/2017 4:26:00 PM"

I want to convert the 12 hour time into 24 hour time.
The following shows what I am trying to achieve in the end:
"12345","BLAH","DEDA","0.000","1.111","2.22222","3.3333333,"15/12/2017 16:26:00"

I found the following answer to a question which seems to solve the conversion of the time segment of my problem.
https://stackoverflow.com/questions/8083973/bash-and-awk-converting-a-field-from-12-hour-to-24-hour-clock-time#8084087
So with the above, I believe I must do the following process (There is probably a more efficient method):

*

*Temporarily separate the date and time into there own records
"12345","BLAH","DEDA","0.000","1.111","2.22222","3.3333333,"15/12/2017","4:26:00 PM"

*Target the time record and convert it into my desired 24 hour format

*Concatenate the date and time records back into a single record

I am trying to achieve this using awk and am stuck on the first section! Is awk to right tool for this job, or would you recommend a different tool?
I'm starting with step 1. I can't even successfully target the date!
awk 'BEGIN {FS=","} { gsub(/[0-9]\{2\}\/[0-9]\{2\}\/[0-9]\{4\}/, "TESTING"); print }' myfile.csv

A: I'd use perl here:
perl -pe 's{\b(\d{1,2})(:\d\d:\d\d) ([AP])M\b}{
  $1 + 12 * (($3 eq "P") - ($1 == 12)) . $2}ge'

That is add 12 to the hour part if PM (except for 12PM) and change 12AM to 0.
With awk, not doing the word-boundary part (so could give false positives on 123:21:99 AMERICA for instance) and assuming there's only one occurrence per line:
awk '
  match($0, /[0-9]{1,2}:[0-9]{2}:[0-9]{2} [AP]M/) {
    split(substr($0, RSTART, RLENGTH), parts, /[: ]/)
    if (parts[4] == "PM" && parts[1] != 12) parts[1] += 12
    if (parts[4] == "AM" && parts[1] == 12) parts[1] = 0

    $0 = substr($0, 1, RSTART - 1) \
         parts[1] ":" parts[2] ":" parts[3] \
         substr($0, RSTART + RLENGTH)
  }
  {print}'

A: This solution converts all items of the 12-hour format to the 24-hour format in each line.
gawk -F, '
{
    for(i = 1; i <= NF; i++) {
        if($i ~ /:[0-9]{2} [PA]M/) {
            split($i, arr, ":| ")

            if(arr[5] ~ /P/)
                arr[2] += 12

            $i = sprintf("%s %02d:%02d:%02d\"", arr[1], arr[2], arr[3], arr[4])
        }
    }
    print
}' OFS=, input.txt

Input
"12345","BLAH","DEDA","0.000","1.111","2.22222","3.3333333","15/12/2017 4:26:00 PM"
"22345","BLAH","DEDA","0.000","1.111","2.22222","3.3333333","16/12/2017 6:26:00 AM"
"32345","BLAH","DEDA","0.000","1.111","2.22222","3.3333333","17/12/2017 10:00:00 PM"
"42345","BLAH","DEDA","0.000","1.111","2.22222","3.3333333","18/12/2017 11:26:00 AM"
"52345","BLAH","DEDA","0.000","1.111","2.22222","3.3333333","19/12/2017 2:26:00 PM"

Output
"12345","BLAH","DEDA","0.000","1.111","2.22222","3.3333333","15/12/2017 16:26:00"
"22345","BLAH","DEDA","0.000","1.111","2.22222","3.3333333","16/12/2017 06:26:00"
"32345","BLAH","DEDA","0.000","1.111","2.22222","3.3333333","17/12/2017 22:00:00"
"42345","BLAH","DEDA","0.000","1.111","2.22222","3.3333333","18/12/2017 11:26:00"
"52345","BLAH","DEDA","0.000","1.111","2.22222","3.3333333","19/12/2017 14:26:00"


text:
Q: OPENUI5 Project MVC + Node.js I do structure the project OpenUI5 MVC structure with node.js as following:

My App.js file:

My index.html file:

However, it always produces the following error:

[ERROR] XML Parsing Error: mismatched tag. Expected: </meta>.
        Location: http://localhost:1024/
        Line Number 6, Column 3:

[ERROR] Error: resource sap/ui/demo/walkthrough/view/App.view.xml could not be loaded from ./view/App.view.xml. Check for 'file not found' or parse errors. Reason: Not Found

If I try to move the "view" folder into the "public" folder ==> the project works well. I don't know what causes the issue above. Any assistance in clarifying this error is greatly appreciated.

A: As you set with app.use(express.static('public') the access path to the root path (/), all static file loads (to which the UI5 source files belongs to) are redirected to /public. W/o having the files in the /public folder you get a load failure.
If you wanna have a specific path which you can use in your app to the static file content, than you can define a mounting path, e.g. app.use('/static', express.static('public').


text:
Q: Fetch Post Method Empty upon arrival at API I am trying to send a web-push subscription object to my API, which consists of 'endpoint' and 'keys'.
The problem I seem to be having is when this object reaches my API it has the 'Keys' values but the 'endpoint' value is null. Yet when I debug it I can confirm that the endpoint value is defined.
This is the JS code I am using:
async function Subscribe() {
        let sw = await navigator.serviceWorker.ready;
        let push = await sw.pushManager.subscribe({
            userVisibleOnly: true,
            applicationServerKey:
                'ApplicationServerKeyHere'
        });
        console.log(JSON.stringify(push)); //Store this in DB

        fetch("https://localhost:44325/Subscribe", {
            method: "POST",
            //credentials: "same-origin", // include, *same-origin, omit
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(push)
        });
    }

endpoint is populated before the Fetch POST is sent:

And then empty when it arrives at the API:

A: The incoming JSON has 'endpoint' as field while your DOTNET model class as 'enpoint' as field (mismatch in field names in json-payload and model class that will accept the json payload)


text:
Q: Deploying multiple VM's with ansible I'm learning ansible to create Linux VM's on azure and I used this sample playbook in this link (https://learn.microsoft.com/en-us/azure/developer/ansible/vm-configure?tabs=ansible) to create one VM on azure.  If I want to deploy 10  VM's exactly like this with ansible-playbook how should I do it? Please help. Thanks in advance
Update: I tried it like this but the script fails after creating two public IP addresses.
- name: Create Azure VM
  hosts: localhost
  connection: local
  tasks:
  - name: Create resource group to hold VM
    azure_rm_resourcegroup:
      name: TestingResource
      location: eastus
  - name: Create virtual network
    azure_rm_virtualnetwork:
      resource_group: TestingResource
      name: testingvnet
      address_prefixes: "10.0.0.0/16"
  - name: Add subnet
    azure_rm_subnet:
      resource_group: TestingResource
      name: testingsubnet
      address_prefix: "10.0.1.0/24"
      virtual_network: testingvnet
  - name: Create public IP address
    azure_rm_publicipaddress:
      resource_group: TestingResource
      allocation_method: Static
      name: "{{ item }}" #CHANGE HERE
    loop:
       - testingpublicIP2
       - testingpublicIP3
    register: output_ip_address
  #- name: Dump public IP for VM which will be created
    #debug:
      #msg: "The public IP is {{ output_ip_address.state.ip_address }}."
  - name: Create Network Security Group that allows SSH
    azure_rm_securitygroup:
      resource_group: TestingResource
      name: TestingSecurityGroup
      rules:
        - name: SSH
          protocol: Tcp
          destination_port_range: 22
          access: Allow
          priority: 1001
          direction: Inbound
  - name: Create virtual network interface card
    azure_rm_networkinterface:
      resource_group: TestingResource
      name: "{{ item }}" #CHANGE HERE
      loop:
         - TestingNIC2
         - TestingNIC3
      virtual_network: testingvnet
      subnet: testingsubnet
      public_ip_name: "{{ item }}" #CHANGE HERE
      loop:
        - testingpublicIP2
        - testingpublicIP3
      security_group: TestingSecurityGroup
  - name: Create VM
    azure_rm_virtualmachine:
      resource_group: TestingResource
      name: "{{ item }}" #CHANGE HERE VM NAME
      loop:
        - TestingResource2
        - TestingResource3
      vm_size: Standard_B2s
      admin_username: admin
      admin_password: password@123
      ssh_password_enabled: true
      network_interfaces: "{{ item }}" #CHANGE HERE
      loop:
         - TestingNIC2
         - TestingNIC3
      image:
        offer: UbuntuServer
        publisher: Canonical
        sku: '18.04-LTS'
        version: latest

A: You can use the loops function to create multiple VMs through ansible as you showed in the question, but you'd better use a list variable to loop so that you don't need to write all the elements every time. And the variables also can be used for other things like resource group name, location, and so on that use multiple times in the code. Here is the example:
- hosts: localhost
  vars:
    resource_group: myResourceGroup
    ...
  tasks:
  - name: Create resource group to hold VM
    azure_rm_resourcegroup:
      name: "{{ resource_group }}"
      location: eastus
  ...

And the variable for the loop:
loop: "{{ var_list }}"

A: I found out it's quite easy with terraform to deploy multiple VM's on azure just by changing one variable in the configuration file, Here's the configuration file that i used (https://github.com/RichardPhilipsRoy/terraform-azure-linuxVMs)


text:
Q: R boxplot frequency I'm in need of assistance... I'm using R to analyze some data... I have a frequency table called mytable... that I created like this:
mytable=table(cut(var1,12),cut(var2,12))

the table looks something like this:
       1-2  2-3  3-4
1-3     2    1    2
3-6     0    1    4
6-9     7    1    8

except is a 12 by 12 table.
I used boxplot.matrix(mytable),the boxplot looks ok... with the 12 boxes corresponding to my 12 stratums, but my boxplot has the frequency as the y-axis and I want the y-axis to be the values from var1, how can I do this?
I wanted to post a pic... but my rep wasnt high enough

A: use boxplot before you summarize your data.
boxplot(var1)

If you want to see the distribution per split, use the formula format:
boxplot(var1 ~ cut(var2, 12))


text:
Q: Unable to Authenticate googleCloudStorageR/googleAuthR I am trying to authenticate gcs in R using googleCloudStorageR and googleAuthR.
I have all the necessary APIs enabled on gcp.
I am able to authenticate with bigrquery when i run query_exec(sql,project,use_legacy_sql = FALSE), the browser opens up, the token is cached and everything works fine.
But when i try to do the same with googlecloudstorageR gcs_auth() or gar_auth() with googleAuthR. I keep getting the following error.
Error: option('googleAuthR.client_id') has not been set
I do not right now have permissions to create credentials from the API page. But i do not understand why i can auth bigrquery without having to do any of this but not googlecloudstorage through gcs_auth or gar_auth.
Also can i use the same client id and secret from the bigrquery .httr/oauth file to auth googlecloudstorage by changing the scope ?
Edit:
I am using it at work, so i do not have privileges to create credentials from the https://console.cloud.google.com/apis/credentials page.
Code:
library(bigrquery)

project <- "mtproject"
sql <- "SELECT * FROM `myproject.Superstore.orders`"
data <- query_exec(sql,myproject,use_legacy_sql = FALSE)

When i run the above code, the browser opens up and gives me a token which i then copy and paste into R.
But when i try to authenticate using the following code for googleAuthR, nothing happens and i get the error.
library(googleAuthR)
2019-05-21 14:10:34> No environment argument found, looked in GAR_AUTH_FILE
Warning message:
package 'googleAuthR' was built under R version 3.5.3
> gar_auth(new_user=TRUE)
Error: option('googleAuthR.client_id') has not been set

I did not set any client id for bigquery auth but that works, why is gar_auth not working ?

A: The option"googleAuthR.client_id" and "googleAuthR.client_secret" are changed by loading another library or setting them in a script, and then a cache file is used with different options set.
If you are always going to use the same credentials, make use of the auto authentication options by creating a cache token, moving it to a dedicated auth folder and using environment variables GAR_AUTH or package supported ones.
You can get more info in the following link: https://code.markedmondson.me/googleAuthR/articles/troubleshooting.html


text:
Q: append content with attributes to newly created content in jquery Objective:

jquery code:
 $('
', {id: 'g_'+ e.GID, class: 'grp'})
    .append($(''), {id: 'g_i_'+ e.GID, class: 'grp_icon'})
    .append($(''), {id: 'g_mng_'+ e.GID, class: 'grp_name'})
    .append($(''), {id: 'g_des_'+ e.GID, class: 'grp_des'})
    .append($(''), {id: 'g_lock_'+ e.GID, class: 'grp_lock'})
    .append($(''), {id: 'g_vis_'+ e.GID, class: 'grp_vis'})

result:

Why are the id and class attributes being created for the parent element, but not for the child elements, however the child elements are being created??

A: The object with the attributes should be in the arguments to $() that create that element. .append() doesn't take an attributes argument, it just takes the elements to append.

var e = {GID: 1};
var div = $('
', {id: 'g_'+ e.GID, "class": 'grp'})
    .append($('', {id: 'g_i_'+ e.GID, "class": 'grp_icon'}))
    .append($('', {id: 'g_mng_'+ e.GID, "class": 'grp_name'}))
    .append($('', {id: 'g_des_'+ e.GID, "class": 'grp_des'}))
    .append($('', {id: 'g_lock_'+ e.GID, "class": 'grp_lock'}))
    .append($('', {id: 'g_vis_'+ e.GID, "class": 'grp_vis'}));
console.log(div[0].outerHTML);

Also, you should quote class when using it as a property name. class is a Javascript keyword, and some browsers will report a syntax error if you don't quote it.


text:
Q: Java regex contained within How can I write a regex to see if a certain string is contained within two characters.
For example, I want to see which part of the string is contained within a quotation mark.
Java"_virtual_"machine

If I run my regex through this, I want to get _virtual_
How can I achieve this using regexes?

A: Supposing the text contains only one such pair of characters and there are no escaping tricks or so, you can use this regex
.*"([^"]*)".*

Try it online

A: I wouldn't do it with regex but with method which finds first and second occurrence of a character so it's more flexible to use in the
String s = "Java\"_virtual_\"machine";
String find = "\"";
int first = s.indexOf(find) + 1;
int second = s.indexOf(find, s.indexOf(find) + 1);
s.substring(first, second);

You can reuse this code on other characters and I bet it's faster than regex.

A: You can use this regex. I'm not sure if this is the best regex you can use though. It will capture every string between quotes.
.*?"([^"]*)"

Demo here
If you want to get the first string that matches the regex, use :
.*?"([^"]*)".*


text:
Q: What is the smartest way of styling a wrapper, but not propagate the styles to the children element? How do I style .parent with color redwithout styling .child?
One solution would be to overwrite the child element style, but in the real world scenario, the child element will have many complex styles and I do not want to touch them, or overwrite these styles, it would be very risky.
What I want is to add the styles only to the wrapper element. In the real world these two elements will be
 elements

        Parent

child - don't style me

A: This is how I solved it:
https://developer.mozilla.org/en-US/docs/Web/CSS/all
.wrapper {
  color: red;
}

.child {
  all: initial;
}

There are other variants, such as revert-layer
This may be the best way to not inherit styles from specific cascade style layers without having to depend/know what are these styles to avoid having them overridden.
Working example: https://codesandbox.io/s/sharp-goldstine-9hongm?file=/src/App.js

A: In case you want to reset the property in child, you can use unset.
Eg:
.parent {
  color: red;
}

.child {
  color: unset;
}


text:
Q: Can't see keychain passwords on another mac I am syncing one of my keychains over Google Drive. Unfortunately things which I add on Snow Leopard I am unable to see on Mountain Lion.

*

*Is it some common issue, which could be easily fixed?

*Or can I fix it at least as make it visible on Mountain Lion?

I am syncing the keychains over Google Drive. I've considered the problem could be in the way Google Drive is syncing that, but it also happens when I copy it over Samba and replace the keychain on another machine.

A: A lot of processes will keep the keychain open, and may not realize that it has been replaced by another keychain.  For example, right now I have
sudo lsof login.keychain
Password:
COMMAND     PID USER   FD   TYPE DEVICE SIZE/OFF     NODE NAME
CalendarA   500  ats  txt    REG    1,4   753764 14974132 login.keychain
ubd         949  ats  txt    REG    1,4   753764 14974132 login.keychain
Dashboard  8779  ats  txt    REG    1,4   753764 14974132 login.keychain
Safari    29631  ats  txt    REG    1,4   753764 14974132 login.keychain
NetAuthSy 29809  ats  txt    REG    1,4   753764 14974132 login.keychain
WebProces 29823  ats  txt    REG    1,4   753764 14974132 login.keychain

You may need to restart things when you replace the keychain, or make sure only to sync the keychain when logged out.  (Which won't work well with dropbox.)
You might want to investigate something else like Keychain2Go which knows about the contents of keychains and makes sure to sync in a fashion that works while other things have it open.

A: Sounds like your Mac has permissions issues.  WHile the transfer through Google Drive would strip the permissions like using an external drive would, it's not working, causing things not to properly be transferred.  I would start with repairing permissions on the transfer FROM mac.  Then verify the permissions are stripped when its on the new machine.


text:
Q: Letra ç no editor do VS Code O cedilha "ç" sumiu no Visual Studio Code que utilizo no MacBook. Isso aconteceu faz algum tempo após uma atualização. Funciona em qualquer editor menos no VS Code.
Alguém ja passou por isso?

A: Vá em: ( Preferences/Keyboard Shortcuts ) e ao abrir a aba de configurações de teclas, abaixo do campo de pesquisa tem a opção de abrir em modo avançado o arquivo (keybindings.json) e edite-o adicionando o objeto abaixo:
[
    {
        "key": "alt+c",
        "command": "-task.cancel",
        "when": "editorTextFocus"
    },
    {
        "key": "alt+c c",
        "command": "-extension.colorHelper.convert",
        "when": "editorTextFocus"
    },
    {
        "key": "alt+c p",
        "command": "-extension.colorHelper.pick",
        "when": "editorTextFocus"
    }
]

Resolveu comigo aqui esse problema o código acima!  Abs...

A: Consegui resolver da seguinte forma:

*

*Abrir o VSCode

*Na barra superior, ir em: Code -> Settings -> Keyboard Shortcuts

*No arquivo aberto, procure por "alt+c", que é o atalho usado pelo mac para fazer o "ç"

*Encontre a configuração que usa esse atalho na lista, no meu caso era o "markdown.extension.checkTaskList" e clique nele

*No campo de texto aberto, atribua uma nova keybiding para esse comando e aperte Enter. No meu caso, coloquei "ctrl+alt+c"

A imagem abaixo mostra o caminho feito para chegar na configuração de keybidings default do VSCode
Caminho para configuração de atalhos

A: Para mim, funcionou assim, no keybindings.json:
[
    {
        "key": "alt+c",
        "command": "",
        "when": "editorTextFocus"
    }
]


text:
Q: vZ solver returns segmentation fault I am very interested in vZ solver after reading the paper "vZ - Maximal Satisfaction with Z3". I compiled the vZ solver from the unsatable branch at commit 04266fc from https://github.com/Z3Prover/z3/tree/unstable. However, vZ returns "Segmentation fault" for several input SMT formulas, one example can be found here. However, this example formula can be online solved by Rise4Fun. Maybe the local version of vZ has problems. Could you do me a favor to tell me the commit number of vZ in Rise4Fun? Then I can use it locally. Thanks in advance!

A: I think I found the answer to my question. I found a runnable vZ solver from z3.codeplex.com. It is in the "opt" branch.


text:
Q: Which would be better I have a msi gt70 dragon edition laptop.I want to install Ubuntu, not sure if 14.04lts or the newer 15.04 would be better considering the internal hardware...

*

*i7-4810mq

*Nvidia GeForce gtx 870m

*12 gb ram

*Steelseries keyboard with programable back lighting ..

Thanks for the input


text:
Q: AWS S3 Sync - Billing Reports GetObject (Access Denied) I have a consolidated billing account from which I am trying to download the Billing Reports using S3 Sync. When I try to do this it throws "Access Denied" errors when syncing the directory.
So the bash command I am running is:
aws s3 sync s3://my-aws-bills /home/user/Billing

The command above logs in with the 123456789:user/IAMUser which is a cross account IAM user.
The S3 Bucket has a policy of:
        {
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::123456789:user/IAMUser"
        },
        "Action": [
            "s3:GetBucketAcl",
            "s3:GetBucketPolicy",
            "s3:ListBucket"
        ],
        "Resource": "arn:aws:s3:::my-aws-bills"
    },
    {
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::123456789:user/IAMUser"
        },
        "Action": [
            "s3:GetObject",
            "s3:DeleteObject"
        ],
        "Resource": "arn:aws:s3:::my-aws-bills/*"
    }

When I run the bash command it connects ok and I see the files listed but each of the files errors with:
download failed: s3://my-aws-bills/123456789-aws-billing-csv-2018-03.csv to ../../home/user/Billing/123456789-aws-billing-csv-2018-03.csv An error occurred (AccessDenied) when calling the GetObject operation: Access Denied

If I upload a file from my desktop to that bucket (having logged in as the account owner) then S3 sync works correctly for that file but not the ones that have been put there by AWS Billing.
I also notice that I do not, through the root user, have access to see the permissions on the csv files that AWS has put there.
I think I am bumping into a permissions issues but I would have thought the permissions I had already applied would have been enough to download these files?

A: So I believe (though cannot prove) that the problem here was I was trying to use a user that was in a different account going across accounts.
I eventually created another IAM user within the same account as the billing account and could access with the same permissions as above (I just changed out the IAMUser).
It would make sense that you cannot access other people's billing data programmatically across accounts but I have not seen it documented anywhere.


text:
Q: ExpandableListView with non-expandable items I'm trying to create an ExpandableListView in my navigation drawer that has other, non-expandable options. I'm trying to create something like below:

All cereals. . . . . . . . . . . .  V

Archived Cereals . . . . . . V

Settings

Help and Feedback

About Us

"All cereals" and "Archived cereals" would have the dropdown indicator because they are groups with children, while "Settings," "About Us," etc. wouldn't have the indicator. I've looked all over and thought of two approaches: modifying the adapter to inflate a different layout for empty groups, and stacking an ExpandableListView on a normal ListView.
Modifying the adapter was not as viable as I'd hoped because the group indicator is attached automatically. I can't figure out how to make the automatic attachment of the dropdown indicator go away. Help?
Stacking the ExpandableListView on a normal ListView was not as viable as I'd hoped, either, because I couldn't get the XML to cooperate with two lists within one DrawerLayout. Help?

A: If those are static elements, then its probably not worth the effort implementing something similar to ViewItemType. You can consider putting them in the footerView of the listview.
Try listview.addFooterView(view);

A: Your ExpandableListView will use an ExpandableListAdapter, which will have some methods in it that will help you out a lot. you can read more about them at this link http://developer.android.com/reference/android/widget/ExpandableListAdapter.html. Starting with having some of the positions not expand, what I have done in the past was override the getChildrenCount() method in the ExpandableListAdaptor. Then to specify click behavior, that can be done by overriding the getGroupViewMethod. Your adapter could look something like this:
public class MyAdapter extends BaseExpandableListAdapter {
...
@Override
//This is where we tell the list not to expand on any position beyond the first 2
public int getChildrenCount(int position) {
switch(position)
{
case 0:
//Expands with the size of the cereal array
return cerealArray.size();
case 1:
//Expands with the size of the Archived Cereal Array
return archivedCerealArray.size();
default:
//List does not expand
return 0;
 }
...
@Override
public View getGroupView(int groupPosition,boolean isExpanded,View convertView,ViewGroup parent)
{
if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.kat_layout, null);
        }
 ImageView arrow = (ImageView)convertView.findViewById(R.id.arrowImage);
//Test for position
switch (groupPosition)
{
  case 0:
 //set arrow visibility to visible
arrow.setVisibility(View.VISIBLE);
 break;
 case 1:
 //set arrow visibility to visible
 arrow.setVisibility(View.VISIBLE);
 break;
 case 2:
 //hide arrow
arrow.setVisibility(View.INVISIBLE);
 convertView.setOnClickListener(new OnClickListener()
      {
      @Override
      public void onClick(View v){
      //Navigate to settings
     }
  }
  break;
 case 3:
 //hide arrow
arrow.setVisibility(View.INVISIBLE);
 convertView.setOnClickListener(new OnClickListener()
      {
      @Override
      public void onClick(View v){
      //Help and feedback
     }
  }
  break;
 case 4:
 //hide arrow
arrow.setVisibility(View.INVISIBLE);
  convertView.setOnClickListener(new OnClickListener()
      {
      @Override
      public void onClick(View v){
      //About us
     }
  }
  break;

}
return convertView;
}

what that will do is have the elements below the first 2 have no children. Since they have no children, they cannot expand.
The click events will also be handled only on condition of position.
As far as getting the group indicator to go away, I would inflate a view from xml in the getGroupView() method. That way, you have complete control over how it looks in any case.
I hope this helps. Good Luck.


text:
Q: Implementing AJAX via POST request I am reading a book that describes the procedure to implement Ajax via POST request. This is code:
name of file: ajaxtest.html

<title>AJAX Example</title>

LOADING A WEBPAGE INTO A DIV

This is going to be replaced

The example of that book also has 2 lines i removed after reading some other articles:
request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close")

The ajaxRequest function is saved in a separate .js file named xhr.js:
function ajaxRequest()
{
try
{
    // fon NON-IE browsers
    var request = new XMLHttpRequest()
}
catch(e1)
{
    try
    {
        //for IE6+ browser
        var request = new ActiveXObject("Msxml2.XMLHTTP")
    }
    catch(e2)
    {
        try
        {
            //for IE5
            var request = new ActiveXObject("Microsoft.XMLHTTP")
        }
        catch(e3)
        {
            //No AJAX support
            var request = false
        }
    }
}
return request
}

And the ajaxtest.php file is:
<?php

if(isset($_POST['url']))
{
echo file_get_contents("http://".$_POST['url']);

echo "test1";
}

echo "test2";

echo $_POST['url'];
?>

The thing is that, as soon as i execute the ajaxtest.html, the part "This is going to be replaced", it disappears (which is correct), but after that what i get is the part of the ajaxtest.php that is outside the if(isset()). And when it reaches the echo $_POST['url'] outside the if(isset()) i get the following error:
Notice: Undefined index: url in C:\wamp\www\ajaxtest.php on line 11
Ofcourse the test2 is printed on the page.
Why is this happening? Shouldn't $_POST['url'] be available in the ajaxtest.php script as well?

A: HTML file

<title>AJAX Example</title>

LOADING A WEBPAGE INTO A DIV

This is going to be replaced

ajaxtest.php
<?php
if(isset($_POST['url'])) {
    $_POST = array_map("urldecode",$_POST);
    echo file_get_contents("http://".$_POST['url']);
} else {
    echo "test2";
}
?>

First, you need to encode your parameters before sending them through ajax.
Second, when getting the parameters in php you need to decode them.
Third, you have misspelled the content-type.

A: Your content type is wrong:
request.setRequestHeader("Content-type", "application/x-wwww-form-urlencode")
//                                                                         ^

It should be:
request.setRequestHeader("Content-type", "application/x-wwww-form-urlencoded")

With the wrong content type you can still tell PHP to parse it anyway:
parse_str(file_get_contents('php://input'), $data);
echo $data['url'];

But setting the correct content type will be the best option.

A: Sticking with the same javascript format from the book you are reading, you could define your 'params' as such:
params = JSON.stringify({url:'oreilly.com'});//SEND AS JSON OBJECT

and in the PHP file:
        <?php
        $request_body = file_get_contents('php://input');
        $data = json_decode($request_body);//DECODE JSON OBJECT
        $url = $data->url;//EXTRACT THE "URL" VALUE FROM DECODED JSON OBJECT
        if(isset($url))
        {
        echo file_get_contents("http://".$url);
        echo "test1";
        }
        ?>

A: Using the Jquery AJAX methods makes using ajax communication a lot simpler.
This can simply be done using the following line of code: (for a web connected site, if it is for local use you would need to download the file locally)

you would then use the following code to setup your ajax request:
$.ajax({
    url: "path",
    type: "POST", //http verb, can be any of the standard verbs, eg, GET, PUT, POST, DELETE...
    data:{data1:data1_value, data2:data2_value}, //any post data to send with request
    async: true,
    dataType:'json', //data format expected from server
    success: function (data) {
        //code to execute on success (the data variable contains any data returned by the server
    },
    error: function (xhr, ajaxOptions, thrownError) {
        //code to handle errors goes here
    },
});


text:
Q: Why does Reactive Extensions send a HTTP GET to microsoft ON COMPILATION? I downloaded the Stable release of Reactive Extensions v1.0 SP1 from this site http://msdn.microsoft.com/en-us/data/gg577610, and I am using it in a .Net Framework 3.5 environment (Visual Studio 2008)
I tried using Reactive Extensions in a project, and noticed it was very slow to start up. Going to LinqPad, I entered the following "C# Expression":
(new int[0]).ToObservable()

I also referenced System.Reactive.dll and imported the System.Reactive.Linq namespace. When I run it, it takes 12 Seconds to compile & run.
I opened Process Monitor and monitored LinqPad. I found that it is sending an HTTP request to 124.155.222.226 OR 124.155.22.59. (FYI LinqPad itself also phones home to 157.55.161.150 when you open it). With WireShark, I noticed it is sending an HTTP GET request to
http://crl.microsoft.com/pki/crl/products/MicCodSigPCA_08-31-2010.crl

Does anyone know why it is phoning home like this when code compiles with Reactive.Extensions? Furthermore, is there any way to turn it off, because a 12 second delay to phone home when devoloping the application (AND running in production) is particularlly inconvenient.
NOTE: It phones home like this when you COMPILE the code (or the JIT compiles it when debugging). It is not actually the run-time behavior that appears to be doing this.

A: It sounds like the Rx assembly is Authenticode-signed. IMO, it's a mistake to Authenticode-sign .NET assemblies built for Framework 3.5 or earlier - because the CLR checks the certification revocation list before reading the assembly, delaying things by a few seconds at best (or 30 seconds at worst if your Internet connection times out).
This misfeature was fixed in CLR 4: Authenticode signatures are verified only on demand, not every time you load the assembly.
(It's for this reason that the Framework 3.5 version of the LINQPad executable is not Authenticode-signed.)
Maybe you could ask the Rx team to consider removing the Authenticode signature from the 3.5 build of the Reactive assemblies (assuming this is indeed the problem).


text:
Q: How does this quantity transform under time reversal and inversion operation respectively? Suppose $\psi_{nk}=e^{ikr}u_{nk}$ is the Bloch function of a periodic Hamiltonian $H(r)=H(r+R)$, where $H(r)\psi_{nk}=\varepsilon_{nk}\psi_{nk}$ and $H(k)=e^{-ikr}H(r)e^{ikr}$.
What would the following quantity change under the time-reversal and inversion operation respectively and why?
$$
\vec{L}(k)=i\int \mathrm{d}r \nabla_k u_{nk}^*\times\left[H(k)-\varepsilon_{nk}\right]\nabla_k u_{nk}
$$
I have no clue how to tackle this, I don't know if I am going to change $u_{nk}$ or to change $H(k)$ and $\varepsilon_{nk}$ or change both, and I am not sure how to change them. Please give a detailed answer if you know how to do this.


text:
Q: Laravel Left Join Query I am using laravel 5.3 and I have some left join query with error in laravel query method.
This is my normal query
 SELECT bran.branchName,sch.schoolName From m_schoolbranch bran
LEFT JOIN m_students stu ON stu.schoolNo=bran.schoolNo AND stu.branchNo=bran.branchNo
LEFT JOIN m_school sch ON sch.schoolNo=stu.schoolNo where stu.userNo='0000000001';

And this is my new laravel Query
DB::table('m_schoolbranch')
            ->join('m_students', 'm_schoolbranch.schoolNo', '=', 'm_students.schoolNo')
            ->join('m_students', 'm_schoolbranch.branchNo', '=', 'm_students.branchNo')
            ->join('m_school', 'm_schoolbranch.schoolNo', '=', 'm_school.schoolNo')
            ->select('m_school.schoolName', 'm_schoolbranch.branchName')
            ->where('m_students.userNo',$userNo)
            ->get();

In these query I need to match two column in table m_students  so I put like this
->join('m_students', 'm_schoolbranch.branchNo', '=', 'm_students.branchNo')

But i show error...

A: Tables in the query need to have unique names, otherwise the DB has no way of knowing which m_schoolbranch should be used when evaluating m_schoolbranch.schoolNo.
You could use unique table aliases in your join statements but I recommend using multiple conditions on the join. Just like you use in your original SQL query. See here: https://stackoverflow.com/a/20732468/4437888

A: DB::table('m_schoolbranch')
            ->join('m_students', function($join)
                {
                    $join->on('m_schoolbranch.schoolNo', '=', 'm_students.schoolNo');
                    $join->on('m_schoolbranch.branchNo', '=', 'm_students.branchNo');
                })
            ->join('m_school', 'm_schoolbranch.schoolNo', '=', 'm_school.schoolNo')
            ->select('m_school.schoolName', 'm_schoolbranch.branchName')
            ->where('m_students.userNo',$userNo)
            ->get();


text:
Q: How to get a complete request from a NSURLRequest? Is there any way to get the actual data that will be sent when a NSURLConnection sends a NSURLRequest? Right now I'm mainly interested in looking at HTTP and HTTPS requests, but since NSURLRequest works for many protocols, it seems like there ought to be a general way to see the corresponding data for any type of request.
Am I missing something, or do I need to construct the request myself by combining the headers, body, etc?
Just to be clear, I'd like to do this programmatically, not by watching what shows up at the server end.
Update: At this point I've written code that effectively constructs a request using the data in a NSURLRequest, so I'm not asking how to go about that. However, I'd still like to know if there's a way to access the request stream that the URL loading system would generate. In other words, can I get access to the exact bytes that would be sent if a NSURLConnection were to send my NSURLRequest?

A: According your last question:

*

*Check cookiesCenter.

*Check credentialsStorage.

*Log all headers for example on the first urlConnection's delegate method didReceiveResponse:.

*Make this connection with local webservice and try to catch all headers, params, etc.

Also, the most simple way, is making request yourself.

A:
Am I missing something, or do I need to construct the request myself
  by combining the headers, body, etc?

It turns out that this is exactly what I needed to do, and it makes sense. It's the protocol handler (NSURLProtocol subclass), not NSURLRequest, that knows how to format the request for its particular protocol. Luckily, it's very easy to render an instance of NSURLRequest into a valid HTTP request. You can get the method (GET, POST, etc.), requested resource, and host from the request, and you can also get all the HTTP headers using the -allHTTPHeaderFields method, which returns a dictionary. You can then loop over the keys in the dictionary and add lines to the request like:
for (NSString *h in headers) {
    [renderedRequest appendFormat:@"%@: %@\r\n", h, [headers objectForKey:h]];
}


text:
Q: Nant cant find assembly in the GAC I have a .Net project which uses the MySQL connector which is located in the GAC.
In my Nant build file there doesnt seem to be a way to tell CSC to look in the GAC to find this dll (or type information) and my project wont build.
Is there a way to tell Nant that this reference does exist and its in the Gac.
Its wierd really because obviously all of the Microsoft libraries e.g. "System" are in the Gac and it doesnt have a problem building anythign referencing those. I have confirmed that the Mysql Connector is also in the Gac.
Thanks.

A: csc looks for DLLs in the current directory, in the framework directory, in the directories mentioned in the /lib switch, in the directories mentioned in the LIB environment variable.
But not in the GAC. You could compile with csc /r:full_path_to_the_gac_file.dll, it works but is not very user-friendly.
.NET assemblies are installed in two places: in the GAC and in the framework directory (which explains why they are found).
You should copy the DLLs you need in a given directory and reference it with the /lib switch. Of course, at run-time, it will be taken from the GAC.

A: Another (more portable) solution could be:
<csc output="../bin/output.dll" target="library">
 <references>
  <include name="\%windir%\assembly\AForge.dll" />
 </references>
 <sources>
  <include name="**/*.cs" />
 </sources>
</csc>

You could also use the lib tag to add \%windir\assembly to the search path, but it is marked deprecated in NAnt documentation.


text:
Q: Unknown device in Debian GNU/Linux What is XT device /dev/xda in Debian GNU/Linux? Could it have something to do with the IBM Personal Computer XT?
I saw it here and nowhere else.
Thank you for your help.

A: Yes, /dev/xda used to provide access to the first drive on an XT-style disk controller, using the xd driver. Linux itself has never been able to run on an IBM PC XT, but it was possible to use XT disk controllers in Linux-compatible systems with ISA slots.
All this is obsolete; the document you found describes Debian 4.0, which was released in 2007. The driver was removed from the kernel in 2013.


text:
Q: Last joined room member is not getting broadcasted message using socket.io in express app socket.js
Step-1 we create socket.js file for all socket events
var socket_io = require('socket.io');
var io = socket_io()
var socketApi = {}
const { instrument } = require("@socket.io/admin-ui");
socketApi.io = io
socketApi.instrument = instrument;
io.on('connection', (socket)=>{
socketApi.socket = socket
 socket.on('joinRoom', (param) => {
  roomName = 'testRoom';
  socket.join(roomName);
 });
});
module.exports = socketApi

bin/www
Step-2 socket.js file include in /bin/www file
var socketApi = require('../socket');
var io = socketApi.io;
io.attach(server,{
cors : {
 origin : ["*","https://admin.socket.io/"],
  credentials: true
 },
});

socketApi.instrument(io, {
 auth: false
});

user.js
Step-3 emitting on saving route of user.js file
var express = require('express');
const io = require('../../../../socket.js');
var router = express.Router();
router.post('/save',async (req,res)=>{
 io.socket.in('testRoom').emit('demo', 'Broadcast on entry');
});


text:
Q: Consuming Signal R service in Desktop application I am new to SignalR, I want to develop a service using SingalR API's and Host as selfhost\IIS, now my doubt is How can I consume these message in Client side my client application will be Windows(Desktop) applications.
    Main intention is to send Notification from SignalR service to Clients. I would like to know is this achievable.
Please share any tutorials link or similar projects URL
Thanks in Advance

A: Yes it's possible. You can connect to a Signal R hub from webclient or winformsclient.
Useful information on this links:

*

*SignalR Chat App in WinForm With Remote Clients

*http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host

A: What I do is use .Net events , to wrap the SignlR client functions and connect to the desktop application call backs . like so :
public class Client
{
    public delegate void OnReciveMessage(Object message);
    public event OnReciveMessage MessageRecivedEvent;

    public void ReciveMessage(Object message)
    {
         if (MessageRecivedEvent != null)
         {
              MessageRecivedEvent(message);
         }
    }
}