Programs & Examples On #Sharepoint upgrade

Pass Javascript variable to PHP via ajax

Pass the data like this to the ajax call (http://api.jquery.com/jQuery.ajax/):

data: { userID : userID }

And in your PHP do this:

if(isset($_POST['userID']))
{
    $uid = $_POST['userID'];

    // Do whatever you want with the $uid
}

isset() function's purpose is to check wheter the given variable exists, not to get its value.

Running an Excel macro via Python?

A variation on SMNALLY's code that doesn't quit Excel if you already have it open:

import os, os.path
import win32com.client
    
if os.path.exists("excelsheet.xlsm"):
    xl=win32com.client.Dispatch("Excel.Application")
    wb = xl.Workbooks.Open(os.path.abspath("excelsheet.xlsm"), ReadOnly=1) #create a workbook object
    xl.Application.Run("excelsheet.xlsm!modulename.macroname")
    wb.Close(False) #close the work sheet object rather than quitting excel
    del wb
    del xl

Strings in C, how to get subString

char* someString = "abcdedgh";
char* otherString = 0;

otherString = (char*)malloc(5+1);
memcpy(otherString,someString,5);
otherString[5] = 0;

UPDATE:
Tip: A good way to understand definitions is called the right-left rule (some links at the end):

Start reading from identifier and say aloud => "someString is..."
Now go to right of someString (statement has ended with a semicolon, nothing to say).
Now go left of identifier (* is encountered) => so say "...a pointer to...".
Now go to left of "*" (the keyword char is found) => say "..char".
Done!

So char* someString; => "someString is a pointer to char".

Since a pointer simply points to a certain memory address, it can also be used as the "starting point" for an "array" of characters.

That works with anything .. give it a go:

char* s[2]; //=> s is an array of two pointers to char
char** someThing; //=> someThing is a pointer to a pointer to char.
//Note: We look in the brackets first, and then move outward
char (* s)[2]; //=> s is a pointer to an array of two char

Some links: How to interpret complex C/C++ declarations and How To Read C Declarations

Using an attribute of the current class instance as a default value for method's parameter

It's written as:

def my_function(self, param_one=None): # Or custom sentinel if None is vaild
    if param_one is None:
        param_one = self.one_of_the_vars

And I think it's safe to say that will never happen in Python due to the nature that self doesn't really exist until the function starts... (you can't reference it, in its own definition - like everything else)

For example: you can't do d = {'x': 3, 'y': d['x'] * 5}

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

A DateTime in C# is a value type, not a reference type, and therefore cannot be null. It can however be the constant DateTime.MinValue which is outside the range of Sql Servers DATETIME data type.

Value types are guaranteed to always have a (default) value (of zero) without always needing to be explicitly set (in this case DateTime.MinValue).

Conclusion is you probably have an unset DateTime value that you are trying to pass to the database.

DateTime.MinValue = 1/1/0001 12:00:00 AM
DateTime.MaxValue = 23:59:59.9999999, December 31, 9999, 
                    exactly one 100-nanosecond tick 
                    before 00:00:00, January 1, 10000

MSDN: DateTime.MinValue


Regarding Sql Server

datetime
Date and time data from January 1, 1753 through December 31, 9999, to an accuracy of one three-hundredth of a second (equivalent to 3.33 milliseconds or 0.00333 seconds). Values are rounded to increments of .000, .003, or .007 seconds

smalldatetime
Date and time data from January 1, 1900, through June 6, 2079, with accuracy to the minute. smalldatetime values with 29.998 seconds or lower are rounded down to the nearest minute; values with 29.999 seconds or higher are rounded up to the nearest minute.

MSDN: Sql Server DateTime and SmallDateTime


Lastly, if you find yourself passing a C# DateTime as a string to sql, you need to format it as follows to retain maximum precision and to prevent sql server from throwing a similar error.

string sqlTimeAsString = myDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff");

Update (8 years later)

Consider using the sql DateTime2 datatype which aligns better with the .net DateTime with date range 0001-01-01 through 9999-12-31 and time range 00:00:00 through 23:59:59.9999999

string dateTime2String = myDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffffff");

MSDN datetime2 (Transact-SQL)

How to kill all active and inactive oracle sessions for user

The KILL SESSION command doesn't actually kill the session. It merely asks the session to kill itself. In some situations, like waiting for a reply from a remote database or rolling back transactions, the session will not kill itself immediately and will wait for the current operation to complete. In these cases the session will have a status of "marked for kill". It will then be killed as soon as possible.

Check the status to confirm:

SELECT sid, serial#, status, username FROM v$session;

You could also use IMMEDIATE clause:

ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE;

The IMMEDIATE clause does not affect the work performed by the command, but it returns control back to the current session immediately, rather than waiting for confirmation of the kill. Have a look at Killing Oracle Sessions.

Update If you want to kill all the sessions, you could just prepare a small script.

SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;' FROM v$session;

Spool the above to a .sql file and execute it, or, copy paste the output and run it.

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

And what something like this?

public class Carrier : Entity
{
    public Carrier()
    {
         this.Id = Guid.NewGuid();
    }  
    public Guid Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

An unhandled exception was generated during the execution of the current web request

As far as I understand, you have more than one form tag in your web page that causes the problem. Make sure you have only one server-side form tag for each page.

Is there an equivalent for var_dump (PHP) in Javascript?

console.log(OBJECT|ARRAY|STRING|...);
console.info(OBJECT|ARRAY|STRING|...);
console.debug(OBJECT|ARRAY|STRING|...);
console.warn(OBJECT|ARRAY|STRING|...);
console.assert(Condition, 'Message if false');

These Should work correctly On Google Chrome and Mozilla Firefox (if you are running with old version of firefox, so you have to install Firebug plugin)
On Internet Explorer 8 or higher you must do as follow:

  • Launch "Developer Tools, by clicking on F12 Button
  • On the Tab List, click on "Script" Tab"
  • Click on "Console" Button in the right side

For more informations you can visit this URL: https://developer.chrome.com/devtools/docs/console-api

Handling identity columns in an "Insert Into TABLE Values()" statement?

By default, if you have an identity column, you do not need to specify it in the VALUES section. If your table is:

ID    NAME    ADDRESS

Then you can do:

INSERT INTO MyTbl VALUES ('Joe', '123 State Street, Boston, MA')

This will auto-generate the ID for you, and you don't have to think about it at all. If you SET IDENTITY_INSERT MyTbl ON, you can assign a value to the ID column.

Singleton: How should it be used

In desktop apps (I know, only us dinosaurs write these anymore!) they are essential for getting relatively unchanging global application settings - the user language, path to help files, user preferences etc which would otherwise have to propogate into every class and every dialog.

Edit - of course these should be read-only !

Capturing count from an SQL query

You'll get converting errors with:

cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();

Use instead:

string stm = "SELECT COUNT(*) FROM table_name WHERE id="+id+";";
MySqlCommand cmd = new MySqlCommand(stm, conn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
if(count > 0){
    found = true; 
} else {
    found = false; 
}

List files with certain extensions with ls and grep

In case you are still looking for an alternate solution:

ls | grep -i -e '\\.tcl$' -e '\\.exe$' -e '\\.mp4$'

Feel free to add more -e flags if needed.

Is it valid to replace http:// with // in a <script src="http://...">?

Yes, this is documented in RFC 3986, section 5.2:

(edit: Oops, my RFC reference was outdated).

How to make a custom LinkedIn share button

Official LinkedIn API for sharing:

https://developer.linkedin.com/docs/share-on-linkedin

Read Terms of Use!

Example link using "Customized URL" method: http://www.linkedin.com/shareArticle?mini=true&url=https://stackoverflow.com/questions/10713542/how-to-make-custom-linkedin-share-button/10737122&title=How%20to%20make%20custom%20linkedin%20share%20button&summary=some%20summary%20if%20you%20want&source=stackoverflow.com

You just need to open it in popup using JavaScript or load it to iframe. Simple and works - that's what I was looking for!

EDIT: Video attached to a post:

I checked that you can't really embed any video to LinkedIn post, the only option is to add the link to the page with video itself.

You can achieve it by putting YT link into url param:

https://www.linkedin.com/shareArticle?mini=true&url=https://www.youtube.com/watch?v=SBi92AOSW2E

If you specify summary and title then LinkedIn will stop pulling it from the video, e.g.:

https://www.linkedin.com/shareArticle?mini=true&summary=youtube&title=f1&url=https://www.youtube.com/watch?v=SBi92AOSW2E

It does work exactly the same with Vimeo, and probably will work for any website. Hope it will help.

EDIT 2: Pulling images to the post:

When you open above links you will see that LinkedIn loads some images along with the passed URL (and optionally title and summary).

LinkedIn does it automatically, and you can read about it here: https://developer.linkedin.com/docs/share-on-linkedin#opengraph

It's interesting though as it says:

If Open Graph tags are present, LinkedIn's crawler will not have to rely on it's own analysis to determine what content will be shared, which improves the likelihood that the information that is shared is exactly what you intended.

It tells me that even if Open Graph information is not attached, LinkedIn can pull this data based on its own analysis. And in case of YouTube it seems to be the case, as I couldn't find any Open Graph tags added to YouTube pages.

Correctly ignore all files recursively under a specific folder except for a specific file type

Either I'm doing it wrongly, or the accepted answer does not work anymore with the current git.

I have actually found the proper solution and posted it under almost the same question here. For more details head there.

Solution:

# Ignore everything inside Resources/ directory
/Resources/**
# Except for subdirectories(won't be committed anyway if there is no committed file inside)
!/Resources/**/
# And except for *.foo files
!*.foo

Can I set up HTML/Email Templates with ASP.NET?

If flexibility is one of your prerequisites, XSLT might be a good choice, which is completely supported by .NET framework and you would be able to even let the user edit those files. This article (http://www.aspfree.com/c/a/XML/XSL-Transformations-using-ASP-NET/) might be useful for a start (msdn has more info about it). As said by ScarletGarden NVelocity is another good choice but I do prefer XSLT for its " built-in" .NET framework support and platform agnostic.

Display an image with Python

import IPython.display as display
from PIL import Image
image_path = 'my_image.jpg'
display.display(Image.open(image_path))

How do I exit a foreach loop in C#?

Look at this code, it can help you to get out of the loop fast!

foreach (var name in parent.names)
{
   if (name.lastname == null)
   {
      Violated = true;
      this.message = "lastname reqd";
      break;
   }
   else if (name.firstname == null)
   {
      Violated = true;
      this.message = "firstname reqd";
      break;
   }
}

SaveFileDialog setting default path and file type?

Here's an example that actually filters for BIN files. Also Windows now want you to save files to user locations, not system locations, so here's an example (you can use intellisense to browse the other options):

            var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
            {
                DefaultExt = "*.xml",
                Filter = "BIN Files (*.bin)|*.bin",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            };

            var result = saveFileDialog.ShowDialog();
            if (result != null && result == true)
            {
                // Save the file here
            }

Can I edit an iPad's host file?

You need access to /private/etc/ so, no. you cant.

jquery - Click event not working for dynamically created button

You could also create the input button in this way:

var button = '<input type="button" id="questionButton" value='+variable+'> <br />';


It might be the syntax of the Button creation that is off somehow.

Postgres: How to convert a json string to text?

In 9.4.4 using the #>> operator works for me:

select to_json('test'::text) #>> '{}';

To use with a table column:

select jsoncol #>> '{}' from mytable;

IIS Config Error - This configuration section cannot be used at this path

Heres what worked for me, had a similar problem on my new laptop which had windows 10.

  • Search for "Turn windows features on or off"
  • Check "Internet Information Services"
  • Check "World Wide Web Services"
  • Check "Application Development Features"
  • Enable all items under this

try again, now it should work.

Understanding generators in Python

I believe the first appearance of iterators and generators were in the Icon programming language, about 20 years ago.

You may enjoy the Icon overview, which lets you wrap your head around them without concentrating on the syntax (since Icon is a language you probably don't know, and Griswold was explaining the benefits of his language to people coming from other languages).

After reading just a few paragraphs there, the utility of generators and iterators might become more apparent.

How to create a trie in Python

Unwind is essentially correct that there are many different ways to implement a trie; and for a large, scalable trie, nested dictionaries might become cumbersome -- or at least space inefficient. But since you're just getting started, I think that's the easiest approach; you could code up a simple trie in just a few lines. First, a function to construct the trie:

>>> _end = '_end_'
>>> 
>>> def make_trie(*words):
...     root = dict()
...     for word in words:
...         current_dict = root
...         for letter in word:
...             current_dict = current_dict.setdefault(letter, {})
...         current_dict[_end] = _end
...     return root
... 
>>> make_trie('foo', 'bar', 'baz', 'barz')
{'b': {'a': {'r': {'_end_': '_end_', 'z': {'_end_': '_end_'}}, 
             'z': {'_end_': '_end_'}}}, 
 'f': {'o': {'o': {'_end_': '_end_'}}}}

If you're not familiar with setdefault, it simply looks up a key in the dictionary (here, letter or _end). If the key is present, it returns the associated value; if not, it assigns a default value to that key and returns the value ({} or _end). (It's like a version of get that also updates the dictionary.)

Next, a function to test whether the word is in the trie:

>>> def in_trie(trie, word):
...     current_dict = trie
...     for letter in word:
...         if letter not in current_dict:
...             return False
...         current_dict = current_dict[letter]
...     return _end in current_dict
... 
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'baz')
True
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'barz')
True
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'barzz')
False
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'bart')
False
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'ba')
False

I'll leave insertion and removal to you as an exercise.

Of course, Unwind's suggestion wouldn't be much harder. There might be a slight speed disadvantage in that finding the correct sub-node would require a linear search. But the search would be limited to the number of possible characters -- 27 if we include _end. Also, there's nothing to be gained by creating a massive list of nodes and accessing them by index as he suggests; you might as well just nest the lists.

Finally, I'll add that creating a directed acyclic word graph (DAWG) would be a bit more complex, because you have to detect situations in which your current word shares a suffix with another word in the structure. In fact, this can get rather complex, depending on how you want to structure the DAWG! You may have to learn some stuff about Levenshtein distance to get it right.

How to concatenate variables into SQL strings

You can accomplish this (if I understand what you are trying to do) using dynamic SQL.

The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.

So you can use something like this approach:

SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue 
    + ' AS fld1 FROM tbl' + @KeyValue

EXEC (@stmt)

First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:

'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'

At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE (or EXEC for short).

The old-school sp_executesql procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.


FOLLOWUP

EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.

Consider what would happen if @KeyValue contained the string:

'1 AS foo; DROP TABLE students; -- '

The string we would produce as a SQL statement would be:

'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'

When we EXECUTE that string as a SQL statement:

INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...

And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)

One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'. If an illegal character is found, then reject the value, and exit without executing any SQL.

How can I scroll a web page using selenium webdriver in python?

element=find_element_by_xpath("xpath of the li you are trying to access")

element.location_once_scrolled_into_view

this helped when I was trying to access a 'li' that was not visible.

How to display line numbers in 'less' (GNU)

You can also press = while less is open to just display (at the bottom of the screen) information about the current screen, including line numbers, with format:

myfile.txt lines 20530-20585/1816468 byte 1098945/116097872 1%  (press RETURN)

So here for example, the screen was currently showing lines 20530-20585, and the files has a total of 1816468 lines.

What is default session timeout in ASP.NET?

It depends on either the configuration or programmatic change.
Therefore the most reliable way to check the current value is at runtime via code.

See the HttpSessionState.Timeout property; default value is 20 minutes.

You can access this propery in ASP.NET via HttpContext:

this.HttpContext.Session.Timeout // ASP.NET MVC controller
Page.Session.Timeout // ASP.NET Web Forms code-behind
HttpContext.Current.Session.Timeout // Elsewhere

Reading Email using Pop3 in C#

You can also try Mail.dll mail component, it has SSL support, unicode, and multi-national email support:

using(Pop3 pop3 = new Pop3())
{
    pop3.Connect("mail.host.com");           // Connect to server and login
    pop3.Login("user", "password");

    foreach(string uid in pop3.GetAll())
    {
        IMail email = new MailBuilder()
            .CreateFromEml(pop3.GetMessageByUID(uid));
          Console.WriteLine( email.Subject );
    }
    pop3.Close(false);      
}

You can download it here at https://www.limilabs.com/mail

Please note that this is a commercial product I've created.

How to set timeout on python's socket recv method?

You can use socket.settimeout() which accepts a integer argument representing number of seconds. For example, socket.settimeout(1) will set the timeout to 1 second

How can I use random numbers in groovy?

If you want to generate random numbers in range including '0' , use the following while 'max' is the maximum number in the range.

Random rand = new Random()
random_num = rand.nextInt(max+1)

Vue equivalent of setTimeout?

Arrow Function

The best and simplest way to solve this problem is by using an arrow function () => {}:

    addToBasket() {
        var item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        // now 'this' is referencing the Vue object and not the 'setTimeout' scope
        setTimeout(() => this.basketAddSuccess = false, 2000);
    }

This works because the this of arrow functions is bound to the this of its enclosing scope- in Vue, that's the parent/ enclosing component. Inside a traditional function called by setTimeout, however, this refers to the window object (which is why you ran into errors when you tried to access this.basketAddSuccess in that context).

Argument Passing

Another way of doing this would be passing this as an arg to your function through setTimeout's prototype using its setTimeout(callback, delay, arg1, arg2, ...) form:

    addToBasket() {
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        //Add scope argument to func, pass this after delay in setTimeout
        setTimeout(function(scope) {
             scope.basketAddSuccess = false;
        }, 2000, this);
    }

(It's worth noting that the arg passing syntax is incompatible with IE 9 and below, however.)

Local Variable

Another possible, but less eloquent and less encouraged, way is to bind this to a var outside of setTimeout:

    addToBasket() {
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        //Declare self, which is accessible inside setTimeout func
        var self = this;
        setTimeout(function() {
             self.basketAddSuccess = false;
        }, 2000);
    }

Using an arrow function would eliminate the need for this extra variable entirely however, and really should be used unless something else is preventing its use.

Call jQuery Ajax Request Each X Minutes

You can use the built-in javascript setInterval.

var ajax_call = function() {
  //your jQuery ajax code
};

var interval = 1000 * 60 * X; // where X is your every X minutes

setInterval(ajax_call, interval);

or if you are the more terse type ...

setInterval(function() {
  //your jQuery ajax code
}, 1000 * 60 * X); // where X is your every X minutes

Send PHP variable to javascript function

You can pass PHP values to JavaScript. The PHP will execute server side so the value will be calculated and then you can echo it to the HTML containing the javascript. The javascript will then execute in the clients browser with the value PHP calculated server-side.

<script type="text/javascript">
    // Do something in JavaScript
    var x = <?php echo $calculatedValue; ?>;
    // etc..
</script>

How do you rename a Git tag?

If it's published, you can't delete it (without risking being tarred and feathered, that is). The 'Git way' is to do:

The sane thing. Just admit you screwed up, and use a different name. Others have already seen one tag-name, and if you keep the same name, you may be in the situation that two people both have "version X", but they actually have different "X"'s. So just call it "X.1" and be done with it.

Alternatively,

The insane thing. You really want to call the new version "X" too, even though others have already seen the old one. So just use git-tag -f again, as if you hadn't already published the old one.

It's so insane because:

Git does not (and it should not) change tags behind users back. So if somebody already got the old tag, doing a git-pull on your tree shouldn't just make them overwrite the old one.

If somebody got a release tag from you, you cannot just change the tag for them by updating your own one. This is a big security issue, in that people MUST be able to trust their tag-names. If you really want to do the insane thing, you need to just fess up to it, and tell people that you messed up.

All courtesy of the man pages.

CASE statement in SQLite query

Also, you do not have to use nested CASEs. You can use several WHEN-THEN lines and the ELSE line is also optional eventhough I recomend it

CASE 
   WHEN [condition.1] THEN [expression.1]
   WHEN [condition.2] THEN [expression.2]
   ...
   WHEN [condition.n] THEN [expression.n]
   ELSE [expression] 
END

Replace transparency in PNG images with white background

I needed either: both -alpha background and -flatten, or -fill.

I made a new PNG with a transparent background and a red dot in the middle.

convert image.png -background green -alpha off green.png failed: it produced an image with black background

convert image.png -background green -alpha background -flatten green.png produced an image with the correct green background.

Of course, with another file that I renamed image.png, it failed to do anything. For that file, I found that the color of the transparent pixels was "#d5d5d5" so I filled that color with green:

convert image.png -fill green -opaque "#d5d5d5" green.png replaced the transparent pixels with the correct green.

Error 500: Premature end of script headers

I bumped into this problem using PHP-FPM and Apache after increasing Apache's default LimitRequestFieldSize and LimitRequestLine values.

The only reason I did this (apache says don't mess) is because Yii2 has some pjax problems with POST requests. As a workaround, I decided to increase these limits and use gigantic GET headers.

php-fpm barfed up the 500 error though.

How to check if object has any properties in JavaScript?

for(var memberName in ad)
{
  //Member Name: memberName
  //Member Value: ad[memberName]
}

Member means Member property, member variable, whatever you want to call it >_>

The above code will return EVERYTHING, including toString... If you only want to see if the object's prototype has been extended:

var dummyObj = {};  
for(var memberName in ad)
{
  if(typeof(dummyObj[memberName]) == typeof(ad[memberName])) continue; //note A
  //Member Name: memberName
  //Member Value: ad[memberName]

}

Note A: We check to see if the dummy object's member has the same type as our testing object's member. If it is an extend, dummyobject's member type should be "undefined"

How do I request a file but not save it with Wget?

Use q flag for quiet mode, and tell wget to output to stdout with O- (uppercase o) and redirect to /dev/null to discard the output:

wget -qO- $url &> /dev/null

> redirects application output (to a file). if > is preceded by ampersand, shell redirects all outputs (error and normal) to the file right of >. If you don't specify ampersand, then only normal output is redirected.

./app &>  file # redirect error and standard output to file
./app >   file # redirect standard output to file
./app 2>  file # redirect error output to file

if file is /dev/null then all is discarded.

This works as well, and simpler:

wget -O/dev/null -q $url

Add and Remove Views in Android Dynamically?

ViewParents in general can't remove views, but ViewGroups can. You need to cast your parent to a ViewGroup (if it is a ViewGroup) to accomplish what you want.

For example:

View namebar = View.findViewById(R.id.namebar);
((ViewGroup) namebar.getParent()).removeView(namebar);

Note that all Layouts are ViewGroups.

Convert Text to Date?

For DD-MM-YYYY here is a simple workaround to manage string and dates:

insert the date into the string via DD-MMM-YYYY for example 01-11-2017 -> 01-Nov-2017

U can use the FORMAT(date, "dd-mmm-yyyy") to input dates into a string from the spread sheet.

Later, when you output it from a string, it will not confuse the days and months.

What's the use of session.flush() in Hibernate

Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database). By default, Hibernate will flush changes automatically for you:

  • before some query executions
  • when a transaction is committed

Allowing to explicitly flush the Session gives finer control that may be required in some circumstances (to get an ID assigned, to control the size of the Session,...).

Meaning of Open hashing and Closed hashing

The use of "closed" vs. "open" reflects whether or not we are locked in to using a certain position or data structure (this is an extremely vague description, but hopefully the rest helps).

For instance, the "open" in "open addressing" tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what's already in the hash table.

The "closed" in "closed hashing" refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table's internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why "closed hashing" and "open addressing" are synonyms.

Contrast this with open hashing - in this strategy, none of the objects are actually stored in the hash table's array; instead once an object is hashed, it is stored in a list which is separate from the hash table's internal array. "open" refers to the freedom we get by leaving the hash table, and using a separate list. By the way, "separate list" hints at why open hashing is also known as "separate chaining".

In short, "closed" always refers to some sort of strict guarantee, like when we guarantee that objects are always stored directly within the hash table (closed hashing). Then, the opposite of "closed" is "open", so if you don't have such guarantees, the strategy is considered "open".

Set scroll position

... Or just replace body by documentElement:

document.documentElement.scrollTop = 0;

disable viewport zooming iOS 10+ safari?

The workaround that works in Mobile Safari at this time of writing, is to have the the third argument in addEventListener be { passive: false }, so the full workaround looks like this:

document.addEventListener('touchmove', function (event) {
  if (event.scale !== 1) { event.preventDefault(); }
}, { passive: false });

You may want to check if options are supported to remain backwards compatible.

Can I open a dropdownlist using jQuery

One thing that this doesn't answer is what happens when you click on one of the options in the select list after you have done your size = n and made it absolute positioning.

Because the blur event makes it size = 1 and changes it back to how it looks, you should have something like this as well

$("option").click(function(){
    $(this).parent().blur();
});

Also, if you're having issues with the absolute positioned select list showing behind other elements, just put a

z-index: 100;

or something like that in the style of the select.

How to declare an array of strings in C++?

You can use the begin and end functions from the Boost range library to easily find the ends of a primitive array, and unlike the macro solution, this will give a compile error instead of broken behaviour if you accidentally apply it to a pointer.

const char* array[] = { "cat", "dog", "horse" };
vector<string> vec(begin(array), end(array));

Include PHP file into HTML file

You'll have to configure the server to interpret .html files as .php files. This configuration is different depending on the server software. This will also add an extra step to the server and will slow down response on all your pages and is probably not ideal.

Questions every good .NET developer should be able to answer?

I'd not ask those "know something from the textbook" questions, but rather ask some tinkering stuff like:

  • What does the foreach loop do in plain C#? (Expecting him to write a iterator loop.)
  • What's a singleton?
  • Let him/her parse a String to Datetime (expecting him/her to use TryParse instead of try/catch)
  • Implement the singleton, strategy and command patterns
  • Let him/her Refactor a piece of code for testing. Expecting him/her to abstract the external services away from the Unit under Test and implement his own Test-double of the service (providing no mocking framework)

These are not 100% sure, depending on the person I may ask them:

  • let him/her guard a method from null input (expecting him/her to use multiple returns to reduce nesting)
  • how does a object initializer work (Expecting him/her to write the thread-safe assignment)

Also I'd ask him how he/she learned his/her stuff and what he/she is reading (what blogs, books).

How to change the icon of an Android app in Eclipse?

You can find an easy guide here

The step are 2: - Copy the icon in the correct folder/folders - Change the AndroidManifest.xml

git status (nothing to commit, working directory clean), however with changes commited

Small hint which other people didn't talk about: git doesn't record changes if you add empty folders in your project folder. That's it, I was adding empty folders with random names to check wether it was recording changes, it wasn't. But it started to do it as soon as I began adding files in them. Cheers.

Java out.println() how is this possible?

you can see this also in sockets ...

PrintWriter out = new PrintWriter(socket.getOutputStream());

out.println("hello");

Open terminal here in Mac OS finder

I mostly use this function:

cf() {
  cd "$(osascript -e 'tell app "Finder" to POSIX path of (insertion location as alias)')"
}

You could also assign a shortcut to a script like the ones below.

Reuse an existing tab or create a new window (Terminal):

tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "Terminal"
    if (exists window 1) and not busy of window 1 then
        do script "cd " & quoted form of p in window 1
    else
        do script "cd " & quoted form of p
    end if
    activate
end tell

Reuse an existing tab or create a new tab (Terminal):

tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "Terminal"
    if not (exists window 1) then reopen
    activate
    if busy of window 1 then
        tell application "System Events" to keystroke "t" using command down
    end if
    do script "cd " & quoted form of p in window 1
end tell

Always create a new tab (iTerm 2):

tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "iTerm"
    if exists current terminal then
        current terminal
    else
        make new terminal
    end if
    tell (launch session "Default") of result to write text "cd " & quoted form of p
    activate
end tell

The first two scripts have two advantages compared to the services added in 10.7:

  • They use the folder on the title bar instead of requiring you to select a folder first.
  • They reuse the frontmost tab if it is not busy, e.g. running a command, displaying a man page, or running emacs.

T-SQL How to create tables dynamically in stored procedures?

First up, you seem to be mixing table variables and tables.

Either way, You can't pass in the table's name like that. You would have to use dynamic TSQL to do that.

If you just want to declare a table variable:

CREATE PROC sp_createATable 
  @name        VARCHAR(10), 
  @properties  VARCHAR(500) 
AS 
  declare @tablename TABLE
  ( 
    id  CHAR(10)  PRIMARY KEY 
  ); 

The fact that you want to create a stored procedure to dynamically create tables might suggest your design is wrong.

Cannot get a text value from a numeric cell “Poi”

    Cell cell = sheet.getRow(i).getCell(0);
    cell.setCellType ( Cell.CELL_TYPE_STRING );
    String j_username = cell.getStringCellValue();

UPDATE

Ok, as have been said in comments, despite this works it isn't correct method of retrieving data from an Excel's cell.

According to the manual here:

If what you want to do is get a String value for your numeric cell, stop!. This is not the way to do it. Instead, for fetching the string value of a numeric or boolean or date cell, use DataFormatter instead.

And according to the DataFormatter API

DataFormatter contains methods for formatting the value stored in an Cell. This can be useful for reports and GUI presentations when you need to display data exactly as it appears in Excel. Supported formats include currency, SSN, percentages, decimals, dates, phone numbers, zip codes, etc.

So, right way to show numeric cell's value is as following:

 DataFormatter formatter = new DataFormatter(); //creating formatter using the default locale
 Cell cell = sheet.getRow(i).getCell(0);
 String j_username = formatter.formatCellValue(cell); //Returns the formatted value of a cell as a String regardless of the cell type.

Switch firefox to use a different DNS than what is in the windows.host file

I wonder if you could write a custom rule for Fiddler to do what you want? IE uses no proxy, Firefox points to Fiddler, Fiddler uses custom rule to direct requests to the dev server...

http://www.fiddlertool.com/fiddler/

Convert comma separated string of ints to int array

If you don't want to have the current error handling behaviour, it's really easy:

return text.Split(',').Select(x => int.Parse(x));

Otherwise, I'd use an extra helper method (as seen this morning!):

public static int? TryParseInt32(string text)
{
    int value;
    return int.TryParse(text, out value) ? value : (int?) null;
}

and:

return text.Split(',').Select<string, int?>(TryParseInt32)
                      .Where(x => x.HasValue)
                      .Select(x => x.Value);

or if you don't want to use the method group conversion:

return text.Split(',').Select(t => t.TryParseInt32(t)
                      .Where(x => x.HasValue)
                      .Select(x => x.Value);

or in query expression form:

return from t in text.Split(',')
       select TryParseInt32(t) into x
       where x.HasValue
       select x.Value;

json_encode(): Invalid UTF-8 sequence in argument

I had a similar error which caused json_encode to return a null field whenever there was a hi-ascii character such as a curly apostrophe in a string, due to the wrong character set being returned in the query.

The solution was to make sure it comes as utf8 by adding:

mysql_set_charset('utf8');

after the mysql connect statement.

Why does the 260 character path length limit exist in Windows?

From Windows 10. you can remove the limitation by modifying a registry key.

Tip Starting in Windows 10, version 1607, MAX_PATH limitations have been removed from common Win32 file and directory functions. However, you must opt-in to the new behavior.

A registry key allows you to enable or disable the new long path behavior. To enable long path behavior set the registry key at HKLM\SYSTEM\CurrentControlSet\Control\FileSystem LongPathsEnabled (Type: REG_DWORD). The key's value will be cached by the system (per process) after the first call to an affected Win32 file or directory function (list follows). The registry key will not be reloaded during the lifetime of the process. In order for all apps on the system to recognize the value of the key, a reboot might be required because some processes may have started before the key was set. The registry key can also be controlled via Group Policy at Computer Configuration > Administrative Templates > System > Filesystem > Enable NTFS long paths. You can also enable the new long path behavior per app via the manifest:

<application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings xmlns:ws2="http://schemas.microsoft.com/SMI/2016/WindowsSettings">
        <ws2:longPathAware>true</ws2:longPathAware>
    </windowsSettings>
</application>

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

How to read an external properties file in Maven

This answer to a similar question describes how to extend the properties plugin so it can use a remote descriptor for the properties file. The descriptor is basically a jar artifact containing a properties file (the properties file is included under src/main/resources).

The descriptor is added as a dependency to the extended properties plugin so it is on the plugin's classpath. The plugin will search the classpath for the properties file, read the file''s contents into a Properties instance, and apply those properties to the project's configuration so they can be used elsewhere.

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

Crash page?

Enter image description here

(It happens when MySQL has to query large rows. By default, memory_limit is set to small, which was safer for the hardware.)

You can check your system existing memory status, before increasing php.ini:

# free -m
             total       used       free     shared    buffers     cached
Mem:         64457      63791        666          0       1118      18273
-/+ buffers/cache:      44398      20058
Swap:         1021          0       1021

Here I have increased it as in the following and then do service httpd restart to fix the crash page issue.

# grep memory_limit /etc/php.ini
memory_limit = 512M

How to update the value of a key in a dictionary in Python?

Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.

>>> books = {}
>>> books['book'] = 3       
>>> books['book'] -= 1   
>>> books   
{'book': 2}   

In your case:

book_shop[ch1] -= 1

Default keystore file does not exist?

go to ~/.android if there is no debug.keystore copy it from your project and paste it here then run command again.

Best way to parse RSS/Atom feeds with PHP

If feed isn't well-formed XML, you're supposed to reject it, no exceptions. You're entitled to call feed creator a bozo.

Otherwise you're paving way to mess that HTML ended up in.

How to edit CSS style of a div using C# in .NET

If all you want to do is conditionally show or hide a <div>, then you could declare it as an <asp:panel > (renders to html as a div tag) and set it's .Visible property.

How to get the difference (only additions) between two files in linux

diff and then grep for the edit type you want.

diff -u A1 A2 | grep -E "^\+"

How to not wrap contents of a div?

A combination of both float: left; white-space: nowrap; worked for me.

Each of them independently didn't accomplish the desired result.

Spring MVC Controller redirect using URL parameters instead of in response

This problem is caused (as others have stated) by model attributes being persisted into the query string - this is usually undesirable and is at risk of creating security holes as well as ridiculous query strings. My usual solution is to never use Strings for redirects in Spring MVC, instead use a RedirectView which can be configured not to expose model attributes (see: http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/view/RedirectView.html)

RedirectView(String url, boolean contextRelative, boolean http10Compatible, boolean exposeModelAttributes)

So I tend to have a util method which does a 'safe redirect' like:

public static RedirectView safeRedirect(String url) {
    RedirectView rv = new RedirectView(url);
    rv.setExposeModelAttributes(false);
    return rv;
}

The other option is to use bean configuration XML:

<bean id="myBean" class="org.springframework.web.servlet.view.RedirectView">
   <property name="exposeModelAttributes" value="false" />
   <property name="url" value="/myRedirect"/>
</bean>

Again, you could abstract this into its own class to avoid repetition (e.g. SafeRedirectView).


A note about 'clearing the model' - this is not the same as 'not exposing the model' in all circumstances. One site I worked on had a lot of filters which added things to the model, this meant that clearing the model before redirecting would not prevent a long query string. I would also suggest that 'not exposing model attributes' is a more semantic approach than 'clearing the model before redirecting'.

What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

Here are some (simple) benchmarks, of algorithms currently given on this page...

The algorithms have not been tested over all inputs of unsigned int; so check that first, before blindly using something ;)

On my machine clz (__builtin_clz) and asm work best. asm seems even faster then clz... but it might be due to the simple benchmark...

//////// go.c ///////////////////////////////
// compile with:  gcc go.c -o go -lm
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/***************** math ********************/

#define POS_OF_HIGHESTBITmath(a) /* 0th position is the Least-Signif-Bit */    \
  ((unsigned) log2(a))         /* thus: do not use if a <= 0 */  

#define NUM_OF_HIGHESTBITmath(a) ((a)               \
                  ? (1U << POS_OF_HIGHESTBITmath(a))    \
                  : 0)



/***************** clz ********************/

unsigned NUM_BITS_U = ((sizeof(unsigned) << 3) - 1);
#define POS_OF_HIGHESTBITclz(a) (NUM_BITS_U - __builtin_clz(a)) /* only works for a != 0 */

#define NUM_OF_HIGHESTBITclz(a) ((a)                    \
                 ? (1U << POS_OF_HIGHESTBITclz(a))  \
                 : 0)


/***************** i2f ********************/

double FF;
#define POS_OF_HIGHESTBITi2f(a) (FF = (double)(ui|1), ((*(1+(unsigned*)&FF))>>20)-1023)


#define NUM_OF_HIGHESTBITi2f(a) ((a)                    \
                 ? (1U << POS_OF_HIGHESTBITi2f(a))  \
                 : 0)




/***************** asm ********************/

unsigned OUT;
#define POS_OF_HIGHESTBITasm(a) (({asm("bsrl %1,%0" : "=r"(OUT) : "r"(a));}), OUT)

#define NUM_OF_HIGHESTBITasm(a) ((a)                    \
                 ? (1U << POS_OF_HIGHESTBITasm(a))  \
                 : 0)




/***************** bitshift1 ********************/

#define NUM_OF_HIGHESTBITbitshift1(a) (({   \
  OUT = a;                  \
  OUT |= (OUT >> 1);                \
  OUT |= (OUT >> 2);                \
  OUT |= (OUT >> 4);                \
  OUT |= (OUT >> 8);                \
  OUT |= (OUT >> 16);               \
      }), (OUT & ~(OUT >> 1)))          \



/***************** bitshift2 ********************/
int POS[32] = {0, 1, 28, 2, 29, 14, 24, 3,
             30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19,
             16, 7, 26, 12, 18, 6, 11, 5, 10, 9};

#define POS_OF_HIGHESTBITbitshift2(a) (({   \
  OUT = a;                  \
  OUT |= OUT >> 1;              \
  OUT |= OUT >> 2;              \
  OUT |= OUT >> 4;              \
  OUT |= OUT >> 8;              \
  OUT |= OUT >> 16;             \
  OUT = (OUT >> 1) + 1;             \
      }), POS[(OUT * 0x077CB531UL) >> 27])

#define NUM_OF_HIGHESTBITbitshift2(a) ((a)              \
                       ? (1U << POS_OF_HIGHESTBITbitshift2(a)) \
                       : 0)



#define LOOPS 100000000U

int main()
{
  time_t start, end;
  unsigned ui;
  unsigned n;

  /********* Checking the first few unsigned values (you'll need to check all if you want to use an algorithm here) **************/
  printf("math\n");
  for (ui = 0U; ui < 18; ++ui)
    printf("%i\t%i\n", ui, NUM_OF_HIGHESTBITmath(ui));

  printf("\n\n");

  printf("clz\n");
  for (ui = 0U; ui < 18U; ++ui)
    printf("%i\t%i\n", ui, NUM_OF_HIGHESTBITclz(ui));

  printf("\n\n");

  printf("i2f\n");
  for (ui = 0U; ui < 18U; ++ui)
    printf("%i\t%i\n", ui, NUM_OF_HIGHESTBITi2f(ui));

  printf("\n\n");

  printf("asm\n");
  for (ui = 0U; ui < 18U; ++ui) {
    printf("%i\t%i\n", ui, NUM_OF_HIGHESTBITasm(ui));
  }

  printf("\n\n");

  printf("bitshift1\n");
  for (ui = 0U; ui < 18U; ++ui) {
    printf("%i\t%i\n", ui, NUM_OF_HIGHESTBITbitshift1(ui));
  }

  printf("\n\n");

  printf("bitshift2\n");
  for (ui = 0U; ui < 18U; ++ui) {
    printf("%i\t%i\n", ui, NUM_OF_HIGHESTBITbitshift2(ui));
  }

  printf("\n\nPlease wait...\n\n");


  /************************* Simple clock() benchmark ******************/
  start = clock();
  for (ui = 0; ui < LOOPS; ++ui)
    n = NUM_OF_HIGHESTBITmath(ui);
  end = clock();
  printf("math:\t%e\n", (double)(end-start)/CLOCKS_PER_SEC);

  start = clock();
  for (ui = 0; ui < LOOPS; ++ui)
    n = NUM_OF_HIGHESTBITclz(ui);
  end = clock();
  printf("clz:\t%e\n", (double)(end-start)/CLOCKS_PER_SEC);

  start = clock();
  for (ui = 0; ui < LOOPS; ++ui)
    n = NUM_OF_HIGHESTBITi2f(ui);
  end = clock();
  printf("i2f:\t%e\n", (double)(end-start)/CLOCKS_PER_SEC);

  start = clock();
  for (ui = 0; ui < LOOPS; ++ui)
    n = NUM_OF_HIGHESTBITasm(ui);
  end = clock();
  printf("asm:\t%e\n", (double)(end-start)/CLOCKS_PER_SEC);

  start = clock();
  for (ui = 0; ui < LOOPS; ++ui)
    n = NUM_OF_HIGHESTBITbitshift1(ui);
  end = clock();
  printf("bitshift1:\t%e\n", (double)(end-start)/CLOCKS_PER_SEC);

  start = clock();
  for (ui = 0; ui < LOOPS; ++ui)
    n = NUM_OF_HIGHESTBITbitshift2(ui);
  end = clock();
  printf("bitshift2\t%e\n", (double)(end-start)/CLOCKS_PER_SEC);

  printf("\nThe lower, the better. Take note that a negative exponent is good! ;)\n");

  return EXIT_SUCCESS;
}

Removing numbers from string

Just a few (others have suggested some of these)

Method 1:

''.join(i for i in myStr if not i.isdigit())

Method 2:

def removeDigits(s):
    answer = []
    for char in s:
        if not char.isdigit():
            answer.append(char)
    return ''.join(char)

Method 3:

''.join(filter(lambda x: not x.isdigit(), mystr))

Method 4:

nums = set(map(int, range(10)))
''.join(i for i in mystr if i not in nums)

Method 5:

''.join(i for i in mystr if ord(i) not in range(48, 58))

How can I test a change made to Jenkinsfile locally?

Put your SSH key into your Jenkins profile, then use the declarative linter as follows:

ssh jenkins.hostname.here declarative-linter < Jenkinsfile

This will do a static analysis on your Jenkinsfile. In the editor of your choice, define a keyboard shortcut that runs that command automatically. In Visual Studio Code, which is what I use, go to Tasks > Configure Tasks, then use the following JSON to create a Validate Jenkinsfile command:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Validate Jenkinsfile",
      "type": "shell",
      "command": "ssh jenkins.hostname declarative-linter < ${file}"
    }
  ]
}

How to style a select tag's option element?

I have a workaround using jquery... although we cannot style a particular option, we can style the select itself - and use javascript to change the class of the select based on what is selected. It works sufficiently for simple cases.

_x000D_
_x000D_
$('select.potentially_red').on('change', function() {_x000D_
 if ($(this).val()=='red') {_x000D_
  $(this).addClass('option_red');_x000D_
 } else {_x000D_
  $(this).removeClass('option_red');_x000D_
 }_x000D_
});_x000D_
$('select.potentially_red').each( function() {_x000D_
 if ($(this).val()=='red') {_x000D_
  $(this).addClass('option_red');_x000D_
 } else {_x000D_
  $(this).removeClass('option_red');_x000D_
 }_x000D_
});
_x000D_
.option_red {_x000D_
    background-color: #cc0000; _x000D_
    font-weight: bold; _x000D_
    font-size: 12px; _x000D_
    color: white;_x000D_
}
_x000D_
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<!-- The js will affect all selects which have the class 'potentially_red' -->_x000D_
<select name="color" class="potentially_red">_x000D_
    <option value="red">Red</option>_x000D_
    <option value="white">White</option>_x000D_
    <option value="blue">Blue</option>_x000D_
    <option value="green">Green</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Note that the js is in two parts, the each part for initializing everything on the page correctly, the .on('change', ... part for responding to change. I was unable to mangle the js into a function to DRY it up, it breaks it for some reason

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

Convert generic list to dataset in C#

You could create an extension method to add all property values through reflection:

public static DataSet ToDataSet<T>(this IList<T> list)
{
    Type elementType = typeof(T);
    DataSet ds = new DataSet();
    DataTable t = new DataTable();
    ds.Tables.Add(t);

    //add a column to table for each public property on T
    foreach(var propInfo in elementType.GetProperties())
    {
        t.Columns.Add(propInfo.Name, propInfo.PropertyType);
    }

    //go through each property on T and add each value to the table
    foreach(T item in list)
    {
        DataRow row = t.NewRow();
        foreach(var propInfo in elementType.GetProperties())
        {
            row[propInfo.Name] = propInfo.GetValue(item, null);
        }
    }

    return ds;
}

How to open mail app from Swift

Updated answer from Stephen Groom for Swift 3

let email = "[email protected]"
let url = URL(string: "mailto:\(email)")
UIApplication.shared.openURL(url!)

Laravel Migration table already exists, but I want to add new not the older

In laravel 5.4, If you are having this issue. Check this link

-or-

Go to this page in app/Providers/AppServiceProvider.php and add code down below

use Illuminate\Support\Facades\Schema;

public function boot()
{
Schema::defaultStringLength(191);
}

Restoring database from .mdf and .ldf files of SQL Server 2008

this is what i did

first execute create database x. x is the name of your old database eg the name of the mdf.

Then open sql sever configration and stop the sql sever.

There after browse to the location of your new created database it should be under program file, in my case is

C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQL\MSSQL\DATA

and repleace the new created mdf and Idf with the old files/database.

then simply restart the sql server and walla :)

What is a mutex?

What is a Mutex?

The mutex (In fact, the term mutex is short for mutual exclusion) also known as spinlock is the simplest synchronization tool that is used to protect critical regions and thus prevent race conditions. That is a thread must acquire a lock before entering into a critical section (In critical section multi threads share a common variable, updating a table, writing a file and so on), it releases the lock when it leaves critical section.

What is a Race Condition?

A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.

Real life example:

When I am having a big heated discussion at work, I use a rubber chicken which I keep in my desk for just such occasions. The person holding the chicken is the only person who is allowed to talk. If you don't hold the chicken you cannot speak. You can only indicate that you want the chicken and wait until you get it before you speak. Once you have finished speaking, you can hand the chicken back to the moderator who will hand it to the next person to speak. This ensures that people do not speak over each other, and also have their own space to talk.

Replace Chicken with Mutex and person with thread and you basically have the concept of a mutex.

@Xetius

Usage in C#:

This example shows how a local Mutex object is used to synchronize access to a protected resource. Because each calling thread is blocked until it acquires ownership of the mutex, it must call the ReleaseMutex method to release ownership of the thread.

using System;
using System.Threading;

class Example
{
    // Create a new Mutex. The creating thread does not own the mutex.
    private static Mutex mut = new Mutex();
    private const int numIterations = 1;
    private const int numThreads = 3;

    static void Main()
    {
        // Create the threads that will use the protected resource.
        for(int i = 0; i < numThreads; i++)
        {
            Thread newThread = new Thread(new ThreadStart(ThreadProc));
            newThread.Name = String.Format("Thread{0}", i + 1);
            newThread.Start();
        }

        // The main thread exits, but the application continues to
        // run until all foreground threads have exited.
    }

    private static void ThreadProc()
    {
        for(int i = 0; i < numIterations; i++)
        {
            UseResource();
        }
    }

    // This method represents a resource that must be synchronized
    // so that only one thread at a time can enter.
    private static void UseResource()
    {
        // Wait until it is safe to enter.
        Console.WriteLine("{0} is requesting the mutex", 
                          Thread.CurrentThread.Name);
        mut.WaitOne();

        Console.WriteLine("{0} has entered the protected area", 
                          Thread.CurrentThread.Name);

        // Place code to access non-reentrant resources here.

        // Simulate some work.
        Thread.Sleep(500);

        Console.WriteLine("{0} is leaving the protected area", 
            Thread.CurrentThread.Name);

        // Release the Mutex.
        mut.ReleaseMutex();
        Console.WriteLine("{0} has released the mutex", 
            Thread.CurrentThread.Name);
    }
}
// The example displays output like the following:
//       Thread1 is requesting the mutex
//       Thread2 is requesting the mutex
//       Thread1 has entered the protected area
//       Thread3 is requesting the mutex
//       Thread1 is leaving the protected area
//       Thread1 has released the mutex
//       Thread3 has entered the protected area
//       Thread3 is leaving the protected area
//       Thread3 has released the mutex
//       Thread2 has entered the protected area
//       Thread2 is leaving the protected area
//       Thread2 has released the mutex

MSDN Reference Mutex

Node.js - How to send data from html to express

I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser which is doing most of the work. Where he puts req.body.name, I believe he/she is using body-parser to get the contents of the name attribute(s) received when the form is submitted.

If you do not want to use Express, use querystring which is a built-in Node module. See the answers in the link below for an example of how to use querystring.

It might help to look at this answer, which is very similar to your quest.

How to check if $? is not equal to zero in unix shell scripting?

You don't need to test if $? is not 0. The shell provides && and || so you can easily branch based on implicit result of that test:

some_command && {
    # executes this block of code,
    # if some_command would result in:  $? -eq 0
} || {
    # executes this block of code,
    # if some_command would result in:  $? -ne 0
}

You can remove either branch, depending on what you want. So if you just want to test for failure (i.e. $? -ne 0):

some_command_returning_nonzero || {
    # executes this block of code when:     $? -ne 0
    # and nothing if the command succeeds:  $? -eq 0
}

However, the code you provided in the question works, as is. I'm confused that you got syntax errors & concluded that $? was a string. It's most likely that the errant code causing the syntax error was not provided with the question. This is especially evident because you claim that no one else's solutions work either. When this happens, you have to re-evaluate your assumptions.

NB: The code above may give confusing results if the code inside the braces returns an error. In that case simply use the if command instead, like this:

if some_command; then
    # executes this block of code,
    # if some_command would result in:  $? -eq 0
else
    # executes this block of code,
    # if some_command would result in:  $? -ne 0
fi

What is the difference between Trap and Interrupt?

I think Traps are caused by the execution of current instruction and thus they are called as synchronous events. where as interrupts are caused by an independent instruction that is running in the processor which are related to external events and thus are known as asynchronous ones.

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

error: expected class-name before ‘{’ token

This should be a comment, but comments don't allow multi-line code.

Here's what's happening:

in Event.cpp

#include "Event.h"

preprocessor starts processing Event.h

#ifndef EVENT_H_

it isn't defined yet, so keep going

#define EVENT_H_
#include "common.h"

common.h gets processed ok

#include "Item.h"

Item.h gets processed ok

#include "Flight.h"

Flight.h gets processed ok

#include "Landing.h"

preprocessor starts processing Landing.h

#ifndef LANDING_H_

not defined yet, keep going

#define LANDING_H_

#include "Event.h"

preprocessor starts processing Event.h

#ifndef EVENT_H_

This IS defined already, the whole rest of the file gets skipped. Continuing with Landing.h

class Landing: public Event {

The preprocessor doesn't care about this, but the compiler goes "WTH is Event? I haven't heard about Event yet."

PHP: Read Specific Line From File

I searched for a one line solution to read specific line from a file. Here my solution:

echo file('dayInt.txt')[1]

How to get a list of column names on Sqlite3 database?

If you have the sqlite database, use the sqlite3 command line program and these commands:

To list all the tables in the database:

.tables

To show the schema for a given tablename:

.schema tablename

Background Image for Select (dropdown) does not work in Chrome

Generally, it's considered a bad practice to style standard form controls because the output looks so different on each browser. See: http://www.456bereastreet.com/lab/styling-form-controls-revisited/select-single/ for some rendered examples.

That being said, I've had some luck making the background color an RGBA value:

<!DOCTYPE html>
<html>
  <head>
    <style>
      body {
        background: #d00;
      }
      select {
        background: rgba(255,255,255,0.1) url('http://www.google.com/images/srpr/nav_logo6g.png') repeat-x 0 0; 
        padding:4px; 
        line-height: 21px;
        border: 1px solid #fff;
      }
    </style>
  </head>
  <body>
    <select>
      <option>Foo</option>
      <option>Bar</option>      
      <option>Something longer</option>     
  </body>
</html>

Google Chrome still renders a gradient on top of the background image in the color that you pass to rgba(r,g,b,0.1) but choosing a color that compliments your image and making the alpha 0.1 reduces the effect of this.

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

I had this error when trying to SSH into my Raspberry pi from my MBP via bash terminal. My RPI was connected to the network via wifi/wlan0 and this IP had been changed upon restart by my routers DHCP.

Check IP being used to login via SSH is correct. Re-check IP of device being SSH'd into (in my case the RPI), which can be checked using hostname -I

Confirm/amend SSH login credentials on "guest" device (in my case the MBP) and it worked fine in my attempt.

ggplot with 2 y axes on each side and different scales

You can use facet_wrap(~ variable, ncol= ) on a variable to create a new comparison. It's not on the same axis, but it is similar.

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

You have a few typos in your select. It should be: input:not([disabled]):not([type="submit"]):focus

See this jsFiddle for a proof of concept. On a sidenote, if I removed the "background-color" property, then the box shadow no longer works. Not sure why.

Get each line from textarea

$array = explode("\n", $text);
for($i=0; $i < count($array); $i++)
{
    echo $line;
    if($i < count($array)-1)
    {
         echo '<br />';
    }
}

Changing the highlight color when selecting text in an HTML text input

Try this code to use:

/* For Mozile Firefox Browser */

::-moz-selection { background-color: #4CAF50; }

/* For Other Browser*/
::selection { background-color: #4CAF50; }

PHP convert XML to JSON

Found FTav's answer the most useful as it is very customizable, but his xml2js function has some flaws. For instance, if children elements has equal tagnames they all will be stored in a single object, this means that the order of elements will not be preserved. In some cases we really want to preserve order, so we better store every element's data in a separate object:

function xml2js($xmlnode) {
    $jsnode = array();
    $nodename = $xmlnode->getName();
    $current_object = array();

    if (count($xmlnode->attributes()) > 0) {
        foreach($xmlnode->attributes() as $key => $value) {
            $current_object[$key] = (string)$value;
        }
    }

    $textcontent = trim((string)$xmlnode);
    if (strlen($textcontent) > 0) {
        $current_object["content"] = $textcontent;
    }

    if (count($xmlnode->children()) > 0) {
        $current_object['children'] = array();
        foreach ($xmlnode->children() as $childxmlnode) {
            $childname = $childxmlnode->getName();
            array_push($current_object['children'], xml2js($childxmlnode, true));
        }
    }

    $jsnode[ $nodename ] = $current_object;
    return $jsnode;
}

Here is how it works. Initial xml structure:

<some-tag some-attribute="value of some attribute">
  <another-tag>With text</another-tag>
  <surprise></surprise>
  <another-tag>The last one</another-tag>
</some-tag>

Result JSON:

{
    "some-tag": {
        "some-attribute": "value of some attribute",
        "children": [
            {
                "another-tag": {
                    "content": "With text"
                }
            },
            {
                "surprise": []
            },
            {
                "another-tag": {
                    "content": "The last one"
                }
            }
        ]
    }
}

How can I create a carriage return in my C# string

<br /> works for me

So...

String body = String.Format(@"New user: 
 <br /> Name: {0}
 <br /> Email: {1}
 <br /> Phone: {2}", Name, Email, Phone);

Produces...

New user:
Name: Name
Email: Email
Phone: Phone

mongo - couldn't connect to server 127.0.0.1:27017

Simply create a folder named "data" in C drive and inside data folder create another folder named "db". Then execute mongod.exe :)

Android: Access child views from a ListView

This assumes you know the position of the element in the ListView :

  View element = listView.getListAdapter().getView(position, null, null);

Then you should be able to call getLeft() and getTop() to determine the elements on screen position.

Calling Objective-C method from C++ member function?

Also, you can call into Objective-C runtime to call the method.

Get current batchfile directory

Here's what I use at the top of all my batch files. I just copy/paste from my template folder.

@echo off
:: --HAS ENDING BACKSLASH
set batdir=%~dp0
:: --MISSING ENDING BACKSLASH
:: set batdir=%CD%
pushd "%batdir%"

Setting current batch file's path to %batdir% allows you to call it in subsequent stmts in current batch file, regardless of where this batch file changes to. Using PUSHD allows you to use POPD to quickly set this batch file's path to original %batdir%. Remember, if using %batdir%ExtraDir or %batdir%\ExtraDir (depending on which version used above, ending backslash or not) you will need to enclose the entire string in double quotes if path has spaces (i.e. "%batdir%ExtraDir"). You can always use PUSHD %~dp0. [https: // ss64.com/ nt/ syntax-args .html] has more on (%~) parameters.

Note that using (::) at beginning of a line makes it a comment line. More importantly, using :: allows you to include redirectors, pipes, special chars (i.e. < > | etc) in that comment.

:: ORIG STMT WAS: dir *.* | find /v "1917" > outfile.txt

Of course, Powershell does this and lots more.

Error: free(): invalid next size (fast):

It means that you have a memory error. You may be trying to free a pointer that wasn't allocated by malloc (or delete an object that wasn't created by new) or you may be trying to free/delete such an object more than once. You may be overflowing a buffer or otherwise writing to memory to which you shouldn't be writing, causing heap corruption.

Any number of programming errors can cause this problem. You need to use a debugger, get a backtrace, and see what your program is doing when the error occurs. If that fails and you determine you have corrupted the heap at some previous point in time, you may be in for some painful debugging (it may not be too painful if the project is small enough that you can tackle it piece by piece).

How can I get the last day of the month in C#?

DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)

Error converting data types when importing from Excel to SQL Server 2008

When Excel finds mixed data types in same column it guesses what is the right format for the column (the majority of the values determines the type of the column) and dismisses all other values by inserting NULLs. But Excel does it far badly (e.g. if a column is considered text and Excel finds a number then decides that the number is a mistake and insert a NULL instead, or if some cells containing numbers are "text" formatted, one may get NULL values into an integer column of the database).

Solution:

  1. Create a new excel sheet with the name of the columns in the first row
  2. Format the columns as text
  3. Paste the rows without format (use CVS format or copy/paste in Notepad to get only text)

Note that formatting the columns on an existing Excel sheet is not enough.

How do I get logs/details of ansible-playbook module executions?

The playbook script task will generate stdout just like the non-playbook command, it just needs to be saved to a variable using register. Once we've got that, the debug module can print to the playbook output stream.

tasks:
- name: Hello yourself
  script: test.sh
  register: hello

- name: Debug hello
  debug: var=hello

- name: Debug hello.stdout as part of a string
  debug: "msg=The script's stdout was `{{ hello.stdout }}`."

Output should look something like this:

TASK: [Hello yourself] ******************************************************** 
changed: [MyTestHost]

TASK: [Debug hello] *********************************************************** 
ok: [MyTestHost] => {
    "hello": {
        "changed": true, 
        "invocation": {
            "module_args": "test.sh", 
            "module_name": "script"
        }, 
        "rc": 0, 
        "stderr": "", 
        "stdout": "Hello World\r\n", 
        "stdout_lines": [
            "Hello World"
        ]
    }
}

TASK: [Debug hello.stdout as part of a string] ******************************** 
ok: [MyTestHost] => {
    "msg": "The script's stdout was `Hello World\r\n`."
}

Monitor network activity in Android Phones

Note: tcpdump requires root privileges, so you'll have to root your phone if not done already. Here's an ARM binary of tcpdump (this works for my Samsung Captivate). If you prefer to build your own binary, instructions are here (yes, you'd likely need to cross compile).

Also, check out Shark For Root (an Android packet capture tool based on tcpdump).

I don't believe tcpdump can monitor traffic by specific process ID. The strace method that Chris Stratton refers to seems like more effort than its worth. It would be simpler to monitor specific IPs and ports used by the target process. If that info isn't known, capture all traffic during a period of process activity and then sift through the resulting pcap with Wireshark.

Reading from a text file and storing in a String

These are the necersary imports:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");

String readFile(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    } finally {
        br.close();
    }
}

Mean filter for smoothing images in Matlab

h = fspecial('average', n);
filter2(h, img);

See doc fspecial: h = fspecial('average', n) returns an averaging filter. n is a 1-by-2 vector specifying the number of rows and columns in h.

Docker: How to delete all local Docker images

You can try like this:

docker system prune

How to split long commands over multiple lines in PowerShell

If you have a function:

$function:foo | % Invoke @(
  'bar'
  'directory'
  $true
)

If you have a cmdlet:

[PSCustomObject] @{
  Path  = 'bar'
  Type  = 'directory'
  Force = $true
} | New-Item

If you have an application:

{foo.exe @Args} | % Invoke @(
  'bar'
  'directory'
  $true
)

Or

icm {foo.exe @Args} -Args @(
  'bar'
  'directory'
  $true
)

How to execute Table valued function

You can execute it just as you select a table using SELECT clause. In addition you can provide parameters within parentheses.

Try with below syntax:

SELECT * FROM yourFunctionName(parameter1, parameter2)

How to upgrade Git to latest version on macOS?

The installer from the git homepage installs into /usr/local/git by default. However, if you install XCode4, it will install a git version in /usr/bin. To ensure you can easily upgrade from the website and use the latest git version, edit either your profile information to place /usr/local/git/bin before /usr/bin in the $PATH or edit /etc/paths and insert /usr/local/git/bin as the first entry.

It may help to someone at-least changing the order in /etc/paths worked for me.

Remove border from IFrame

Try

<iframe src="url" style="border:none;"></iframe>

This will remove the border of your frame.

How can I detect whether an iframe is loaded?

You can try onload event as well;

var createIframe = function (src) {
        var self = this;
        $('<iframe>', {
            src: src,
            id: 'iframeId',
            frameborder: 1,
            scrolling: 'no',
            onload: function () {
                self.isIframeLoaded = true;
                console.log('loaded!');
            }
        }).appendTo('#iframeContainer');

    };

How do I output text without a newline in PowerShell?

desired o/p: Enabling feature XYZ......Done

you can use below command

$a = "Enabling feature XYZ"

Write-output "$a......Done"

you have to add variable and statement inside quotes. hope this is helpful :)

Thanks Techiegal

Simple way to calculate median with MySQL

Another riff on Velcrow's answer, but uses a single intermediate table and takes advantage of the variable used for row numbering to get the count, rather than performing an extra query to calculate it. Also starts the count so that the first row is row 0 to allow simply using Floor and Ceil to select the median row(s).

SELECT Avg(tmp.val) as median_val
    FROM (SELECT inTab.val, @rows := @rows + 1 as rowNum
              FROM data as inTab,  (SELECT @rows := -1) as init
              -- Replace with better where clause or delete
              WHERE 2 > 1
              ORDER BY inTab.val) as tmp
    WHERE tmp.rowNum in (Floor(@rows / 2), Ceil(@rows / 2));

android ellipsize multiline textview

There are a few attributes you should check: android:lines, android:minLines, android:maxLines. To display a maximum of 4 lines and ellipsize it, you just need android:maxLines and android:ellipsize:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:maxLines="4"
    android:ellipsize="marquee"
    android:text="Hai!"
    />

Open a URL without using a browser from a batch file

You can try put in a shortcut to the site and tell the .bat file to open that.

start Google.HTML
exit

How do I PHP-unserialize a jQuery-serialized form?

You shouldn't have to unserialize anything in PHP from the jquery serialize method. If you serialize the data, it should be sent to PHP as query parameters if you are using a GET method ajax request or post vars if you are using a POST ajax request. So in PHP, you would access values like $_POST["varname"] or $_GET["varname"] depending on the request type.

The serialize method just takes the form elements and puts them in string form. "varname=val&var2=val2"

How to get table list in database, using MS SQL 2008?

Answering the question in your title, you can query sys.tables or sys.objects where type = 'U' to check for the existence of a table. You can also use OBJECT_ID('table_name', 'U'). If it returns a non-null value then the table exists:

IF (OBJECT_ID('dbo.My_Table', 'U') IS NULL)
BEGIN
    CREATE TABLE dbo.My_Table (...)
END

You can do the same for databases with DB_ID():

IF (DB_ID('My_Database') IS NULL)
BEGIN
    CREATE DATABASE My_Database
END

If you want to create the database and then start using it, that needs to be done in separate batches. I don't know the specifics of your case, but there shouldn't be many cases where this isn't possible. In a SQL script you can use GO statements. In an application it's easy enough to send across a new command after the database is created.

The only place that you might have an issue is if you were trying to do this in a stored procedure and creating databases on the fly like that is usually a bad idea.

If you really need to do this in one batch, you can get around the issue by using EXEC to get around the parsing error of the database not existing:

CREATE DATABASE Test_DB2

IF (OBJECT_ID('Test_DB2.dbo.My_Table', 'U') IS NULL)
BEGIN
    EXEC('CREATE TABLE Test_DB2.dbo.My_Table (my_id INT)')
END

EDIT: As others have suggested, the INFORMATION_SCHEMA.TABLES system view is probably preferable since it is supposedly a standard going forward and possibly between RDBMSs.

"Could not find or load main class" Error while running java program using cmd prompt

faced the same problem. solved by following these steps

  • go to directory containing the package 'org.tij.exercises' (e.g: in eclipse it may be your src folder)
  • use java org.tij.exercises.HelloWorld

passing several arguments to FUN of lapply (and others *apply)

If you look up the help page, one of the arguments to lapply is the mysterious .... When we look at the Arguments section of the help page, we find the following line:

...: optional arguments to ‘FUN’.

So all you have to do is include your other argument in the lapply call as an argument, like so:

lapply(input, myfun, arg1=6)

and lapply, recognizing that arg1 is not an argument it knows what to do with, will automatically pass it on to myfun. All the other apply functions can do the same thing.

An addendum: You can use ... when you're writing your own functions, too. For example, say you write a function that calls plot at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use ... (as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to plot.

How can I pad an int with leading zeros when using cout << operator?

I would use the following function. I don't like sprintf; it doesn't do what I want!!

#define hexchar(x)    ((((x)&0x0F)>9)?((x)+'A'-10):((x)+'0'))
typedef signed long long   Int64;

// Special printf for numbers only
// See formatting information below.
//
//    Print the number "n" in the given "base"
//    using exactly "numDigits".
//    Print +/- if signed flag "isSigned" is TRUE.
//    Use the character specified in "padchar" to pad extra characters.
//
//    Examples:
//    sprintfNum(pszBuffer, 6, 10, 6,  TRUE, ' ',   1234);  -->  " +1234"
//    sprintfNum(pszBuffer, 6, 10, 6, FALSE, '0',   1234);  -->  "001234"
//    sprintfNum(pszBuffer, 6, 16, 6, FALSE, '.', 0x5AA5);  -->  "..5AA5"
void sprintfNum(char *pszBuffer, int size, char base, char numDigits, char isSigned, char padchar, Int64 n)
{
    char *ptr = pszBuffer;

    if (!pszBuffer)
    {
        return;
    }

    char *p, buf[32];
    unsigned long long x;
    unsigned char count;

    // Prepare negative number
    if (isSigned && (n < 0))
    {
        x = -n;
    }
    else
    {
        x = n;
    }

    // Set up small string buffer
    count = (numDigits-1) - (isSigned?1:0);
    p = buf + sizeof (buf);
    *--p = '\0';

    // Force calculation of first digit
    // (to prevent zero from not printing at all!!!)
    *--p = (char)hexchar(x%base);
    x = x / base;

    // Calculate remaining digits
    while(count--)
    {
        if(x != 0)
        {
            // Calculate next digit
            *--p = (char)hexchar(x%base);
            x /= base;
        }
        else
        {
            // No more digits left, pad out to desired length
            *--p = padchar;
        }
    }

    // Apply signed notation if requested
    if (isSigned)
    {
        if (n < 0)
        {
            *--p = '-';
        }
        else if (n > 0)
        {
            *--p = '+';
        }
        else
        {
            *--p = ' ';
        }
    }

    // Print the string right-justified
    count = numDigits;
    while (count--)
    {
        *ptr++ = *p++;
    }
    return;
}

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

Had issues using most of the mentioned methods since textfield had not accepted keyboard input, and the mouse solution seem not complete.

This worked for to simulate a click in the field, selecting the content and replacing it with new.

     Actions actionList = new Actions(driver);
     actionList.clickAndHold(WebElement).sendKeys(newTextFieldString).
     release().build().perform();

What is the volatile keyword useful for?

Volatile Variables are light-weight synchronization. When visibility of latest data among all threads is requirement and atomicity can be compromised , in such situations Volatile Variables must be preferred. Read on volatile variables always return most recent write done by any thread since they are neither cached in registers nor in caches where other processors can not see. Volatile is Lock-Free. I use volatile, when scenario meets criteria as mentioned above.

Ansible - read inventory hosts and variables to group_vars/all file

If you want to have your vars in files under group_vars, just move them here. Vars can be in the inventory ([group:vars] section) but also (and foremost) in files under group_vars or hosts_vars.

For instance, with your example above, you can move your vars for group tests in the file group_vars/tests :

Inventory file :

[lb]
10.112.84.122

[tomcat]
10.112.84.124

[jboss5]
10.112.84.122

...

[tests:children]
lb
tomcat
jboss5

[default:children]
tests

group_vars/tests file :

data_base_user=NETWIN-4.3
data_base_password=NETWIN
data_base_encrypted_password=
data_base_host=10.112.69.48
data_base_port=1521
data_base_service=ssdenwdb
data_base_url=jdbc:oracle:thin:@10.112.69.48:1521/ssdenwdb

What is the default username and password in Tomcat?

My answer is tested on Windows 7 with installation of NetBeans IDE 6.9.1 which has bundled Tomcat version 6.0.26. The instruction may work with other tomcat versions according to my opinion.

If you are starting the Apache Tomcat server from the Servers panel in NetBeans IDE then you shall know that the Catalina base and config files used by NetBeans IDE to start the Tomcat server are kept at a different location.

Steps to know the catalina base directory for your installation:

  1. Right click on the Apache Tomcat node in Servers panel and choose properties option in the context menu. This will open a dialog box named Servers.
  2. Check the directory name of the field Catalina Base, this is that directory where the current conf/tomcat-users.xml is located and which you want to open and read.
    (In my case it is C:\Users\Tushar Joshi\.netbeans\6.9\apache-tomcat-6.0.26_base )
  3. Open this directory in My Computer and go to the conf directory where you will find the actual tomcat-users.xml file used by NetBeans IDE. NetBeans IDE comes configured with one default password with username="ide" and some random password, you may change this username and password if you want or use it for your login also
  4. This dialog box also have username and password field which are populated with these default username and password and NetBeans IDE also offers you to open the manager application by right clicking on the manager node under the Apache Tomcat node in Servers panel
  5. The only problem with the NetBeans IDE is it tries to open the URL http://localhost:8084/manager/ which shall be http://localhost:8084/manager/html now

View tabular file such as CSV from command line

I wrote this csv_view.sh to format CSVs from the command line, this reads the entire file to figure out the optimal width of each column (requires perl, assumes there are no commas in fields, also uses less):


#!/bin/bash

perl -we '
  sub max( @ ) {
    my $max = shift;

    map { $max = $_ if $_ > $max } @_;
    return $max;
  }

  sub transpose( @ ) {
    my @matrix = @_;
    my $width  = scalar @{ $matrix[ 0 ] };
    my $height = scalar @matrix;

    return map { my $x = $_; [ map { $matrix[ $_ ][ $x ] } 0 .. $height - 1 ] } 0 .. $width - 1;
  }

  # Read all lines, as arrays of fields
  my @lines = map { s/\r?\n$//; [ split /,/ ] } ;

  my $widths =
    # Build a pack expression based on column lengths
    join "",

    # For each column get the longest length plus 1
    map { 'A' . ( 1 + max map { length } @$_ ) }

    # Get arrays of columns
    transpose

    @lines
  ;

  # Format all lines with pack
  map { print pack( $widths, @$_ ) . "\n" } @lines;
' $1 | less -NS

Pass a javascript variable value into input type hidden value

//prompts for input in javascript
test=prompt("Enter a value?","some string");

//passes javascript to a hidden field.
document.getElementById('myField').value = test;

//prompts for input in javascript
test2=prompt("Enter a value?","some string2");

//passes javascript to a hidden field
document.getElementById('myField').value = test2;

//prints output
document.write("hello, "+test+test2;

now this is confusing but this should work...

Heroku "psql: FATAL: remaining connection slots are reserved for non-replication superuser connections"

See Heroku “psql: FATAL: remaining connection slots are reserved for non-replication superuser connections”:

Heroku sometimes has a problem with database load balancing.

André Laszlo, markshiz and me all reported dealing with that in comments on the question.

To save you the support call, here's the response I got from Heroku Support for a similar issue:

Hello,

One of the limitations of the hobby tier databases is unannounced maintenance. Many hobby databases run on a single shared server, and we will occasionally need to restart that server for hardware maintenance purposes, or migrate databases to another server for load balancing. When that happens, you'll see an error in your logs or have problems connecting. If the server is restarting, it might take 15 minutes or more for the database to come back online.

Most apps that maintain a connection pool (like ActiveRecord in Rails) can just open a new connection to the database. However, in some cases an app won't be able to reconnect. If that happens, you can heroku restart your app to bring it back online.

This is one of the reasons we recommend against running hobby databases for critical production applications. Standard and Premium databases include notifications for downtime events, and are much more performant and stable in general. You can use pg:copy to migrate to a standard or premium plan.

If this continues, you can try provisioning a new database (on a different server) with heroku addons:add, then use pg:copy to move the data. Keep in mind that hobby tier rules apply to the $9 basic plan as well as the free database.

Thanks, Bradley

sed: print only matching group

And for yet another option, I'd go with awk!

echo "foo bar <foo> bla 1 2 3.4" | awk '{ print $(NF-1), $NF; }'

This will split the input (I'm using STDIN here, but your input could easily be a file) on spaces, and then print out the last-but-one field, and then the last field. The $NF variables hold the number of fields found after exploding on spaces.

The benefit of this is that it doesn't matter if what precedes the last two fields changes, as long as you only ever want the last two it'll continue to work.

Using SUMIFS with multiple AND OR conditions

Speed

SUMPRODUCT is faster than SUM arrays, i.e. having {} arrays in the SUM function. SUMIFS is 30% faster than SUMPRODUCT.

{SUM(SUMIFS({}))} vs SUMPRODUCT(SUMIFS({})) both works fine, but SUMPRODUCT feels a bit easier to write without the CTRL-SHIFT-ENTER to create the {}.

Preference

I personally prefer writing SUMPRODUCT(--(ISNUMBER(MATCH(...)))) over SUMPRODUCT(SUMIFS({})) for multiple criteria.

However, if you have a drop-down menu where you want to select specific characteristics or all, SUMPRODUCT(SUMIFS()), is the only way to go. (as for selecting "all", the value should enter in "<>" + "Whatever word you want as long as it's not part of the specific characteristics".

Create File If File Does Not Exist

You don't even need to do the check manually, File.Open does it for you. Try:

using (StreamWriter sw = new StreamWriter(File.Open(path, System.IO.FileMode.Append))) 
{

Ref: http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx

Check orientation on Android phone

such this is overlay all phones such as oneplus3

public static boolean isScreenOriatationPortrait(Context context) {
    return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
}

right code as follows:

public static int getRotation(Context context) {
    final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();

    if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
        return Configuration.ORIENTATION_PORTRAIT;
    }

    if (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) {
        return Configuration.ORIENTATION_LANDSCAPE;
    }

    return -1;
}

jQuery delete confirmation box

Simply works as:

$("a. close").live("click",function(event){
     return confirm("Do you want to delete?");
});

Partition Function COUNT() OVER possible using DISTINCT

I use a solution that is similar to that of David above, but with an additional twist if some rows should be excluded from the count. This assumes that [UserAccountKey] is never null.

-- subtract an extra 1 if null was ranked within the partition,
-- which only happens if there were rows where [Include] <> 'Y'
dense_rank() over (
  partition by [Mth] 
  order by case when [Include] = 'Y' then [UserAccountKey] else null end asc
) 
+ dense_rank() over (
  partition by [Mth] 
  order by case when [Include] = 'Y' then [UserAccountKey] else null end desc
)
- max(case when [Include] = 'Y' then 0 else 1 end) over (partition by [Mth])
- 1

An SQL Fiddle with an extended example can be found here.

NSUserDefaults - How to tell if a key exists

Swift version to get Bool?

NSUserDefaults.standardUserDefaults().objectForKey(DefaultsIsGiver) as? Bool

Is calling destructor manually always a sign of bad design?

What about this?
Destructor is not called if an exception is thrown from the constructor, so I have to call it manually to destroy handles that have been created in the constructor before the exception.

class MyClass {
  HANDLE h1,h2;
  public:
  MyClass() {
    // handles have to be created first
    h1=SomeAPIToCreateA();
    h2=SomeAPIToCreateB();        
    try {
      ...
      if(error) {
        throw MyException();
      }
    }
    catch(...) {
      this->~MyClass();
      throw;
    }
  }
  ~MyClass() {
    SomeAPIToDestroyA(h1);
    SomeAPIToDestroyB(h2);
  }
};

How to create an Observable from static data similar to http one in Angular?

This way you can create Observable from data, in my case I need to maintain shopping cart:

service.ts

export class OrderService {
    cartItems: BehaviorSubject<Array<any>> = new BehaviorSubject([]);
    cartItems$ = this.cartItems.asObservable();

    // I need to maintain cart, so add items in cart

    addCartData(data) {
        const currentValue = this.cartItems.value; // get current items in cart
        const updatedValue = [...currentValue, data]; // push new item in cart

        if(updatedValue.length) {
          this.cartItems.next(updatedValue); // notify to all subscribers
        }
      }
}

Component.ts

export class CartViewComponent implements OnInit {
    cartProductList: any = [];
    constructor(
        private order: OrderService
    ) { }

    ngOnInit() {
        this.order.cartItems$.subscribe(items => {
            this.cartProductList = items;
        });
    }
}

How to add an extra language input to Android?

I just found Scandinavian Keyboard as a fine solution to this problem. It do also have English and German keyboard, but neither Dutch nor Spanish - but I guess they could be added. And I guess there is other alternatives out there.

How to convert a string to lower or upper case in Ruby

In combination with try method, to support nil value:

'string'.try(:upcase)
'string'.try(:capitalize)
'string'.try(:titleize)

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

I have come to point out the answer nobody seems to see here. You can fullfill all requests you have made with pure CSS and it's very simple. Just use Media Queries. Media queries can check the orientation of the user's screen, or viewport. Then you can style your images depending on the orientation.

Just set your default CSS on your images like so:

img {
   width:auto;
   height:auto;
   max-width:100%;
   max-height:100%;
}

Then use some media queries to check your orientation and that's it!

@media (orientation: landscape) { img { height:100%; } }
@media (orientation: portrait) { img { width:100%; } }

You will always get an image that scales to fit the screen, never loses aspect ratio, never scales larger than the screen, never clips or overflows.

To learn more about these media queries, you can read MDN's specs.

Centering

To center your image horizontally and vertically, just use the flex box model. Use a parent div set to 100% width and height, like so:

div.parent {
   display:flex;
   position:fixed;
   left:0px;
   top:0px;
   width:100%;
   height:100%;
   justify-content:center;
   align-items:center;
}

With the parent div's display set to flex, the element is now ready to use the flex box model. The justify-content property sets the horizontal alignment of the flex items. The align-items property sets the vertical alignment of the flex items.

Conclusion

I too had wanted these exact requirements and had scoured the web for a pure CSS solution. Since none of the answers here fulfilled all of your requirements, either with workarounds or settling upon sacrificing a requirement or two, this solution really is the most straightforward for your goals; as it fulfills all of your requirements with pure CSS.

EDIT: The accepted answer will only appear to work if your images are large. Try using small images and you will see that they can never be larger than their original size.

What is the difference between .py and .pyc files?

Python compiles the .py and saves files as .pyc so it can reference them in subsequent invocations.

There's no harm in deleting them, but they will save compilation time if you're doing lots of processing.

Simulating Key Press C#

You can use the Win32 API FindWindow or FindWindowEx to find the window handle of the open browser and then just call SendMessage with WM_KEYDOWN. Typically it's easiest just to pass the window caption to FindWindowEx and have it find the associated window handle for you.

If you are starting the browser process yourself via a Process process object then you can use process.MainWindowHandle instead of calling FindWindowEx.

Spy++ is a very useful tool when you want to start working with other windows. It basically allows you to learn another program's hierarchy of UI elements. You can also monitor all of the messages that go into the window you're monitoring. I have more info in this thread.

The F5 keystroke has this virtual key code:

const int VK_F5 = 0x74;

The p/invoke signature for FindWindowEx in C# is:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

You can p/invoke (bring in) the Win32 API SendMessage like this:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

So to recap, you call FindWindowEx directly from your C# code after having the above code somewhere inside your class. FindWindowEx will return a window handle. Then once you have the window handle, you can send any keystroke(s) to the window, or call many other Win32 API calls on the window handle. Or even find a child window by using another call to FindWindowEx. For example you could select the edit control of the browser even and then change it's text.

If all else goes wrong and you think you're sending the right key to the window, you can use spy++ to see what messages are sent to the window when you manually set focus to the browser and manually press F5.

Drawing an SVG file on a HTML5 canvas

Mozilla has a simple way for drawing SVG on canvas called "Drawing DOM objects into a canvas"

Catch Ctrl-C in C

Set up a trap (you can trap several signals with one handler):

signal (SIGQUIT, my_handler);
signal (SIGINT, my_handler);

Handle the signal however you want, but be aware of limitations and gotchas:

void my_handler (int sig)
{
  /* Your code here. */
}

How can I delete all Git branches which have been merged?

Let's say I have a remote named upstream and an origin (GitHub style, my fork is origin, upstream is upstream).

I don't want to delete ANY masters, HEAD, or anything from the upstream. I also don't want to delete the develop branch as that is our common branch we create PRs from.

List all remote branches, filtered by ones that were merged:

git branch -r

Remove lines from that list that contain words I know are in branch names I don't want to remove:

sed '/develop\|master\|HEAD\|upstream/d'

Remove the remote name from the reference name (origin/somebranch becomes somebranch):

sed 's/.*\///'

Use xargs to call a one-liner:

xargs git push --delete origin

Pipe it all together you get:

git branch -r --merged | sed '/develop\|master\|HEAD\|upstream/d' |  sed 's/.*\///' | xargs git push --delete origin

This will leave me with only some branches that I have worked on, but have not merged. You can then remove them one by one as there shouldn't be too many.

Find branches you no longer want:

git branch -ar

Say you find branch1, branch2, and branch3 you want to delete:

git push --delete origin branch1 branch2 branch3

Parse String to Date with Different Format in Java

Check the javadocs for java.text.SimpleDateFormat It describes everything you need.

How to Reload ReCaptcha using JavaScript?

For AngularJS users:

$window.grecaptcha.reset();

How do I set path while saving a cookie value in JavaScript?

This will help....

function setCookie(name,value,days) {
   var expires = "";
   if (days) {
       var date = new Date();
       date.setTime(date.getTime() + (days*24*60*60*1000));
       expires = "; expires=" + date.toUTCString();
   }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

 function getCookie(name) {
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');
   for(var i=0;i < ca.length;i++) {
       var c = ca[i];
       while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return 
        c.substring(nameEQ.length,c.length);
  }
return null;
}

Hex colors: Numeric representation for "transparent"?

You can use this conversion table: http://roselab.jhu.edu/~raj/MISC/hexdectxt.html

eg, if you want a transparency of 60%, you use 3C (hex equivalent).

This is usefull for IE background gradient transparency:

filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#3C545454, endColorstr=#3C545454);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#3C545454, endColorstr=#3C545454)";

where startColorstr and endColorstr: 2 first characters are a hex value for transparency, and the six remaining are the hex color.

Changing button text onclick

This worked fine for me. I had multiple buttons which I wanted to toggle the input value text from 'Add Range' to 'Remove Range'

<input type="button" onclick="if(this.value=='Add Range') { this.value='Remove Range'; } else { this.value='Add Range'; }" />

How can I check if char* variable points to empty string?

if (!*ptr) { /* empty string  */}

similarly

if (*ptr)  { /* not empty */ }

Exporting result of select statement to CSV format in DB2

This is how you can do it from DB2 client.

  1. Open the Command Editor and Run the select Query in the Commands Tab.

  2. Open the corresponding Query Results Tab

  3. Then from Menu --> Selected --> Export

How can I check if a Perl array contains a particular value?

Even though it's convenient to use, it seems like the convert-to-hash solution costs quite a lot of performance, which was an issue for me.

#!/usr/bin/perl
use Benchmark;
my @list;
for (1..10_000) {
    push @list, $_;
}

timethese(10000, {
  'grep'    => sub {
            if ( grep(/^5000$/o, @list) ) {
                # code
            }
        },
  'hash'    => sub {
            my %params = map { $_ => 1 } @list;
            if ( exists($params{5000}) ) {
                # code
            }
        },
});

Output of benchmark test:

Benchmark: timing 10000 iterations of grep, hash...
          grep:  8 wallclock secs ( 7.95 usr +  0.00 sys =  7.95 CPU) @ 1257.86/s (n=10000)
          hash: 50 wallclock secs (49.68 usr +  0.01 sys = 49.69 CPU) @ 201.25/s (n=10000)

How to disable an input type=text?

If you know this when the page is rendered, which it sounds like you do because the database has a value, it's better to disable it when rendered instead of JavaScript. To do that, just add the readonly attribute (or disabled, if you want to remove it from the form submission as well) to the <input>, like this:

<input type="text" disabled="disabled" />
//or...
<input type="text" readonly="readonly" />

Using Image control in WPF to display System.Drawing.Bitmap

I wrote a program with wpf and used Database for showing images and this is my code:

SqlConnection con = new SqlConnection(@"Data Source=HITMAN-PC\MYSQL;
                                      Initial Catalog=Payam;
                                      Integrated Security=True");

SqlDataAdapter da = new SqlDataAdapter("select * from news", con);

DataTable dt = new DataTable();
da.Fill(dt);

string adress = dt.Rows[i]["ImgLink"].ToString();
ImageSource imgsr = new BitmapImage(new Uri(adress));
PnlImg.Source = imgsr;

Changing the cursor in WPF sometimes works, sometimes doesn't

You can use a data trigger (with a view model) on the button to enable a wait cursor.

<Button x:Name="NextButton"
        Content="Go"
        Command="{Binding GoCommand }">
    <Button.Style>
         <Style TargetType="{x:Type Button}">
             <Setter Property="Cursor" Value="Arrow"/>
             <Style.Triggers>
                 <DataTrigger Binding="{Binding Path=IsWorking}" Value="True">
                     <Setter Property="Cursor" Value="Wait"/>
                 </DataTrigger>
             </Style.Triggers>
         </Style>
    </Button.Style>
</Button>

Here is the code from the view-model:

public class MainViewModel : ViewModelBase
{
   // most code removed for this example

   public MainViewModel()
   {
      GoCommand = new DelegateCommand<object>(OnGoCommand, CanGoCommand);
   }

   // flag used by data binding trigger
   private bool _isWorking = false;
   public bool IsWorking
   {
      get { return _isWorking; }
      set
      {
         _isWorking = value;
         OnPropertyChanged("IsWorking");
      }
   }

   // button click event gets processed here
   public ICommand GoCommand { get; private set; }
   private void OnGoCommand(object obj)
   {
      if ( _selectedCustomer != null )
      {
         // wait cursor ON
         IsWorking = true;
         _ds = OrdersManager.LoadToDataSet(_selectedCustomer.ID);
         OnPropertyChanged("GridData");

         // wait cursor off
         IsWorking = false;
      }
   }
}

Get all messages from Whatsapp

Whatsapp store all messages in an encrypted database (pyCrypt) which is very easy to decipher using Python.

You can fetch this database easily on Android, iPhone, Blackberry and dump it into html file. Here are complete instructions: Read, Extract WhatsApp Messages backup on Android, iPhone, Blackberry

Disclaimer: I researched and wrote this extensive guide.

Sql Query to list all views in an SQL Server 2005 database

This is old, but I thought I'd put this out anyway since I couldn't find a query that would give me ALL the SQL code from EVERY view I had out there. So here it is:

  SELECT SM.definition
  FROM sys.sql_modules SM
  INNER JOIN sys.Objects SO ON SM.Object_id = SO.Object_id
  WHERE SO.type = 'v'

how to change any data type into a string in python

You can use %s like below

>>> "%s" %([])
'[]'

JavaScript: Create and destroy class instance through class method

You can only manually delete properties of objects. Thus:

var container = {};

container.instance = new class();

delete container.instance;

However, this won't work on any other pointers. Therefore:

var container = {};

container.instance = new class();

var pointer = container.instance;

delete pointer; // false ( ie attempt to delete failed )

Furthermore:

delete container.instance; // true ( ie attempt to delete succeeded, but... )

pointer; // class { destroy: function(){} }

So in practice, deletion is only useful for removing object properties themselves, and is not a reliable method for removing the code they point to from memory.

A manually specified destroy method could unbind any event listeners. Something like:

function class(){
  this.properties = { /**/ }

  function handler(){ /**/ }

  something.addEventListener( 'event', handler, false );

  this.destroy = function(){
    something.removeEventListener( 'event', handler );
  }
}

How to normalize a NumPy array to within a certain range?

You are trying to min-max scale the values of audio between -1 and +1 and image between 0 and 255.

Using sklearn.preprocessing.minmax_scale, should easily solve your problem.

e.g.:

audio_scaled = minmax_scale(audio, feature_range=(-1,1))

and

shape = image.shape
image_scaled = minmax_scale(image.ravel(), feature_range=(0,255)).reshape(shape)

note: Not to be confused with the operation that scales the norm (length) of a vector to a certain value (usually 1), which is also commonly referred to as normalization.

How to convert an ArrayList containing Integers to primitive int array?

A very simple one-line solution is:

Integer[] i = arrlist.stream().toArray(Integer[]::new);

How to check if a table exists in MS Access for vb macros

Access has some sort of system tables You can read about it a little here you can fire the folowing query to see if it exists ( 1 = it exists, 0 = it doesnt ;))

SELECT Count([MSysObjects].[Name]) AS [Count]
FROM MSysObjects
WHERE (((MSysObjects.Name)="TblObject") AND ((MSysObjects.Type)=1));

Eclipse java debugging: source not found

In my case problem was resolved by clicking Remove All Breakpoints

How to create a foreign key in phpmyadmin

When you create table than you can give like follows.

CREATE TABLE categories(
cat_id int not null auto_increment primary key,
cat_name varchar(255) not null,
cat_description text
) ENGINE=InnoDB;


CREATE TABLE products(
   prd_id int not null auto_increment primary key,
   prd_name varchar(355) not null,
   prd_price decimal,
   cat_id int not null,
   FOREIGN KEY fk_cat(cat_id)
   REFERENCES categories(cat_id)
   ON UPDATE CASCADE
   ON DELETE RESTRICT
)ENGINE=InnoDB;

and when after the table create like this

   ALTER table_name
    ADD CONSTRAINT constraint_name
    FOREIGN KEY foreign_key_name(columns)
    REFERENCES parent_table(columns)
    ON DELETE action
    ON UPDATE action;

Following on example for it.

CREATE TABLE vendors(
    vdr_id int not null auto_increment primary key,
    vdr_name varchar(255)
)ENGINE=InnoDB;

ALTER TABLE products 
ADD COLUMN vdr_id int not null AFTER cat_id;

To add a foreign key to the products table, you use the following statement:

ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;

For drop the key

ALTER TABLE table_name 
DROP FOREIGN KEY constraint_name;

Hope this help to learn FOREIGN keys works

C Macro definition to determine big endian or little endian machine?

If you dump the preprocessor #defines

gcc -dM -E - < /dev/null
g++ -dM -E -x c++ - < /dev/null

You can usually find stuff that will help you. With compile time logic.

#define __LITTLE_ENDIAN__ 1
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__

Various compilers may have different defines however.

If else embedding inside html

You will find multiple different methods that people use and they each have there own place.

<?php if($first_condition): ?>
  /*$first_condition is true*/
<?php elseif ($second_condition): ?>
  /*$first_condition is false and $second_condition is true*/
<?php else: ?>
  /*$first_condition and $second_condition are false*/
<?php endif; ?>

If in your php.ini attribute short_open_tag = true (this is normally found on line 141 of the default php.ini file) you can replace your php open tag from <?php to <?. This is not advised as most live server environments have this turned off (including many CMS's like Drupal, WordPress and Joomla). I have already tested short hand open tags in Drupal and confirmed that it will break your site, so stick with <?php. short_open_tag is not on by default in all server configurations and must not be assumed as such when developing for unknown server configurations. Many hosting companies have short_open_tag turned off.

A quick search of short_open_tag in stackExchange shows 830 results. https://stackoverflow.com/search?q=short_open_tag That's a lot of people having problems with something they should just not play with.

with some server environments and applications, short hand php open tags will still crash your code even with short_open_tag set to true.

short_open_tag will be removed in PHP6 so don't use short hand tags.

all future PHP versions will be dropping short_open_tag

"It's been recommended for several years that you not use the short tag "short cut" and instead to use the full tag combination. With the wide spread use of XML and use of these tags by other languages, the server can become easily confused and end up parsing the wrong code in the wrong context. But because this short cut has been a feature for such a long time, it's currently still supported for backwards compatibility, but we recommend you don't use them." – Jelmer Sep 25 '12 at 9:00 php: "short_open_tag = On" not working

and

Normally you write PHP like so: . However if allow_short_tags directive is enabled you're able to use: . Also sort tags provides extra syntax: which is equal to .

Short tags might seem cool but they're not. They causes only more problems. Oh... and IIRC they'll be removed from PHP6. Crozin answered Aug 24 '10 at 22:12 php short_open_tag problem

and

To answer the why part, I'd quote Zend PHP 5 certification guide: "Short tags were, for a time, the standard in the PHP world; however, they do have the major drawback of conflicting with XML headers and, therefore, have somewhat fallen by the wayside." – Fluffy Apr 13 '11 at 14:40 Are PHP short tags acceptable to use?

You may also see people use the following example:

<?php if($first_condition){ ?>
  /*$first_condition is true*/
<?php }else if ($second_condition){ ?>
  /*$first_condition is false and $second_condition is true*/
<?php }else{ ?>
  /*$first_condition and $second_condition are false*/
<?php } ?>

This will work but it is highly frowned upon as it's not considered as legible and is not what you would use this format for. If you had a PHP file where you had a block of PHP code that didn't have embedded tags inside, then you would use the bracket format.

The following example shows when to use the bracket method

<?php
if($first_condition){
   /*$first_condition is true*/
}else if ($second_condition){
   /*$first_condition is false and $second_condition is true*/
}else{
   /*$first_condition and $second_condition are false*/
}
?>

If you're doing this code for yourself you can do what you like, but if your working with a team at a job it is advised to use the correct format for the correct circumstance. If you use brackets in embedded html/php scripts that is a good way to get fired, as no one will want to clean up your code after you. IT bosses will care about code legibility and college professors grade on legibility.

UPDATE

based on comments from duskwuff its still unclear if shorthand is discouraged (by the php standards) or not. I'll update this answer as I get more information. But based on many documents found on the web about shorthand being bad for portability. I would still personally not use it as it gives no advantage and you must rely on a setting being on that is not on for every web host.

How to read an entire file to a string using C#?

A benchmark comparison of File.ReadAllLines vs StreamReader ReadLine from C# file handling

File Read Comparison

Results. StreamReader is much faster for large files with 10,000+ lines, but the difference for smaller files is negligible. As always, plan for varying sizes of files, and use File.ReadAllLines only when performance isn't critical.


StreamReader approach

As the File.ReadAllText approach has been suggested by others, you can also try the quicker (I have not tested quantitatively the performance impact, but it appears to be faster than File.ReadAllText (see comparison below)). The difference in performance will be visible only in case of larger files though.

string readContents;
using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
{
     readContents = streamReader.ReadToEnd();
}


Comparison of File.Readxxx() vs StreamReader.Readxxx()

Viewing the indicative code through ILSpy I have found the following about File.ReadAllLines, File.ReadAllText.

  • File.ReadAllText - Uses StreamReader.ReadToEnd internally
  • File.ReadAllLines - Also uses StreamReader.ReadLine internally with the additionally overhead of creating the List<string> to return as the read lines and looping till the end of file.


So both the methods are an additional layer of convenience built on top of StreamReader. This is evident by the indicative body of the method.

File.ReadAllText() implementation as decompiled by ILSpy

public static string ReadAllText(string path)
{
    if (path == null)
    {
        throw new ArgumentNullException("path");
    }
    if (path.Length == 0)
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
    }
    return File.InternalReadAllText(path, Encoding.UTF8);
}   

private static string InternalReadAllText(string path, Encoding encoding)
{
    string result;
    using (StreamReader streamReader = new StreamReader(path, encoding))
    {
        result = streamReader.ReadToEnd();
    }
    return result;
}

OpenCV !_src.empty() in function 'cvtColor' error

must please see guys that the error is in the cv2.imread() .Give the right path of the image. and firstly, see if your system loads the image or not. this can be checked first by simple load of image using cv2.imread(). after that ,see this code for the face detection

import numpy as np
import cv2

cascPath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site-   packages/cv2/data/haarcascade_frontalface_default.xml"

eyePath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site-packages/cv2/data/haarcascade_eye.xml"

smilePath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site-packages/cv2/data/haarcascade_smile.xml"

face_cascade = cv2.CascadeClassifier(cascPath)
eye_cascade = cv2.CascadeClassifier(eyePath)
smile_cascade = cv2.CascadeClassifier(smilePath)

img = cv2.imread('WhatsApp Image 2020-04-04 at 8.43.18 PM.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
    img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex,ey,ew,eh) in eyes:
        cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here, cascPath ,eyePath ,smilePath should have the right actual path that's picked up from lib/python3.7/site-packages/cv2/data here this path should be to picked up the haarcascade files

Load RSA public key from file

Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/

   import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.security.KeyFactory;
    import java.security.NoSuchAlgorithmException;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;

    public class Demo {

        public static final String PRIVATE_KEY="/home/user/private.der";
        public static final String PUBLIC_KEY="/home/user/public.der";

        public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
            //get the private key
            File file = new File(PRIVATE_KEY);
            FileInputStream fis = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(fis);

            byte[] keyBytes = new byte[(int) file.length()];
            dis.readFully(keyBytes);
            dis.close();

            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
            System.out.println("Exponent :" + privKey.getPrivateExponent());
            System.out.println("Modulus" + privKey.getModulus());

            //get the public key
            File file1 = new File(PUBLIC_KEY);
            FileInputStream fis1 = new FileInputStream(file1);
            DataInputStream dis1 = new DataInputStream(fis1);
            byte[] keyBytes1 = new byte[(int) file1.length()];
            dis1.readFully(keyBytes1);
            dis1.close();

            X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
            KeyFactory kf1 = KeyFactory.getInstance("RSA");
            RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);

            System.out.println("Exponent :" + pubKey.getPublicExponent());
            System.out.println("Modulus" + pubKey.getModulus());
        }
    }

How do I show the changes which have been staged?

From version 1.7 and later it should be:

git diff --staged

How can I pad an integer with zeros on the left?

You can use Google Guava:

Maven:

<dependency>
     <artifactId>guava</artifactId>
     <groupId>com.google.guava</groupId>
     <version>14.0.1</version>
</dependency>

Sample code:

String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"

Note:

Guava is very useful library, it also provides lots of features which related to Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc

Ref: GuavaExplained

Export tables to an excel spreadsheet in same directory

You can use VBA to export an Access database table as a Worksheet in an Excel Workbook.

To obtain the path of the Access database, use the CurrentProject.Path property.

To name the Excel Workbook file with the current date, use the Format(Date, "yyyyMMdd") method.

Finally, to export the table as a Worksheet, use the DoCmd.TransferSpreadsheet method.

Example:

Dim outputFileName As String
outputFileName = CurrentProject.Path & "\Export_" & Format(Date, "yyyyMMdd") & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table1", outputFileName , True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table2", outputFileName , True

This will output both Table1 and Table2 into the same Workbook.

HTH

Is a DIV inside a TD a bad idea?

It breaks semantics, that's all. It works fine, but there may be screen readers or something down the road that won't enjoy processing your HTML if you "break semantics".

Add inline style using Javascript

If you don't want to add each css property line by line, you can do something like this:

_x000D_
_x000D_
document.body.insertAdjacentHTML('afterbegin','<div id="div"></div>');_x000D_
_x000D_
/**_x000D_
 * Add styles to DOM element_x000D_
 * @element DOM element_x000D_
 * @styles object with css styles_x000D_
 */_x000D_
function addStyles(element,styles){_x000D_
  for(id in styles){_x000D_
    element.style[id] = styles[id];_x000D_
  }_x000D_
}_x000D_
_x000D_
// usage_x000D_
var nFilter = document.getElementById('div');_x000D_
var styles = {_x000D_
  color: "red"_x000D_
  ,width: "100px"_x000D_
  ,height: "100px"_x000D_
  ,display: "block"_x000D_
  ,border: "1px solid blue"_x000D_
}_x000D_
addStyles(nFilter,styles);
_x000D_
_x000D_
_x000D_

How to make a view with rounded corners?

The tutorial link you provided seems to suggest that you need to set the layout_width and layout_height properties, of your child elements to match_parent.

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

How to add values in a variable in Unix shell scripting?

var=$((count7 + count1))

Arithmetic in bash uses $((...)) syntax.

You do not need to $ symbol within the $(( ))

MySQL - SELECT * INTO OUTFILE LOCAL ?

The path you give to LOAD DATA INFILE is for the filesystem on the machine where the server is running, not the machine you connect from. LOAD DATA LOCAL INFILE is for the client's machine, but it requires that the server was started with the right settings, otherwise it's not allowed. You can read all about it here: http://dev.mysql.com/doc/refman/5.0/en/load-data-local.html

As for SELECT INTO OUTFILE I'm not sure why there is not a local version, besides it probably being tricky to do over the connection. You can get the same functionality through the mysqldump tool, but not through sending SQL to the server.

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

In addition to what was already said - in order to avoid this error from interfering (stopping) other Javascript code on your page, you could try forcing the YouTube iframe to load last - after all other Javascript code is loaded.

Images can't contain alpha channels or transparencies

What worked for me here was using a jpg file instead of PNG as jpg files don't use alpha or transparency features. I did it via online image converter or you can also open the image in preview and then File->Export and uncheck alpha as option to save the image and use this image.

Hide div after a few seconds

jquery offers a variety of methods to hide the div in a timed manner that do not require setting up and later clearing or resetting interval timers or other event handlers. Here are a few examples.

Pure hide, one second delay

// hide in one second
$('#mydiv').delay(1000).hide(0); 

Pure hide, no delay

// hide immediately
$('#mydiv').delay(0).hide(0); 

Animated hide

// start hide in one second, take 1/2 second for animated hide effect
$('#mydiv').delay(1000).hide(500); 

fade out

// start fade out in one second, take 300ms to fade
$('#mydiv').delay(1000).fadeOut(300); 

Additionally, the methods can take a queue name or function as a second parameter (depending on method). Documentation for all the calls above and other related calls can be found here: https://api.jquery.com/category/effects/

Python script to do something at the same time every day

I needed something similar for a task. This is the code I wrote: It calculates the next day and changes the time to whatever is required and finds seconds between currentTime and next scheduled time.

import datetime as dt

def my_job():
    print "hello world"
nextDay = dt.datetime.now() + dt.timedelta(days=1)
dateString = nextDay.strftime('%d-%m-%Y') + " 01-00-00"
newDate = nextDay.strptime(dateString,'%d-%m-%Y %H-%M-%S')
delay = (newDate - dt.datetime.now()).total_seconds()
Timer(delay,my_job,()).start()

pandas how to check dtype for all columns in a dataframe?

The singular form dtype is used to check the data type for a single column. And the plural form dtypes is for data frame which returns data types for all columns. Essentially:

For a single column:

dataframe.column.dtype

For all columns:

dataframe.dtypes

Example:

import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [True, False, False], 'C': ['a', 'b', 'c']})

df.A.dtype
# dtype('int64')
df.B.dtype
# dtype('bool')
df.C.dtype
# dtype('O')

df.dtypes
#A     int64
#B      bool
#C    object
#dtype: object

Converting char* to float or double

You are missing an include : #include <stdlib.h>, so GCC creates an implicit declaration of atof and atod, leading to garbage values.

And the format specifier for double is %f, not %d (that is for integers).

#include <stdlib.h>
#include <stdio.h>

int main()
{
  char *test = "12.11";
  double temp = strtod(test,NULL);
  float ftemp = atof(test);
  printf("price: %f, %f",temp,ftemp);
  return 0;
}
/* Output */
price: 12.110000, 12.110000

Xcode source automatic formatting

Well I was searching for an easy way. And find out on medium.

First to copy the json text and validate it on jsonlint or something similar. Then to copy from jsonlint, already the json is formatted. And paste the code on Xcode with preserving the format, shortcut shift + option + command + v

How do I find the current machine's full hostname in C (hostname and domain information)?

gethostname() is POSIX way to get local host name. Check out man.

BSD function getdomainname() can give you domain name so you can build fully qualified hostname. There is no POSIX way to get a domain I'm afraid.

How do you get assembler output from C/C++ source in gcc?

Use the -S option to gcc (or g++).

gcc -S helloworld.c

This will run the preprocessor (cpp) over helloworld.c, perform the initial compilation and then stop before the assembler is run.

By default this will output a file helloworld.s. The output file can be still be set by using the -o option.

gcc -S -o my_asm_output.s helloworld.c

Of course this only works if you have the original source. An alternative if you only have the resultant object file is to use objdump, by setting the --disassemble option (or -d for the abbreviated form).

objdump -S --disassemble helloworld > helloworld.dump

This option works best if debugging option is enabled for the object file (-g at compilation time) and the file hasn't been stripped.

Running file helloworld will give you some indication as to the level of detail that you will get by using objdump.

Current Subversion revision command

svn info, I believe, is what you want.

If you just wanted the revision, maybe you could do something like:

svn info | grep "Revision:"

Switching users inside Docker image to a non-root user

In case you need to perform privileged tasks like changing permissions of folders you can perform those tasks as a root user and then create a non-privileged user and switch to it:

From <some-base-image:tag>

# Switch to root user
USER root # <--- Usually you won't be needed it - Depends on base image

# Run privileged command
RUN apt install <packages>
RUN apt <privileged command>

# Set user and group
ARG user=appuser
ARG group=appuser
ARG uid=1000
ARG gid=1000
RUN groupadd -g ${gid} ${group}
RUN useradd -u ${uid} -g ${group} -s /bin/sh -m ${user} # <--- the '-m' create a user home directory

# Switch to user
USER ${uid}:${gid}

# Run non-privileged command
RUN apt <non-privileged command>

Using "like" wildcard in prepared statement

PreparedStatement ps = cn.prepareStatement("Select * from Users where User_FirstName LIKE ?");
ps.setString(1, name + '%');

Try this out.

How to clone ArrayList and also clone its contents?

Here is a solution using a generic template type:

public static <T> List<T> copyList(List<T> source) {
    List<T> dest = new ArrayList<T>();
    for (T item : source) { dest.add(item); }
    return dest;
}

Django Forms: if not valid, show form with error message

You can put simply a flag variable, in this case is_successed.

def preorder_view(request, pk, template_name='preorders/preorder_form.html'):
    is_successed=0
    formset = PreorderHasProductsForm(request.POST)
    client= get_object_or_404(Client, pk=pk)
    if request.method=='POST':
        #populate the form with data from the request
       # formset = PreorderHasProductsForm(request.POST)
        if formset.is_valid():
            is_successed=1
            preorder_date=formset.cleaned_data['preorder_date']
            product=formset.cleaned_data['preorder_has_products']
            return render(request, template_name, {'preorder_date':preorder_date,'product':product,'is_successed':is_successed,'formset':formset})



    return render(request, template_name, {'object':client,'formset':formset})

afterwards in your template you can just put the code below

{%if is_successed == 1 %}
<h1>{{preorder_date}}</h1>
<h2> {{product}}</h2>
{%endif %}

Read all contacts' phone numbers in android

You can get all phone contacts using this:

    Cursor c = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            new String[] { ContactsContract.Contacts._ID,
                    ContactsContract.Contacts.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER,
                    ContactsContract.RawContacts.ACCOUNT_TYPE },
            ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'google' ",
            null, null);

check complete example HERE...........

warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

If you're running OSX and getting this often, another good thing to consider is to use a built-in OSX permissions fixing tool. If you didn't change the mode of your directories, something else did and there's a chance that other directories have overgenerous permissions as well - this tool will reset them back all to factory defaults, which is a good security idea. There's a great guide on the Apple stackextange about this very process.

Authenticating in PHP using LDAP through Active Directory

For those looking for a complete example check out http://www.exchangecore.com/blog/how-use-ldap-active-directory-authentication-php/.

I have tested this connecting to both Windows Server 2003 and Windows Server 2008 R2 domain controllers from a Windows Server 2003 Web Server (IIS6) and from a windows server 2012 enterprise running IIS 8.