Thursday, 29 August 2019

dispose - Implementing IDisposable in C#




I am trying to implement IDisposable in a sample program. If I use SqlConnection class inside a using block statement, it will automatically dispose it.




public int testCon()
{
using (SqlConnection conn = new SqlConnection("Conn string"))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT COUNT(1) FROM Carsd";

return (int)cmd.ExecuteScalar();

}
}
}


I have created a class and implemented IDisposable. I have created a new instance inside a using block statement.



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

{
testDispose objTestDispose;

using (objTestDispose = new testDispose())
{
objTestDispose.UserName = "testUser";
objTestDispose.PassWord = "testPassword";
}

Console.WriteLine("Check obj of testDispose Class" + objTestDispose.UserName);

Console.WriteLine("Check obj of testDispose Class" + objTestDispose.PassWord);
Console.ReadLine();

}
}

public class testDispose : IDisposable
{
public string UserName { get; set; }
public string PassWord { get; set; }


public void Dispose()
{ }
}


I believe, using block automatically call dispose method. So, if I am create a new instance in using block, it would be dispose after existing using block. But, still I am able to access objTestDispose object outside of the using block.WHY?



Please suggest.




UDPATE



Mr.BWA..Thank you for the making my question duplicate. but you should know I am a student and learning. I have this question in my mind so I have asked here.
**You can not say that IDisposable interface only for unmanaged resources.**I can also remove managed resources. It depends on the situation. As per the below link -




What if your object has allocated a 250MB System.Drawing.Bitmap (i.e. the .NET managed Bitmap class) as some sort of frame buffer? Sure, this is a managed .NET object, and the garbage collector will free it. But do you really want to leave 250MB of memory just sitting there – waiting for the garbage collector to eventually come along and free it? What if there's an open database connection? Surely we don't want that connection sitting open, waiting for the GC to finalize the object.



If the user has called Dispose() (meaning they no longer plan to use
the object) why not get rid of those wasteful bitmaps and database

connections?



So now we will:



get rid of unmanaged resources (because we have to), and get rid of
managed resources (because we want to be helpful)



Answer



Dispose is being called, but it doesn't do anything to destroy the object itself (you'll note that a lot of IDiposable classes within the Framework additionally have a IsDisposed property to indicate whether the unmanaged resources have been released or not)


sort array on specific value with php

I have an array with specific values in it and i would like to sort the array on a specific value in it. For instance, TOTCOM_METIER DESC.
Ex :




Array
(
[0] => Array
(
[TOTCOM_METIER] => 1
[metier] => Traiteur
)

[1] => Array

(
[TOTCOM_METIER] => 4
[metier] => Restauration traditionnelle
)

[2] => Array
(
[TOTCOM_METIER] => 2
[metier] => Coiffure
)


)


I would like to sort it on TOTCOM_METIER DESC to have this result :



Array
(
[0] => Array
(

[TOTCOM_METIER] => 4
[metier] => Restauration traditionnelle
)

[1] => Array
(
[TOTCOM_METIER] => 2
[metier] => Coiffure
)


[2] => Array
(
[TOTCOM_METIER] => 1
[metier] => Traiteur
)

)

email - Sent Mail in PHP throw 504 Gateway Time-out

I'm on Ubuntu VM.



I have this PHP





# --------------------------------------------------------------------------------
# Goal : send an email
# Run : curl 45.55.88.57/code/mail.php | php


$to = 'email@gmail.com';
$subject = '';

$message = 'hello';
$headers = 'From: john@gmail.com' . "\r\n" .
'Reply-To: john@gmail.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>






I ran this :



curl 45.55.88.57/code/mail.php  | php


I get this



  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Dload Upload Total Spent Left Speed

100 176 100 176 0 0 2 0 0:01:28 0:01:00 0:00:28 45

504 Gateway Time-out

504 Gateway Time-out



nginx






Is my code is wrong, or is something wrong with my VM?



I don't get any emails.

javascript - Returning a value from callback function in Node.js





I am facing small trouble in returning a value from callback function in Node.js, I will try to explain my situation as easy as possible. Consider I have a snippet, which takes URL and hits that url and gives the output:



urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {                              
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
});


I tried to wrap it inside a function and return a value like this:




function doCall(urlToCall) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return finalData;
});
}


Because in my Node.js code, I have a lot of if-else statement where value of urlToCall will be decided, like this:




if(//somecondition) {
urlToCall = //Url1;
} else if(//someother condition) {
urlToCall = //Url2;
} else {
urlToCall = //Url3;
}



The thing is all of the statements inside a urllib.request will remain same, except value of urlToCall. So definitely I need to put those common code inside a function. I tried the same but in doCall will always return me undefined. I tried like this:



response = doCall(urlToCall);
console.log(response) //Prints undefined


But if I print value inside doCall() it prints perfectly, but it will always return undefined. As per my research I came to know that we cannot return values from callback functions! (is it true)? If yes, can anyone advice me how to handle this situation, as I want to prevent duplicate code in every if-else blocks.


Answer



Its undefined because, console.log(response) runs before doCall(urlToCall); is finished. You have to pass in a callback function aswell, that runs when your request is done.




First, your function. Pass it a callback:



function doCall(urlToCall, callback) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return callback(finalData);
});
}



Now:



var urlToCall = "http://myUrlToCall";
doCall(urlToCall, function(response){
// Here you have access to your variable
console.log(response);
})



@Rodrigo, posted a good resource in the comments. Read about callbacks in node and how they work. Remember, it is asynchronous code.


arguments - Reference — What does this symbol mean in PHP?




What is this?



This is a collection of questions that come up every now and then about syntax in PHP. This is also a Community Wiki, so everyone is invited to participate in maintaining this list.



Why is this?



It used to be hard to find questions about operators and other syntax tokens.¹
The main idea is to have links to existing questions on , so it's easier for us to reference them, not to copy over content from the PHP Manual.



Note: Since January 2013, does support special characters. Just surround the search terms by quotes, e.g. [php] "==" vs "==="




What should I do here?



If you have been pointed here by someone because you have asked such a question, please find the particular syntax below. The linked pages to the PHP manual along with the linked questions will likely answer your question then. If so, you are encouraged to upvote the answer. This list is not meant as a substitute to the help others provided.



The List



If your particular token is not listed below, you might find it in the List of Parser Tokens.







& Bitwise Operators or References








=& References









&= Bitwise Operators








&& Logical Operators









% Arithmetic Operators









!! Logical Operators








@ Error Control Operators









?: Ternary Operator








?? Null Coalesce Operator (since PHP 7)









?string
?int
?array
?bool
?float Nullable return type declaration (since PHP 7.1)









: Alternative syntax for control structures, Ternary Operator









:: Scope Resolution Operator








\ Namespaces









-> Classes And Objects








=> Arrays









^ Bitwise Operators









>> Bitwise Operators








<< Bitwise Operators









<<< Heredoc or Nowdoc








= Assignment Operators









== Comparison Operators









=== Comparison Operators








!== Comparison Operators









!= Comparison Operators








<> Comparison Operators









<=> Comparison Operators (since PHP 7.0)









| Bitwise Operators








|| Logical Operators









~ Bitwise Operators








+ Arithmetic Operators, Array Operators









+= and -= Assignment Operators









++ and -- Incrementing/Decrementing Operators








.= Assignment Operators









. String Operators








, Function Arguments






, Variable Declarations








$$ Variable Variables









` Execution Operator









Short Open Tags








[] Arrays (short syntax since PHP 5.4)









Opening and Closing tags








... Argument unpacking (since PHP 5.6)







** Exponentiation (since PHP 5.6)






# One-line shell-style comment









:? Nullable return types







Answer



Incrementing / Decrementing Operators




++ increment operator



-- decrement operator



Example    Name              Effect
---------------------------------------------------------------------
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.

$a-- Post-decrement Returns $a, then decrements $a by one.


These can go before or after the variable.



If put before the variable, the increment/decrement operation is done to the variable first then the result is returned. If put after the variable, the variable is first returned, then the increment/decrement operation is done.



For example:



$apples = 10;

for ($i = 0; $i < 10; ++$i) {
echo 'I have ' . $apples-- . " apples. I just ate one.\n";
}


Live example



In the case above ++$i is used, since it is faster. $i++ would have the same results.



Pre-increment is a little bit faster because it really increments the variable and after that 'returns' the result. Post-increment creates a special variable, copies there the value of the first variable and only after the first variable is used, replaces its value with second's.




However, you must use $apples--, since first, you want to display the current number of apples, and then you want to subtract one from it.



You can also increment letters in PHP:



$i = "a";
while ($i < "c") {
echo $i++;
}



Once z is reached aa is next, and so on.




Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.







Posts:





Wednesday, 28 August 2019

regex - Does lookaround affect which languages can be matched by regular expressions?



There are some features in modern regex engines which allow you to match languages that couldn't be matched without that feature. For example the following regex using back references matches the language of all strings that consist of a word that repeats itself: (.+)\1. This language is not regular and can't be matched by a regex that does not use back references.




Does lookaround also affect which languages can be matched by a regular expression? I.e. are there any languages that can be matched using lookaround that couldn't be matched otherwise? If so, is this true for all flavors of lookaround (negative or positive lookahead or lookbehind) or just for some of them?


Answer



As the other answers claim, lookarounds don't add any extra power to regular expressions.



I think we can show this using the following:



One Pebble 2-NFA (see the Introduction section of the paper which refers to it).



The 1-pebble 2NFA does not deal with nested lookaheads, but, we can use a variant of multi-pebble 2NFAs (see section below).




Introduction



A 2-NFA is a non deterministic finite automaton which has the ability to move either left or right on it's input.



A one pebble machine is where the machine can place a pebble on the input tape (i.e. mark a specific input symbol with a pebble) and do possibly different transitions based on whether there is a pebble at the current input position or not.



It is known the One Pebble 2-NFA has the same power as a regular DFA.



Non-nested Lookaheads




The basic idea is as follows:



The 2NFA allows us to backtrack (or 'front track') by moving forward or backward in the input tape. So for a lookahead we can do the match for the lookahead regular expression and then backtrack what we have consumed, in matching the lookahead expression. In order to know exactly when to stop backtracking, we use the pebble! We drop the pebble before we enter the dfa for the lookahead to mark the spot where the backtracking needs to stop.



Thus at the end of running our string through the pebble 2NFA, we know whether we matched the lookahead expression or not and the input left (i.e. what is left to be consumed) is exactly what is required to match the remaining.



So for a lookahead of the form u(?=v)w



We have the DFAs for u, v and w.




From the accepting state (yes, we can assume there is only one) of DFA for u, we make an e-transition to the start state of v, marking the input with a pebble.



From an accepting state for v, we e-transtion to a state which keeps moving the input left, till it finds a pebble, and then transitions to start state of w.



From a rejecting state of v, we e-transition to a state which keeps moving left until it finds the pebble, and transtions to the accepting state of u (i.e where we left off).



The proof used for regular NFAs to show r1 | r2, or r* etc, carry over for these one pebble 2nfas. See http://www.coli.uni-saarland.de/projects/milca/courses/coal/html/node41.html#regularlanguages.sec.regexptofsa for more info on how the component machines are put together to give the bigger machine for the r* expression etc.



The reason why the above proofs for r* etc work is that the backtracking ensures that the input pointer is always at the right spot, when we enter the component nfas for repetition. Also, if a pebble is in use, then it is being processed by one of the lookahead component machines. Since there are no transitions from lookahead machine to lookahead machine without completely backtracking and getting back the pebble, a one pebble machine is all that is needed.




For eg consider ([^a] | a(?=...b))*



and the string abbb.



We have abbb which goes through the peb2nfa for a(?=...b), at the end of which we are at the state: (bbb, matched) (i.e in input bbb is remaining, and it has matched 'a' followed by '..b'). Now because of the *, we go back to the beginning (see the construction in the link above), and enter the dfa for [^a]. Match b, go back to beginning, enter [^a] again two times, and then accept.



Dealing with Nested Lookaheads



To handle nested lookaheads we can use a restricted version of k-pebble 2NFA as defined here: Complexity Results for Two-Way and Multi-Pebble Automata and their Logics (see Definition 4.1 and Theorem 4.2).




In general, 2 pebble automata can accept non-regular sets, but with the following restrictions, k-pebble automata can be shown to be regular (Theorem 4.2 in above paper).



If the pebbles are P_1, P_2, ..., P_K




  • P_{i+1} may not be placed unless P_i is already on the tape and P_{i} may not be picked up unless P_{i+1} is not on the tape. Basically the pebbles need to be used in a LIFO fashion.


  • Between the time P_{i+1} is placed and the time that either P_{i} is picked up or P_{i+2} is placed, the automaton can traverse only the subword located between the current location of P_{i} and the end of the input word that lies in the direction of P_{i+1}. Moreover, in this sub-word, the automaton can act only as a 1-pebble automaton with Pebble P_{i+1}. In particular it is not allowed to lift up, place or even sense the presence of another pebble.




So if v is a nested lookahead expression of depth k, then (?=v) is a nested lookahead expression of depth k+1. When we enter a lookahead machine within, we know exactly how many pebbles have to have been placed so far and so can exactly determine which pebble to place and when we exit that machine, we know which pebble to lift. All machines at depth t are entered by placing pebble t and exited (i.e. we return to processing of a depth t-1 machine) by removing pebble t. Any run of the complete machine looks like a recursive dfs call of a tree and the above two restrictions of the multi-pebble machine can be catered to.




Now when you combine expressions, for rr1, since you concat, the pebble numbers of r1 must be incremented by the depth of r. For r* and r|r1 the pebble numbering remains the same.



Thus any expression with lookaheads can be converted to an equivalent multi-pebble machine with the above restrictions in pebble placement and so is regular.



Conclusion



This basically addresses the drawback in Francis's original proof: being able to prevent the lookahead expressions from consuming anything which are required for future matches.



Since Lookbehinds are just finite string (not really regexs) we can deal with them first, and then deal with the lookaheads.




Sorry for the incomplete writeup, but a complete proof would involve drawing a lot of figures.



It looks right to me, but I will be glad to know of any mistakes (which I seem to be fond of :-)).


analysis - Why is the bride's name beeped in Kill Bill Vol 1? - Movies & TV



In the movie Kill Bill Vol.1, whenever someone mentions the bride by her name




Beatrix Kiddo




Her name is censored with a beep. Is this explained somewhere in the movie? Or is it just a signature that Tarantino leaves?


Answer




Well for the first film and for most of the second, the Bride is on a revenge mission where she is hunting her victims. Her identity would have to be a secret to make sure she doesn't get followed or caught.



It could be Tarantino's way of breaking the 4th wall and including us in the element of mystery and disguise that the Bride has to undertake to remain anonymous. Also, this could mean we are meant to detached emotionally from her as a character until her name is finally revealed as Beatrix Kiddo by Elle Driver.



This is when we see the character as fully vulnerable and when she opens up her emotions. So Tarantino thought of this as the opportune moment to unveil all secrets of this character.



Or perhaps it was just Tarantino being weird and awesome.


php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...