Wednesday 31 May 2017

sql server - T-SQL dynamic pivot



Ok I have a table that looks like this



ItemID | ColumnName | Value
1 | name | Peter
1 | phone | 12345678
1 | email | peter@host.com

2 | name | John
2 | phone | 87654321
2 | email | john@host.com
3 | name | Sarah
3 | phone | 55667788
3 | email | sarah@host.com


Now I need to turn that into this:




ItemID | name  | phone    | email
1 | Peter | 12345678 | peter@host.com
2 | John | 87654321 | john@host.com
3 | Sarah | 55667788 | sarah@host.com


I have been looking at dynamic pivot examples, but it seems Im not able to fit them into my scenario.



Can anyone help?


Answer




Have a look at the following example



CREATE TABLE #Table (
ID INT,
ColumnName VARCHAR(250),
Value VARCHAR(250)
)

INSERT INTO #Table SELECT 1,'name','Peter'
INSERT INTO #Table SELECT 1,'phone','12345678'

INSERT INTO #Table SELECT 1,'email','peter@host.com'
INSERT INTO #Table SELECT 2,'name','John'
INSERT INTO #Table SELECT 2,'phone','87654321'
INSERT INTO #Table SELECT 2,'email','john@host.com'
INSERT INTO #Table SELECT 3,'name','Sarah'
INSERT INTO #Table SELECT 3,'phone','55667788'
INSERT INTO #Table SELECT 3,'email','sarah@host.com'

---I assumed your tablename as TESTTABLE---
DECLARE @cols NVARCHAR(2000)

DECLARE @query NVARCHAR(4000)

SELECT @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
'],[' + t.ColumnName
FROM #Table AS t
--ORDER BY '],[' + t.ID
FOR XML PATH('')
), 1, 2, '') + ']'

SELECT @cols


SET @query = N'SELECT ID,'+ @cols +' FROM
(SELECT t1.ID,t1.ColumnName , t1.Value FROM #Table AS t1) p
PIVOT (MAX([Value]) FOR ColumnName IN ( '+ @cols +' ))
AS pvt;'

EXECUTE(@query)

DROP TABLE #Table


function - What is the scope of variables in JavaScript?



What is the scope of variables in javascript? Do they have the same scope inside as opposed to outside a function? Or does it even matter? Also, where are the variables stored if they are defined globally?


Answer



I think about the best I can do is give you a bunch of examples to study.
Javascript programmers are practically ranked by how well they understand scope.

It can at times be quite counter-intuitive.




  1. A globally-scoped variable



    // global scope
    var a = 1;

    function one() {
    alert(a); // alerts '1'

    }

  2. Local scope



    // global scope
    var a = 1;

    function two(a) { // passing (a) makes it local scope
    alert(a); // alerts the given argument, not the global value of '1'
    }


    // local scope again
    function three() {
    var a = 3;
    alert(a); // alerts '3'
    }

  3. Intermediate: No such thing as block scope in JavaScript (ES5; ES6 introduces let and const)



    a.




    var a = 1;

    function four() {
    if (true) {
    var a = 4;
    }

    alert(a); // alerts '4', not the global value of '1'
    }



    b.



    var a = 1;

    function one() {
    if (true) {
    let a = 4;
    }


    alert(a); // alerts '1' because the 'let' keyword uses block scoping
    }


    c.



    var a = 1;

    function one() {

    if (true) {
    const a = 4;
    }

    alert(a); // alerts '1' because the 'const' keyword also uses block scoping as 'let'
    }

  4. Intermediate: Object properties



    var a = 1;


    function Five() {
    this.a = 5;
    }

    alert(new Five().a); // alerts '5'

  5. Advanced: Closure



    var a = 1;


    var six = (function() {
    var a = 6;

    return function() {
    // JavaScript "closure" means I have access to 'a' in here,
    // because it is defined in the function in which I was defined.
    alert(a); // alerts '6'
    };
    })();


  6. Advanced: Prototype-based scope resolution



    var a = 1;

    function seven() {
    this.a = 7;
    }

    // [object].prototype.property loses to

    // [object].property in the lookup chain. For example...

    // Won't get reached, because 'a' is set in the constructor above.
    seven.prototype.a = -1;

    // Will get reached, even though 'b' is NOT set in the constructor.
    seven.prototype.b = 8;

    alert(new seven().a); // alerts '7'
    alert(new seven().b); // alerts '8'





  7. Global+Local: An extra complex Case



    var x = 5;

    (function () {
    console.log(x);
    var x = 10;

    console.log(x);
    })();


    This will print out undefined and 10 rather than 5 and 10 since JavaScript always moves variable declarations (not initializations) to the top of the scope, making the code equivalent to:



    var x = 5;

    (function () {
    var x;

    console.log(x);
    x = 10;
    console.log(x);
    })();

  8. Catch clause-scoped variable



    var e = 5;
    console.log(e);
    try {

    throw 6;
    } catch (e) {
    console.log(e);
    }
    console.log(e);


    This will print out 5, 6, 5. Inside the catch clause e shadows global and local variables. But this special scope is only for the caught variable. If you write var f; inside the catch clause, then it's exactly the same as if you had defined it before or after the try-catch block.



php - Undefined index with $_POST




I am trying to relearn some PHP basics for making a simple login script, however I get an error I have not received before(I made the same script a little over a year ago and never had this error. I simplified the code as much as I could to test to see which area was problematic and here is the issue:




$user = $_POST["username"];
if($user != null)
{
echo $user;
echo " is your username";
}
else
{
echo "no username supplied";
}

?>


Now this code works fine when I send a variable to the script, but when no variable is supplied it spits out an error. In theory this will be fine because if no username/pass is supplied then an error is expected. I will be checking to make sure of this before the code is send to the script, however I fear that somehow a blank string may leak through and spit out some unknown error. Here is the error I get:



( ! ) Notice: Undefined index: username in C:\wamp\www\verify_login.php on line 2

Call Stack

Time Memory Function Location

1 0.0003 668576 {main}( ) ..\verify_login.php:0


no username supplied



as you can see the code registers that no variable was supplied, but it gives out and error that I assume means that a variable was not found were one was expected or something like that. Can someone please clarify this for me?


Answer



In PHP, a variable or array element which has never been set is different from one whose value is null; attempting to access such an unset value is a runtime error.



That's what you're running into: the array $_POST does not have any element at the key "username", so the interpreter aborts your program before it ever gets to the nullity test.




Fortunately, you can test for the existence of a variable or array element without actually trying to access it; that's what the special operator isset does:



if (isset($_POST["username"]))
{
$user = $_POST["username"];
echo $user;
echo " is your username";
}
else

{
$user = null;
echo "no username supplied";
}


This looks like it will blow up in exactly the same way as your code, when PHP tries to get the value of $_POST["username"] to pass as an argument to the function isset(). However, isset() is not really a function at all, but special syntax recognized before the evaluation stage, so the PHP interpreter checks for the existence of the value without actually trying to retrieve it.



It's also worth mentioning that as runtime errors go, a missing array element is considered a minor one (assigned the E_NOTICE level). If you change the error_reporting level so that notices are ignored, your original code will actually work as written, with the attempted array access returning null. But that's considered bad practice, especially for production code.




Side note: PHP does string interpolation, so the echo statements in the if block can be combined into one:



echo "$user is your username";

How can I add a PHP page to WordPress?

If you wanted to create your own .php file and interact with WordPress without 404 headers and keeping your current permalink structure there is no need for a template file for that one page.



I found that this approach works best, in your .php file:



    require_once(dirname(__FILE__) . '/wp-config.php');

$wp->init();
$wp->parse_request();
$wp->query_posts();
$wp->register_globals();
$wp->send_headers();

// Your WordPress functions here...
echo site_url();
?>



Then you can simply perform any WordPress functions after this. Also, this assumes that your .php file is within the root of your WordPress site where your wp-config.php file is located.



This, to me, is a priceless discovery as I was using require_once(dirname(__FILE__) . '/wp-blog-header.php'); for the longest time as WordPress even tells you that this is the approach that you should use to integrate WordPress functions, except, it causes 404 headers, which is weird that they would want you to use this approach. Integrating WordPress with Your Website



I know many people have answered this question, and it already has an accepted answer, but here is a nice approach for a .php file within the root of your WordPress site (or technically anywhere you want in your site), that you can browse to and load without 404 headers!





Update: There is a way to use wp-blog-header.php without 404 headers, but this requires that you add in the headers manually. Something like this will work in the root of your WordPress installation:


    require_once(dirname(__FILE__) . '/wp-blog-header.php');
header("HTTP/1.1 200 OK");
header("Status: 200 All rosy");

// Your WordPress functions here...
echo site_url();
?>



Just to update you all on this, a little less code needed for this approach, but it's up to you on which one you use.

parameters - AngularJS ui router passing data between states without URL



I am facing this problem of passing data between two states without exposing the data in the url, it's like user cannot really directly land on this state.




For example.
I have two states "A" and "B".
I am doing some server call in state "A" and passing the response of the call
to state "B". The response of the server call is a string message, which is quite long, so i cannot expose that in the url.



So is there any way in angular ui router to pass data between states, without using url params ?


Answer



We can use params, new feature of the UI-Router:



API Reference / ui.router.state / $stateProvider





params A map which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a configuration object keyed to the name of the parameter.




See the part: "...or defines additional non-url parameters..."



So the state def would be:



$stateProvider

.state('home', {
url: "/home",
templateUrl: 'tpl.html',
params: { hiddenOne: null, }
})


Few examples form the doc mentioned above:



// define a parameter's default value

params: {
param1: { value: "defaultValue" }
}
// shorthand default values
params: {
param1: "defaultValue",
param2: "param2Default"
}

// param will be array []

params: {
param1: { array: true }
}

// handling the default value in url:
params: {
param1: {
value: "defaultId",
squash: true
} }

// squash "defaultValue" to "~"
params: {
param1: {
value: "defaultValue",
squash: "~"
} }


EXTEND - working example: http://plnkr.co/edit/inFhDmP42AQyeUBmyIVl?p=info




Here is an example of a state definition:



 $stateProvider
.state('home', {
url: "/home",
params : { veryLongParamHome: null, },
...
})
.state('parent', {
url: "/parent",

params : { veryLongParamParent: null, },
...
})
.state('parent.child', {
url: "/child",
params : { veryLongParamChild: null, },
...
})



This could be a call using ui-sref:



home

parent

parent.child


Check the example here


python - How do I return multiple values from a function?

The canonical way to return multiple values in languages that support it is often tupling.



Option: Using a tuple



Consider this trivial example:




def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return (y0, y1, y2)


However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.




Option: Using a dictionary



The next logical step seems to be to introduce some sort of 'record notation'. In Python, the obvious way to do this is by means of a dict.



Consider the following:



def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3

return {'y0': y0, 'y1': y1 ,'y2': y2}


(Just to be clear, y0, y1, and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers.)



Now, we have a mechanism whereby we can project out a particular member of the returned object. For example,



result['y0']



Option: Using a class



However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:



class ReturnValue:
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2


def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return ReturnValue(y0, y1, y2)


In Python the previous two are perhaps very similar in terms of plumbing - after all { y0, y1, y2 } just end up being entries in the internal __dict__ of the ReturnValue.



There is one additional feature provided by Python though for tiny objects, the __slots__ attribute. The class could be expressed as:




class ReturnValue(object):
__slots__ = ["y0", "y1", "y2"]
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2


From the Python Reference Manual:





The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.




Option: Using a dataclass (Python 3.7+)



Using Python 3.7's new dataclasses, return a class with automatically added special methods, typing and other useful tools:



@dataclass

class Returnvalue:
y0: int
y1: float
y3: int

def total_cost(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return ReturnValue(y0, y1, y2)



Option: Using a list



Another suggestion which I'd overlooked comes from Bill the Lizard:



def h(x):
result = [x + 1]
result.append(x * 3)
result.append(y0 ** y3)

return result


This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be.



A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are mutable, whereas tuples are not.



I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.






After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?



I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents.



On the other hand, there are some in the Python community that feel implied interfaces should be preferred to explicit interfaces, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning.



So, how do -you- return multiple values in Python?

MS Excel VBA how to insert a row in the current worksheet and three others



I am using MS Excel 2007 and Microsoft Visula Basic 6.5.



I want to select a row in a sheet and then use a macro to insert a row in this sheet and three others. I am trying the code below however when I run it I get the error "Run-time error '1004': Application-defined or object-defined error" on "Worksheets("Rel. Planning Meeting").Range(Lst).Activate".




Sub Copy1()
Dim Lst As Long
'save the rowNo
Lst = ActiveCell.Row

Worksheets("Rel. Planning Meeting").Activate
Worksheets("Rel. Planning Meeting").Range(Lst).Activate
ActiveCell.EntireRow.Insert

Worksheets("Master Release Plan - HTSTG").Activate

Worksheets("Master Release Plan - HTSTG").Range(Lst).Activate
ActiveCell.EntireRow.Insert

Worksheets("Inst. Gateway").Activate
Worksheets("Inst. Gateway").Range(Lst).Activate
ActiveCell.EntireRow.Insert


Worksheets("CAB").Activate
Worksheets("CAB").Range(Lst).Activate

ActiveCell.EntireRow.Insert

Worksheets("Rel. Planning Meeting").Range("A3:G5000").Copy _
Destination:=Worksheets("Master Release Plan - HTSTG").Range("A3")

Worksheets("Master Release Plan - HTSTG").Range("A3:O5000").Copy _
Destination:=Worksheets("Inst. Gateway").Range("A3")

Worksheets("Inst. Gateway").Range("A3:T5000").Copy _
Destination:=Worksheets("CAB").Range("A3")


End Sub


I have tried "Dim Lst As Range" however then I get the error "Run time error '91': Object variable or With block variable not set" on "Lst = ActiveCell.Row".



Your help is greatly appreciated.



Regards,




Glyn



New Code:



Sub InsertRow()

Dim Lst As Long
'save the rowNo
Lst = ActiveCell.Row


'Insert a row in each worksheet at the currently selected cell.
Worksheets("Rel. Planning Meeting").Rows(Lst).Insert
Worksheets("Master Release Plan - HTSTG").Unprotect
Worksheets("Master Release Plan - HTSTG").Rows(Lst).Insert
Worksheets("Inst. Gateway").Unprotect
Worksheets("Inst. Gateway").Rows(Lst).Insert
Worksheets("CAB").Unprotect
Worksheets("CAB").Rows(Lst).Insert
End Sub


Answer



in the 2nd line of your code, you are assigning lst, a value(activecell.row), which is a long variable. if you write



Worksheets("Rel. Planning Meeting").Range(Lst).Activate


that means ex - Worksheets("Rel. Planning Meeting").Range(4).Activate, if ur activecell.row is 4. This will not work on a range.



If you want to select a row then change your existing line and all other similar lines, where you have range(lst) to -




Worksheets("Rel. Planning Meeting").Rows(Lst).Activate


I would suggest not selecting anything on the sheet as far as possible because this may slow up the execution time. Your's is a very simple macro here but it is good practice to avoid selecting or activating stuff on your sheet as much as possible.



Hope this helps.


javascript - this.setState makes variable undefined?



I'm trying to increment my state variable, but whenever I do so an error pops up which says that the variable state is undefined. I defined my variable inside the constructor. Obviously something is going on in the setState function.



Here is the code which renders an error:



displayDiv(){
var arr=[];
if (this.state.flag[2]){
this.setState({counter:counter+4}); // error:undefined

for (let i = this.state.counter-4; i < this.state.counter; i++)
arr.push(this.state.arrayHeader[0].content);
}
}
return(
arr.map(function(item,i){
return (






);

})
);
}


Here is the defined variable inside the constructor:




constructor(props){
super(props);

this.state = {
arrayHeader:[],
arraytag1:[],
arraytag2:[],
counter:0,
flag:[false,false,false]

}
}

Answer



Your counter +4 points nowhere.



It should be this.state.counter + 4



Also, if you are calling this function on the render() make sure it has been previously binded, you can do that like this on the constructor:




this.displayDiv = this.displayDiv.bind(this);

Why does Java require an explicit cast on a final variable if it was copied from an array?



Starting with the following code...



byte foo = 1;
byte fooFoo = foo + foo;


When I try compiling this code I will get the following error...





Error:(5, 27) java: incompatible types: possible lossy conversion from int to byte




... but if foo is final...



final byte foo = 1;
final byte fooFoo = foo + foo;



the file will compile successfully.



Moving on to the following code...



final byte[] fooArray = new byte[1];
fooArray[0] = 1;

final byte foo = fooArray[0];
fooArray[0] = 127;


System.out.println("foo is: " + foo);


... will print



foo is: 1


... which is fine. The value is copied to a final variable and it can not be changed any more. Playing with the value in the array does not change the value of the foo (as expected...).




Why does the following require a cast?



final byte[] fooArray = new byte[1];
fooArray[0] = 1;
final byte foo = fooArray[0];
final byte fooFoo = foo + foo;


How is this different than the second example in this question? Why is the compiler giving me the following error?





Error:(5, 27) java: incompatible types: possible lossy conversion from int to byte




How can this happen?


Answer



The JLS (§5.2) has special rules for assignment conversion with constant expressions:




In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:





  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.




If we follow the link above, we see these in the definition of constant expression:






  • Literals of primitive type and literals of type String

  • The additive operators + and -

  • Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).




If we follow the second link above, we see that




A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable.





It follows that foo + foo can only be assigned to fooFoo if foo is a constant variable. To apply that to your cases:




  • byte foo = 1; does not define a constant variable because it's not final.


  • final byte foo = 1; does define a constant variable, because it's final and initialized with a constant expression (a primitive literal).


  • final byte foo = fooArray[0]; does not define a constant variable because it's not initialized with a constant expression.





Note that whether fooFoo is itself final doesn't matter.


Converting string to byte array in C#

I'm converting something from VB into C#. Having a problem with the syntax of this statement:



if ((searchResult.Properties["user"].Count > 0))

{
profile.User = System.Text.Encoding.UTF8.GetString(searchResult.Properties["user"][0]);
}


I then see the following errors:




Argument 1: cannot convert from 'object' to 'byte[]'




The best overloaded method match for
'System.Text.Encoding.GetString(byte[])' has some invalid arguments




I tried to fix the code based on this post, but still no success



string User = Encoding.UTF8.GetString("user", 0);


Any suggestions?

Get multiple tracks from Spotify API using ISRC code



There is a solution to fetch a single track by querying the Spotify search API with ISRC.



But, I didn't find any way to fetch multiple tracks for the same.



I tried these ways but nothing worked:



Comma-separated: https://api.spotify.com/v1/search?type=track&q=isrc:USEE10001993,USEE10001994



Plus-separated: https://api.spotify.com/v1/search?type=track&q=isrc:USEE10001993+USEE10001994



Is there any way to achieve this?


Answer



This request work fine for me: https://api.spotify.com/v1/search?type=track&q=isrc:USWB11802164+OR+isrc:DEMA61301103


Java: Print Array: IndexOutOfBoundsException: Index: 2, Size: 2




I am trying to print the contents of an array using System.out.print() but I encounter this error:



Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at Polymorphism.actionPerformed(Polymorphism.java:196)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)

at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)

at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)

at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)


The line the error is referring to is line 3:



 else if (e.getSource() == printArray) {
for (int q=0; q
System.out.print("Type: " + itemList.get(j).selectedType + " ");
System.out.print("Width: " + itemList.get(j).selectedWidth + " ");
System.out.print("Length: " + itemList.get(j).selectedLength + " ");
}
}


I don't have any debugger experience so I appreciate any help, thanks.


Answer



Change to .get(j) as Renjith says and you can also make sure to never end up in the situation you're in




instead of



for (int q=0; q


do



for (int q=0; q



This way you cannot .get from anything larger than the size of the list/array


What's the simplest way to print a Java array?




In Java, arrays don't override toString(), so if you try to print one directly, you get the className + '@' + the hex of the hashCode of the array, as defined by Object.toString():



int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray); // prints something like '[I@3343c8b3'


But usually, we'd actually want something more like [1, 2, 3, 4, 5]. What's the simplest way of doing that? Here are some example inputs and outputs:



// Array of primitives:

int[] intArray = new int[] {1, 2, 3, 4, 5};
//output: [1, 2, 3, 4, 5]

// Array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};
//output: [John, Mary, Bob]

Answer



Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that the Object[] version calls .toString() on each object in the array. The output is even decorated in the exact way you're asking.




Examples:




  • Simple Array:



    String[] array = new String[] {"John", "Mary", "Bob"};
    System.out.println(Arrays.toString(array));


    Output:




    [John, Mary, Bob]

  • Nested Array:



    String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
    System.out.println(Arrays.toString(deepArray));
    //output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
    System.out.println(Arrays.deepToString(deepArray));



    Output:



    [[John, Mary], [Alice, Bob]]

  • double Array:



    double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
    System.out.println(Arrays.toString(doubleArray));



    Output:



    [7.0, 9.0, 5.0, 1.0, 3.0 ]

  • int Array:



    int[] intArray = { 7, 9, 5, 1, 3 };
    System.out.println(Arrays.toString(intArray));



    Output:



    [7, 9, 5, 1, 3 ]


How does ANDROID_ID on ARC (Chrome) differ from Android?



On Android, the ANDROID_ID is constant for a user profile on a device (see discussion here). This does not appear to be the case on ARC, but ARC is very new and hopefully this will change.



It is also worth noting - in regards to device identification with ARC - that the Android serial # is not available on ARC, that WiFi MAC address is not currently available (yes, I've seen people talk about using this for device id), and product model information is not available.



Motivation: I know it is not now recommended, but I think a lot of apps use the ANDROID_ID to identify devices in their server database.




The behavior of ANDROID_ID on Android means that, if a user uninstalls your app and then re-installs it, you would know and could eg. re-sync their data to the device. And if a user installs two apps of your apps, you know they are on the same device (and user profile).


Answer



In my experience - using ARC runtime 42.4410.288.23 on Chrome 41.0.2272.118 m (stable) on Windows - a new ANDROID_ID is generated for every app install.



So, for example, if you uninstall your app and then re-install it, it will see a new ANDROID_ID.



I should test this on a Chromebook, since that is the only platform supported for deployment at this time, but I don't have a Chromebook available.


null coalescing operator - What do two question marks together mean in C#?



Ran across this line of code:




FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();


What do the two question marks mean, is it some kind of ternary operator?
It's hard to look up in Google.


Answer



It's the null coalescing operator, and quite like the ternary (immediate-if) operator. See also ?? Operator - MSDN.



FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();



expands to:



FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();


which further expands to:



if(formsAuth != null)

FormsAuth = formsAuth;
else
FormsAuth = new FormsAuthenticationWrapper();


In English, it means "If whatever is to the left is not null, use that, otherwise use what's to the right."



Note that you can use any number of these in sequence. The following statement will assign the first non-null Answer# to Answer (if all Answers are null then the Answer is null):



string Answer = Answer1 ?? Answer2 ?? Answer3 ?? Answer4;






Also it's worth mentioning while the expansion above is conceptually equivalent, the result of each expression is only evaluated once. This is important if for example an expression is a method call with side effects. (Credit to @Joey for pointing this out.)


c# - reading from app.config file

I am trying to read StartingMonthColumn and CategoryHeadingColumn
from the below app.config file using the code



ConfigurationSettings.AppSettings["StartingMonthColumn"]



but it is returning null, also ConfigurationSettings.AppSettings.Count returns zero



Please help me to read this in my windows application























shell - Is there a TRY CATCH command in Bash



I'm writing a shell script and need to check that a terminal app has been installed. I want to use a TRY/CATCH command to do this unless there is a neater way.


Answer




Is there a TRY CATCH command in Bash?




No.




Bash doesn't have as many luxuries as one can find in many programming languages.



There is no try/catch in bash; however, one can achieve similar behavior using && or ||.



Using ||:



if command1 fails then command2 runs as follows



command1 || command2



Similarly, using &&, command2 will run if command1 is successful



The closest approximation of try/catch is as follows



{ # try

command1 &&
#save your output


} || { # catch
# save log for exception
}


Also bash contains some error handling mechanisms, as well



set -e



It will immediately stop your script if a simple command fails. I think this should have been the default behavior. Since such errors almost always signify something unexpected, it is not really 'sane' to keep executing the following commands.



And also why not if...else. It is your best friend.


javascript - Change a style then with second click reset to original class





I have a button and it takes some styles with first click. But I want the user to be able to reset to the original with second click on own button or any button in page.



How can I do this?







my codes





$("#checkButton").click(function() {
$("#checkButton").css("color", "yellow");
});










Answer



You can do it with CSS styling, but I've made a below snippet in case if you want to change color without make CSS.



Check current color, and then set the different one.






$("#checkButton").click(function() {
var color = $("#checkButton").css("color")
var yellow = "rgb(255, 255, 0)"

if (color !== yellow) {
$("#checkButton").css("color", yellow);
} else {
$("#checkButton").css("color", "");
}

});






Tuesday 30 May 2017

c - GCC, duplicate typedefs, and DWARF

For the past few years, GCC has allowed duplicate typedefs as long as they're compatible with each other. The issue I'm facing is with DWARF debugging extensions: it seems that GCC (v4.8) marks duplicate typedefs as unused, and does not include them in DWARF.



Example:



typedef struct yyx yyx_handle;

typedef struct yyx yyx_handle;

yyx_handle *get_yyx(void *p)
{ return (yyx_handle *)p; }


Results:



$ gcc -o f1.o -c f1.c -g
$ readelf --debug-dump f1.o | grep yyx_handle | wc -l

0


If I add -fno-eliminate-unused-debug-types the typedef is included, but then all my unused types appear as well, blowing up the object file size.



The obvious solution is to remove the duplicate definition, but that's not always practical. Any other suggestions?

python - Regex include line breaks





I have the following xml file




A




B
C





D



Picture number 3?




and I just want to get the text between

and
.

So I've tried this code :



import os, re

html = open("2.xml", "r")
text = html.read()
lon = re.compile(r'
\n(.+)\n
', re.MULTILINE)
lon = lon.search(text).group(1)
print lon



but It doesn't seem to work.


Answer



1) Don't parse XML with regex. It just doesn't work. Use an XML parser.



2) If you do use regex for this, you don't want re.MULTILINE, which controls how ^ and $ work in a multiple-line string. You want re.DOTALL, which controls whether . matches \n or not.



3) You probably also want your pattern to return the shortest possible match, using the non-greedy +? operator.



lon = re.compile(r'
\n(.+?)\n
', re.DOTALL)


How do I enumerate the properties of a JavaScript object?





How do I enumerate the properties of a JavaScript object?



I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.


Answer



Simple enough:



for(var propertyName in myObject) {
// propertyName is what you want
// you can get the value like this: myObject[propertyName]
}



Now, you will not get private variables this way because they are not available.






EDIT: @bitwiseplatypus is correct that unless you use the hasOwnProperty() method, you will get properties that are inherited - however, I don't know why anyone familiar with object-oriented programming would expect anything less! Typically, someone that brings this up has been subjected to Douglas Crockford's warnings about this, which still confuse me a bit. Again, inheritance is a normal part of OO languages and is therefore part of JavaScript, notwithstanding it being prototypical.



Now, that said, hasOwnProperty() is useful for filtering, but we don't need to sound a warning as if there is something dangerous in getting inherited properties.




EDIT 2: @bitwiseplatypus brings up the situation that would occur should someone add properties/methods to your objects at a point in time later than when you originally wrote your objects (via its prototype) - while it is true that this might cause unexpected behavior, I personally don't see that as my problem entirely. Just a matter of opinion. Besides, what if I design things in such a way that I use prototypes during the construction of my objects and yet have code that iterates over the properties of the object and I want all inherited properties? I wouldn't use hasOwnProperty(). Then, let's say, someone adds new properties later. Is that my fault if things behave badly at that point? I don't think so. I think this is why jQuery, as an example, has specified ways of extending how it works (via jQuery.extend and jQuery.fn.extend).


php - Warning: Cannot modify header information - headers already sent by







Hi All,




I keep having a warning message appear when I try login. Can you help me rectify the problem.



Warning: Cannot modify header information - headers already sent by (output started at /path/to/login.php:15) in /path/to/login.php on line 231


here's the php code before the html:



        //allow sessions to be passed so we can see if the user is logged in

session_start();
//connect to the database so we can check, edit, or insert data to our users table
$con = mysql_connect('XXXXXXXXXXXXXXX', 'XXXXXXXXXXXX', 'XXXXXXXXXX') or die(mysql_error());
$db = mysql_select_db('XXXXXXXXXXXXXXXXX', $con) or die(mysql_error());
//include out functions file giving us access to the protect() function made earlier
include "functions.php";
?>


Here is the functions.php file:





function protect($string){
$string = trim(strip_tags(addslashes($string)));
return $string;
}

?>



and finally here is the PHP inside the HTML:




//If the user has submitted the form
if($_POST['submit']){
//protect the posted value then store them to variables
$username = protect($_POST['username']);
$password = protect($_POST['password']);


//Check if the username or password boxes were not filled in
if(!$username || !$password){
//if not display an error message
echo "
You need to fill in a Username and a Password!
";
}else{
//if the were continue checking

//select all rows from the table where the username matches the one entered by the user
$res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."'");

$num = mysql_num_rows($res);

//check if there was not a match
if($num == 0){
//if not display an error message
echo "
The Username you supplied does not exist!
";
}else{
//if there was a match continue checking

//select all rows where the username and password match the ones submitted by the user

$res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."' AND `password` = '".$password."'");
$num = mysql_num_rows($res);

//check if there was not a match
if($num == 0){
//if not display error message
echo "
The Password you supplied does not match the one for that username!
";
}else{
//if there was continue checking


//split all fields fom the correct row into an associative array
$row = mysql_fetch_assoc($res);

//check to see if the user has not activated their account yet
if($row['active'] != 1){
//if not display error message
echo "
You have not yet Activated your account!
";
}else{
//if they have log them in


//set the login session storing there id - we use this to see if they are logged in or not
$_SESSION['uid'] = $row['id'];
//show message
echo "
You have successfully logged in!
";

//update the online field to 50 seconds into the future
$time = date('U')+50;
mysql_query("UPDATE `users` SET `online` = '".$time."' WHERE `id` = '".$_SESSION['uid']."'");

//redirect them to the usersonline page

header('Location: usersOnline.php');
}
}
}
}
}

?>



The main issue arises when I try redirect them to my usersOnline.php page.



//redirect them to the usersonline page
header('Location: usersOnline.php');


I have minimised all white space, but still have problems. Where the error informs me, line 15 is my meta id's (Description & Keywords - SEO). Does this pose problems in PHP?



Any help given is much appreciated as I am relatively new with PHP.




Thanks,
Darren

python - A version of str.isdigit that returns True for decimal fractions?




I want to test raw_input to make sure that the string contains only numbers and at maximum a single decimal point. str.isdigit() looked promising but it will not return True if there is a decimal point in the string.



Ideally, the code would look like this:



def enter_number():
number = raw_input("Enter a number: ") # I enter 3.5
if number.SOMETHING: # SOMETHING is what I am looking for

float_1 = float(number)
return float_1
else
sys.exit()

half = enter_number() / 2 # = 1.75
double = enter_number() * 2 # = 7

Answer



I suggest the EAFP approach.




float raises the ValueError exception if its argument is not a valid float:



In [6]: float('bad value')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
in ()
----> 1 float('bad value')

ValueError: could not convert string to float: 'bad value'



You could catch it:



number = raw_input("Enter a number: ")
try:
return float(number)
except ValueError:
sys.exit()


c# - NullReferenceException was unhandled by user code - Object reference not set to instance of an object




I have the following C# classes:




public class Locales
{
public Region region { get; set; }
public Buttons buttons { get; set; }
public Fields fields { get; set; }
}

public class Region
{

public Center center { get; set; }
public East east { get; set; }
}

public class Center
{
public string title { get; set; }
}

public class East

{
public string title { get; set; }
}

public class Buttons
{
public string save { get; set; }
}

public class Fields

{
public Labels labels { get; set; }
}

public class Labels
{
public string firstName { get; set; }
public string lastName { get; set; }
public string chooseLocale { get; set; }
}



To sum up, Locales has Region, Buttons and Fields. Region has Center and East. Center and East have property title. Fields has Labels which has properties firstName, lastName and chooseLocale.



In a method (called GetLocale) I have the following code:



Locale englishLang = new Locale(); 
englishLang.region.center.title = "Center Region";
englishLang.region.east.title = "East Region - Form";
englishLang.buttons.save = "Save";

englishLang.fields.labels.firstName = "First Name";
englishLang.fields.labels.lastName = "Last Name";
englishLang.fields.labels.chooseLocale = "Choose Your Locale";


When I run the code, a "NullReferenceException was unhandled by user code" is thrown at the line : englishLang.region.center.title = "Center Region";



Am I doing something wrong in the way I have set the properties title, save, firstName, lastName and chooseLocale?
I tried adding the following block of code after Locale englishLang = new Locale(); and before englishLang.region.center.title = "Center Region"; but I still get the error message.




Region region = new Region();
Center center = new Center();
East east = new East();
Buttons buttons = new Buttons();
Fields fields = new Fields();
Labels labels = new Labels();


What am I doing wrong?


Answer




Your Locales object never instantiates its properties, nor does the consuming code instantiate them. As reference types, the properties in that class have a default value of null. So when you do this:



Locale englishLang = new Locale();


The following values are null:



englishLang.region
englishLang.buttons
englishLang.fields



Thus, you'll receive a NullReferenceException if you try to de-reference those fields, like you do here:



englishLang.region.center.title = "Center Region";


That line of code attempts to de-reference englishLang.region by referring to its center property. But region is null because it hasn't been instantiated yet.



The best place to instantiate those in the case of these DTO classes would probably be in their constructors. Something like this:




public class Locales
{
public Region region { get; set; }
public Buttons buttons { get; set; }
public Fields fields { get; set; }

public Locales()
{
region = new Region();

buttons = new Buttons();
fields = new Fields();
}
}


That way consuming code doesn't have to do this manually each time, the fields are automatically instantiated by the constructor any time you create an instance of Locales. Naturally, you'll want to repeat this same pattern for your other objects.


jQuery deferreds and promises - .then() vs .done()



I've been reading about jQuery deferreds and promises and I can't see the difference between using .then() & .done() for successful callbacks. I know Eric Hynds mentions that .done() and .success() map to the same functionality but I'm guessing so does .then() as all the callbacks are all invoked on a completion of a successful operation.



Can anyone please enlighten me to the correct usage?



Answer



The callbacks attached to done() will be fired when the deferred is resolved. The callbacks attached to fail() will be fired when the deferred is rejected.



Prior to jQuery 1.8, then() was just syntactic sugar:



promise.then( doneCallback, failCallback )
// was equivalent to
promise.done( doneCallback ).fail( failCallback )



As of 1.8, then() is an alias for pipe() and returns a new promise, see here for more information on pipe().



success() and error() are only available on the jqXHR object returned by a call to ajax(). They are simple aliases for done() and fail() respectively:



jqXHR.done === jqXHR.success
jqXHR.fail === jqXHR.error


Also, done() is not limited to a single callback and will filter out non-functions (though there is a bug with strings in version 1.8 that should be fixed in 1.8.1):




// this will add fn1 to 7 to the deferred's internal callback list
// (true, 56 and "omg" will be ignored)
promise.done( fn1, fn2, true, [ fn3, [ fn4, 56, fn5 ], "omg", fn6 ], fn7 );


Same goes for fail().


oop - How do you create a static class in C++?




How do you create a static class in C++? I should be able to do something like:



cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;


Assuming I created the BitParser class. What would the BitParser class definition look like?


Answer



If you're looking for a way of applying the "static" keyword to a class, like you can in C# for example, then you won't be able to without using Managed C++.



But the looks of your sample, you just need to create a public static method on your BitParser object. Like so:




BitParser.h



class BitParser
{
public:
static bool getBitAt(int buffer, int bitIndex);

// ...lots of great stuff


private:
// Disallow creating an instance of this object
BitParser() {}
};


BitParser.cpp



bool BitParser::getBitAt(int buffer, int bitIndex)
{

bool isBitSet = false;
// .. determine if bit is set
return isBitSet;
}


You can use this code to call the method in the same way as your example code.



Hope that helps! Cheers.


multithreading - What so different about Node.js's event-driven? Can't we do that in ASP.Net's HttpAsyncHandler?



I'm not very experienced in web programming,
and I haven't actually coded anything in Node.js yet, just curious about the event-driven approach. It does seems good.



The article explains some bad things that could happen when we use a thread-based approach to handle requests, and should opt for a event-driven approach instead.
In thread-based, the cashier/thread is stuck with us until our food/resource is ready. While in event-driven, the cashier send us somewhere out of the request queue so we don't block other requests while waiting for our food.
To scale the blocking thread-based, you need to increase the number of threads.
To me this seems like a bad excuse for not using threads/threadpools properly.




Couldn't that be properly handled using IHttpAsyncHandler?
ASP.Net receives a request, uses the ThreadPool and runs the handler (BeginProcessRequest), and then inside it we load the file/database with a callback. That Thread should then be free to handle other requests. Once the file-reading is done, the ThreadPool is called into action again and executes the remaining response.
Not so different for me, so why is that not as scalable?



One of the disadvantages of the thread-based that I do know is, using threads needs more memory. But only with these, you can enjoy the benefits of multiple cores. I doubt Node.js is not using any threads/cores at all.



So, based on just the event-driven vs thread-based (don't bring the "because it's Javascript and every browser..." argument), can someone point me out what is the actual benefit of using Node.js instead of the existing technology?



That was a long question. Thanks :)



Answer



First of all, Node.js is not multi-threaded. This is important. You have to be a very talented programmer to design programs that work perfectly in a threaded environment. Threads are just hard.



You have to be a god to maintain a threaded project where it wasn't designed properly. There are just so many problems that can be hard to avoid in very large projects.



Secondly, the whole platform was designed to be run asynchronously. Have you see any ASP.NET project where every single IO interaction was asynchronous? simply put, ASP.NET was not designed to be event-driven.



Then, there's the memory footprint due to the fact that we have one thread per open-connection and the whole scaling issue. Correct me if I'm wrong but I don't know how you would avoid creating a new thread for each connection in ASP.NET.



Another issue is that a Node.js request is idle when it's not being used or when it's waiting for IO. On the other hand, a C# thread sleeps. Now, there is a limit to the number of these threads that can sleep. In Node.js, you can easily handle 10k clients at the same time in parallel on one development machine. You try handling 10k threads in parallel on one development machine.




JavaScript itself as a language makes asynchronous coding easier. If you're still in C# 2.0, then the asynchronous syntax is a real pain. A lot of developers will simply get confused if you're defining Action<> and Function<> all over the place and using callbacks. An ASP.NET project written in an evented way is just not maintainable by an average ASP.NET developer.



As for threads and cores. Node.js is single-threaded and scales by creating multiple-node processes. If you have a 16 core then you run 16 instances of your node.js server and have a single Node.js load balancer in front of it. (Maybe a nginx load balancer if you want).



This was all written into the platform at a very low-level right from the beginning. This was not some functionality bolted on later down the line.



Other advantages



Node.js has a lot more to it then above. Above is only why Node.js' way of handling the event loop is better than doing it with asynchronous capabilities in ASP.NET.





  • Performance. It's fast. Real fast.

  • One big advantage of Node.js is its low-level API. You have a lot of control.

  • You have the entire HTTP server integrated directly into your code then outsourced to IIS.

  • You have the entire nginx vs Apache comparison.

  • The entire C10K challenge is handled well by node but not by IIS

  • AJAX and JSON communication feels natural and easy.

  • Real-time communication is one of the great things about Node.js. It was made for it.

  • Plays nicely with document-based nosql databases.


  • Can run a TCP server as well. Can do file-writing access, can run any unix console command on the server.

  • You query your database in javascript using, for example, CouchDB and map/reduce. You write your client in JavaScript. There are no context switches whilst developing on your web stack.

  • Rich set of community-driven open-source modules. Everything in node.js is open source.

  • Small footprint and almost no dependencies. You can build the node.js source yourself.



Disadvantages of Node.js



It's hard. It's young. As a skilled JavaScript developer, I face difficulty writing a website with Node.js just because of its low-level nature and the level of control I have. It feels just like C. A lot of flexibility and power either to be used for me or to hang me.




The API is not frozen. It's changing rapidly. I can imagine having to rewrite a large website completely in 5 years because of the amount Node.js will be changed by then. It is do-able, you just have to be aware that maintenance on node.js websites is not cheap.



further reading



http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/



http://blip.tv/file/2899135



http://nodeguide.com/


php - The second argument to copy() function cannot be a directory and move_uploaded_file(): Unable to move




in the code




if(isset($_POST['submit'])){


$post_image=$_FILES['post_image']['name'];
$post_image_tmp=$_FILES['post_image']['tmp_name'];

if($post_image='' ){
echo "";

exit();

}
else{

move_uploaded_file($post_image_tmp,"news_images/$post_image");
?>


I get this error





Warning: move_uploaded_file(): The second argument to copy() function
cannot be a directory in C:\xampp\htdocs\MyCMS\admin\insert_post.php
on line 107



Warning: move_uploaded_file(): Unable to move
'C:\xampp\tmp\php946C.tmp' to 'news_images/' in
C:\xampp\htdocs\MyCMS\admin\insert_post.php on line 107





Please help I'am just newbie.


Answer



= is assignment operator.
use comparison operator == here.



if($post_image == '' ) {

enumeration - Iterate Between Enum Values in C#





Possible Duplicate:
How to enumerate an enum?







Suppose that i have an enumeration like that:



public enum Cars
{
Audi = 0,
BMW,
Opel,
Renault,
Fiat,

Citroen,
AlfaRomeo,
}


Do i have a chance to iterate between Opel and Citroen? I want to give these values as parameters of a method.


Answer



This will work:



for(Cars car=Cars.Opel; car<=Cars.Citroen; car++)

{
Console.WriteLine(car);
}


but you have to make sure that the start value is less than the end value.



EDIT
If you don't hardcode the start and end, but supply them as parameters, you need to use them in the correct order. If you just switch "Opel" and "Citroen", you will get no output.



Also (as remarked in the comments) the underlying integer values must not contain gaps or overlaps. Luckily if you do not specify values yourself (even the '=0' is not needed), this will be the default behaviour. See MSDN:





When you do not specify values for the elements in the enumerator list, the values are automatically incremented by 1.



java - Parsing Xml with SAX Parser



I am trying to parse an xml file with SAX Parser.
I need to get attributes and it's values of a start element







Operation Succeeded



Service-Type = Frames-User, Framed-Protocol = PPP, Framed-Routing = None










IN this xml, I need to get Settings tag/start element attributes along with it's values.



These attributes are dynamic, so I am trying to make a map of them. I am new to SAX Parser.



So far my java code:




public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {

if (elementName.equalsIgnoreCase(GenericConstants.INFO)) {
this.searchRaidusBean.setServer(attributes.getValue(GenericConstants.SERVER));
this.searchRaidusBean.setFunction(attributes.getValue(GenericConstants.FUNCTION));
}
if (elementName.equalsIgnoreCase(GenericConstants.RESULT)) {
this.searchRaidusBean.setResultCode(attributes.getValue(GenericConstants.CODE));
}


if (elementName.equalsIgnoreCase(GenericConstants.ACCOUNT)) {
this.searchRaidusBean.setLoginId(attributes.getValue(GenericConstants.LOGIN));
}
if (elementName.equalsIgnoreCase(GenericConstants.ACCOUNT)) {
this.searchRaidusBean.setSkyNum(attributes.getValue(GenericConstants.SKYNUM));
}
if (elementName.equalsIgnoreCase(GenericConstants.ACCOUNT)) {
this.searchRaidusBean.setMaxAliases(attributes.getValue(GenericConstants.MAXALIASES));
}

if (elementName.equalsIgnoreCase(GenericConstants.ACCOUNT)) {
this.searchRaidusBean.setCreationDate(attributes.getValue(GenericConstants.CREATION_DATE));
}
if (elementName.equalsIgnoreCase(GenericConstants.ACCOUNT)) {
this.searchRaidusBean.setType(attributes.getValue(GenericConstants.TYPE));
}
if (elementName.equalsIgnoreCase(GenericConstants.ACCOUNT)) {
this.searchRaidusBean.setStatus(attributes.getValue(GenericConstants.STATUS));
}
if (elementName.equalsIgnoreCase(GenericConstants.ACCOUNT)) {

this.searchRaidusBean.setMnemonic(attributes.getValue(GenericConstants.MNEMONIC));
}
if (elementName.equalsIgnoreCase(GenericConstants.ACCOUNT)) {
this.searchRaidusBean.setRateLimit(attributes.getValue(GenericConstants.RATELIMIT));
}
if (elementName.equalsIgnoreCase(GenericConstants.SETTINGS)) {
//this.searchRaidusBean.getBitval().add(attributes.getValue(GenericConstants.BITVAL));
System.out.println(attributes);
//stuck here
}

if (elementName.equalsIgnoreCase(GenericConstants.ALIASES)) {
this.tempKey = attributes.getValue(GenericConstants.MNEMONIC);
}
}



public void endElement(String str1, String str2, String element) throws SAXException {
if (element.equalsIgnoreCase(GenericConstants.RESULT)) {
this.searchRaidusBean.setResultMessage(this.tempValue);

}
if (element.equalsIgnoreCase(GenericConstants.ALIASES)) {
if (!StringUtils.isBlank(this.tempKey)) {
this.searchRaidusBean.getAlias().put(this.tempKey, this.tempValue);
}
}
}


public void characters(char[] charArray, int i, int j) throws SAXException {

this.tempValue = new String(charArray, i, j);
}

Answer



If you are using the DefaultHandler, then you will be receiving a startElement event.



This method carries the Attributes as one of it's parameters.



You will need to use getIndex(String) to get the index of the named attribute and getValue(int) to get the value of said attribute.




As Nambari has pointed out, there are hundreds of tutorials on the internet and more then a few posts on the subject on SO (I answered one over the weekend).



UPDATED



I'd suggest it should look something like this (I've not tested it)



public void startElement(String uri, String localName, String elementName, Attributes attributes) throws SAXException {

if (elementName.equalsIgnoreCase(GenericConstants.INFO)) {
this.searchRaidusBean.setServer(attributes.getValue(GenericConstants.SERVER));

this.searchRaidusBean.setFunction(attributes.getValue(GenericConstants.FUNCTION));
}
if (elementName.equalsIgnoreCase(GenericConstants.RESULT)) {
this.searchRaidusBean.setResultCode(attributes.getValue(GenericConstants.CODE));
}

if (elementName.equalsIgnoreCase(GenericConstants.ACCOUNT)) {
this.searchRaidusBean.setLoginId(attributes.getValue(GenericConstants.LOGIN));
this.searchRaidusBean.setSkyNum(attributes.getValue(GenericConstants.SKYNUM));
this.searchRaidusBean.setMaxAliases(attributes.getValue(GenericConstants.MAXALIASES));

this.searchRaidusBean.setCreationDate(attributes.getValue(GenericConstants.CREATION_DATE));
this.searchRaidusBean.setType(attributes.getValue(GenericConstants.TYPE));
this.searchRaidusBean.setStatus(attributes.getValue(GenericConstants.STATUS));
this.searchRaidusBean.setMnemonic(attributes.getValue(GenericConstants.MNEMONIC));
this.searchRaidusBean.setRateLimit(attributes.getValue(GenericConstants.RATELIMIT));
}

if (elementName.equalsIgnoreCase(GenericConstants.SETTINGS)) {

for (int index = 0; index < attributes.getLength(); index++) {


String attName = attributes.getLocalName(index);
String value = attributes.getValue(index);

map.put(attName, value);

}

}


if (elementName.equalsIgnoreCase(GenericConstants.ALIASES)) {
this.tempKey = attributes.getValue(GenericConstants.MNEMONIC);
}

}


UPDATED with tested example



I took you data (from the OP) and run it through the following handler




DefaultHandler handler = new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

if (qName.equalsIgnoreCase("settings")) {

System.out.println("Parse settings attributes...");

for (int index = 0; index < attributes.getLength(); index++) {


String aln = attributes.getLocalName(index);
String value = attributes.getValue(index);

System.out.println(" " + aln + " = " + value);


}

}


}
};


And I got the following output



Parse settings attributes...
bitval = 4
status = open

Parse settings attributes...
bitval = 8192
status = open
session_timeout = 10800
Parse settings attributes...
bitval = 32768
status = open
cisco_address_pool = thepool



So I don't know what you're doing.


c - Under what circumstances (if ever) does strcat() hang?



I have this code in a function in C:




char* root = "/home/OS/homework/user/honorsupgrade/HTML";
requestInfo->resource = "/bing"
printf("1\n");
int counter = 0;
for(counter = 0; counter < 100; counter++)
{
if(root[counter] == '\0')
{
printf("True1\n");

break;
}
}
for(counter = 0; counter < 100; counter++)
{
if(requestInfo->resource[counter] == '\0')
{
printf("True2\n");
break;
}

}
printf("2\n");
fflush(stdout);
strcat(root, requestInfo->resource);
printf("3\n");
fflush(stdout);
return open(root, 0_RDONLY);


...




Request Info's stuff, as needed



struct ReqInfo
{
char *resource;
}


I have created two string (character pointers) in C, but for some reason when I pass these methods to strcat(), strcat() never returns. This causes the program to hang. I have tested to ensure that both strings have null terminators (so strcat isn't trying to concatenate more than it should). The program will print 1 and 2, but never print 3, meaning it never gets past the strcat() call, as I am flushing the buffer to make sure that there isn't a problem there. \




EDIT: I've created the struct outside of this block of code, I'm getting the same issues when replacing "requestInfo->resource" with a char* resource and making it "/bing"


Answer



Attempting to write to const char *



Even though char* root is a char *, it really points to a const char *. And writing to that is undefined behavior.



char* root = "/home/OS/homework/user/honorsupgrade/HTML";
....
strcat(root, requestInfo->resource);



Code should allocate a right sized working buffer instead.



char buffer[1000];
strcpy(buffer, root);
strcat(buffer, requestInfo->resource);

c - Capture quoted strings separated with commas from a file




let's say I want to take an input from a file like this :-



"8313515769001870,GRKLK,03/2023,eatcp,btlzg"
"6144115684794523,ZEATL,10/2033,arnne,drrfd"


for a structure I made as follows



typedef struct{

char Card_Number[20];
char Bank_Code[6];
char Expiry_Date[8];
char First_Name[30];
char Last_Name[30];
}Card;


This is my attempt to read the input from a file named 'file' in the reading mode, the str in fgets is storing the right string but it isn't getting absorbed c[i]:




FILE * fptr;
int count=0;
fptr= fopen("file","r");
Card *c = (Card*)calloc(10,sizeof(Card));
printf("StartAlloc\n");
int i=0;
char str[1000];
fgets(str,80,fptr);
if(fptr==NULL)
{return 0;}

do{
sscanf(str,"\"%[^,],%[^,],%[^,],%[^,],%[^,]\" \n",c[i].Card_Number,c[i].Bank_Code,c[i].Expiry_Date,c[i].First_Name,c[i].Last_Name);
i++;

}while(fgets(str,80,fptr)!=NULL);


I do not understand why the regex %[^,] is not capturing the individual elements, I have wasted a lot of time, and help would be greatly appreciated.


Answer



Using fscanf() with the proper format you can retrieve the desired elements from each line :




"\"%[^,]%*c %[^,]%*c %[^,]%*c %[^,]%*c %[^\"]%*c\n" 



With the previous format, the opening quote is ignored (\"), and the strings separated by commas are captured (%[^,]%*c). Finally the the closing quote is discarded (%[^\"]%*c), and the line break considered (\n), to let next line to be read.




This is how you can integrate it in your code :




while (fscanf(file, "\"%[^,]%*c %[^,]%*c %[^,]%*c %[^,]%*c %[^\"]%*c\n", c[i].Card_Number, c[i].Bank_Code, c[i].Expiry_Date, c[i].First_Name, c[i].Last_Name) != -1 ) i++;


Complete code snippet for testing purposes :



#include 
#include

typedef struct{
char Card_Number[20];

char Bank_Code[6];
char Expiry_Date[8];
char First_Name[30];
char Last_Name[30];
}Card;

int main(){
FILE *file;
file = fopen("data.csv", "r");
int i=0;

Card *c = (Card*)calloc(10,sizeof(Card));

while (fscanf(file, "\"%[^,]%*c %[^,]%*c %[^,]%*c %[^,]%*c %[^\"]%*c\n", c[i].Card_Number, c[i].Bank_Code, c[i].Expiry_Date, c[i].First_Name, c[i].Last_Name) != -1 ) {
printf("%s | %s | %s | %s | %s \n", c[i].Card_Number, c[i].Bank_Code, c[i].Expiry_Date, c[i].First_Name, c[i].Last_Name);
i++;
}
fclose(file);
return 0;
}


PHP Removing elements from an array




I am new to PHP and I need a function that enables me to remove an item from an array.




So far I have:



 $ab = milk
$ba = apple
$ca = bread

array($ab, $ba, $ca).



Is there a function or method available to delete $ba from the list?



      I.e  if (condition)==true

array_delete ($ab): ($ab, $ba, $ca)


Obviously the above does not work, or exist, but I am looking for something like it that does exist.



Any help would be huugely appreciated!




Thanks


Answer



you can try this:



$ab = milk;
$ba = apple;
$ca = bread;

$arr=array($ab, $ba, $ca);

if (in_array($ba, $arr))
{
unset($ba);
}


hope this may help you..


java - ThreeTen-Backport error on Android - ZoneRulesException: No time-zone data files registered



I'm using ThreeTen-Backport library for my Android project (because java.time is not yet implemented in android development).



When I write LocalDate today=LocalDate.now(); or LocalTime time=LocalTime.now(); I get the following exception:



Caused by: org.threeten.bp.zone.ZoneRulesException: 
No time-zone data files registered
at org.threeten.bp.zone.ZoneRulesProvider.getProvider(ZoneRulesProvider.java:176)

at org.threeten.bp.zone.ZoneRulesProvider.getRules(ZoneRulesProvider.java:133)
at org.threeten.bp.ZoneRegion.ofId(ZoneRegion.java:143)
at org.threeten.bp.ZoneId.of(ZoneId.java:357)
at org.threeten.bp.ZoneId.of(ZoneId.java:285)
at org.threeten.bp.ZoneId.systemDefault(ZoneId.java:244)
at org.threeten.bp.Clock.systemDefaultZone(Clock.java:137)
at org.threeten.bp.LocalDate.now(LocalDate.java:165)


The same line of code works well in another java project I have, which uses the native java.time library.




I searched for a possible solution but couldn't find anything useful: one solution suggested I need to use another jar that includes the time-zone rules and other suggested that there might be two or more ThreeTenBP-libraries inside the classpath.
Those cases don't match my case.



Inside the build.gradle file, at the dependencies section, I've tried few configurations:




  • At first, I used - compile 'com.jakewharton.threetenabp:threetenabp:1.0.3'

  • Then, I tried -
    compile 'org.threeten:threetenbp:1.0.3'

  • After that, I tried -

    compile 'org.threeten:threetenbp:1.3.1'

  • Currently, I use compile 'org.threeten:threetenbp:1.3.2'



I don't know what is wrong with that line of code and how to fix it.
The LocalDate.now() and LocalTime.now() methods should work without specifying a time zone.


Answer



For Android project you should use



implementation 'com.jakewharton.threetenabp:threetenabp:1.0.3'



Make sure you call AndroidThreeTen.init(this); before using the classes from the library. This will read the time zones data (included in the library). You can initialize the library in your Application class in the onCreate method just like it is recommended in the README.


syntax - What does ":" mean in PHP?





Possible Duplicate:
What is “:” in PHP?






What does the : mean in the following PHP code?



    while (have_posts()) : the_post();
?>

Answer



It's called an Alternative Syntax For Control Structures. You should have an endwhile; somewhere after that. Basically, it allows you to omit braces {} from a while to make it look "prettier"...



As far as your edit, it's called the Ternary Operator (it's the third section). Basically it's an assignment shorthand.



$foo = $first ? $second : $third;


is the same as saying (Just shorter):



if ($first) {
$foo = $second;
} else {
$foo = $third;
}

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...