Programs & Examples On #Getpasswd

How to add a where clause in a MySQL Insert statement?

INSERT INTO users (id,username, password) 
VALUES ('1','Jack','123')
ON DUPLICATE KEY UPDATE username='Jack',password='123'

This will work only if the id field is unique/pk (not composite PK though) Also, this will insert if no id of value 1 is found and update otherwise the record with id 1 if it does exists.

Selecting distinct values from a JSON

This is a great spot for a reduce

var uniqueArray = o.DATA.reduce(function (a, d) {
       if (a.indexOf(d.name) === -1) {
         a.push(d.name);
       }
       return a;
    }, []);

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

If you have this error running "php artisan migrate". You can alter the table you want to update by writing this :

    DB::statement('ALTER TABLE table_name ROW_FORMAT = DYNAMIC;');        

In your migration script. Example :

class MyMigration extends Migration {

/**
 * Run the migrations.
 */
public function up()
{
    DB::statement('ALTER TABLE table_name ROW_FORMAT = DYNAMIC;');        
    Schema::table('table_name', function ($table) {
        //....
    });
}

/**
 * Undo the migrations.
 */
public function down()
{
    //....
}
}

And then run php artisan migrate again

base_url() function not working in codeigniter

Anything if you use directly in the Codeigniter framework directly, like base_url(), uri_string(), or word_limiter(), All of these are coming from some sort of Helper function of framework.

While some of Helpers may be available globally to use just like log_message() which are extremely useful everywhere, rest of the Helpers are optional and use case varies application to application. base_url() is a function defined in url helper of the Framework.

You can learn more about helper in Codeigniter user guide's helper section.

You can use base_url() function once your current class have access to it, for which you needs to load it first.

$this->load->helper('url')

You can use this line anywhere in the application before using the base_url() function.

If you need to use it frequently, I will suggest adding this function in config/autoload.php in the autoload helpers section.

Also, make sure you have well defined base_url value in your config/config.php file.

This will be the first configuration you will see,

$config['base_url'] = 'http://yourdomain.com/'; 

You can check quickly by

echo base_url();

Reference: https://codeigniter.com/user_guide/helpers/url_helper.html

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

The menu location seems to have changed to:

Query Designer --> Pane --> SQL

How do I create a multiline Python string with inline variables?

f-strings, also called “formatted string literals,” are string literals that have an f at the beginning; and curly braces containing expressions that will be replaced with their values.

f-strings are evaluated at runtime.

So your code can be re-written as:

string1="go"
string2="now"
string3="great"
print(f"""
I will {string1} there
I will go {string2}
{string3}
""")

And this will evaluate to:

I will go there
I will go now
great

You can learn more about it here.

Align a div to center

This has always worked for me.

Provided you set a fixed width for your DIV, and the proper DOCTYPE, try this

div {        
  margin-left:auto;
  margin-right:auto;
}

Hope this helps.

MySQL: How to set the Primary Key on phpMyAdmin?

MySQL can index the first x characters of a column,but a TEXT type is of variable length so mysql cant assure the uniqueness of the column.If you still want text column,use VARCHAR.

Concatenating Files And Insert New Line In Between Files

If it were me doing it I'd use sed:

sed -e '$s/$/\n/' -s *.txt > finalfile.txt

In this sed pattern $ has two meanings, firstly it matches the last line number only (as a range of lines to apply a pattern on) and secondly it matches the end of the line in the substitution pattern.

If your version of sed doesn't have -s (process input files separately) you can do it all as a loop though:

for f in *.txt ; do sed -e '$s/$/\n/' $f ; done > finalfile.txt

Update MySQL using HTML Form and PHP

Try it this way. Put the table name in quotes (``). beside put variable '".$xyz."'.

So your sql query will be like:

$sql = mysql_query("UPDATE `anstalld` SET mandag = "'.$mandag.'" WHERE namn =".$name)or die(mysql_error());

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

Assuming you are using Eclipse, on a MAC you can:

  1. Launch Eclipse.app
  2. Choose Eclipse -> Preferences
  3. Choose Java -> Installed JREs
  4. Click the Add... button
  5. Choose MacOS X VM as the JRE type. Press Next.
  6. In the "JRE Home:" field, type /Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
  7. You should see the system libraries in the list titled "JRE system libraries:"
  8. Give the JRE a name. The recommended name is JDK 1.7. Click Finish.
  9. Check the checkbox next to the JRE entry you just created. This will cause Eclipse to use it as the default JRE for all new Java projects. Click OK.
  10. Now, create a new project. For this verification, from the menu, select File -> New -> Java Project.
  11. In the dialog that appears, enter a new name for your project. For this verification, type Test17Project
  12. In the JRE section of the dialog, select Use default JRE (currently JDK 1.7)
  13. Click Finish.

Hope this helps

How do I include a pipe | in my linux find -exec command?

find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'

How to search for an element in a golang slice

With a simple for loop:

for _, v := range myconfig {
    if v.Key == "key1" {
        // Found!
    }
}

Note that since element type of the slice is a struct (not a pointer), this may be inefficient if the struct type is "big" as the loop will copy each visited element into the loop variable.

It would be faster to use a range loop just on the index, this avoids copying the elements:

for i := range myconfig {
    if myconfig[i].Key == "key1" {
        // Found!
    }
}

Notes:

It depends on your case whether multiple configs may exist with the same key, but if not, you should break out of the loop if a match is found (to avoid searching for others).

for i := range myconfig {
    if myconfig[i].Key == "key1" {
        // Found!
        break
    }
}

Also if this is a frequent operation, you should consider building a map from it which you can simply index, e.g.

// Build a config map:
confMap := map[string]string{}
for _, v := range myconfig {
    confMap[v.Key] = v.Value
}

// And then to find values by key:
if v, ok := confMap["key1"]; ok {
    // Found
}

How to change TIMEZONE for a java.util.Calendar/Date

In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime() gives you the mentioned milliseconds).
In your solution:

Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();

long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);

you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.

Another possible solution would be to utilise the static fields of the Calendar class:

//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);

Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.

When are static variables initialized?

The static variable can be intialize in the following three ways as follow choose any one you like

  1. you can intialize it at the time of declaration
  2. or you can do by making static block eg:

    static {
            // whatever code is needed for initialization goes here
        }
    
  3. There is an alternative to static blocks — you can write a private static method

    class name {
        public static varType myVar = initializeVar();
    
        private static varType initializeVar() {
            // initialization code goes here
        }
    }
    

getting a checkbox array value from POST

// if you do the input like this
<input id="'.$userid.'" value="'.$userid.'"  name="invite['.$userid.']" type="checkbox">

// you can access the value directly like this:
$invite = $_POST['invite'][$userid];

'Operation is not valid due to the current state of the object' error during postback

If your stack trace looks like following then you are sending a huge load of json objects to server

Operation is not valid due to the current state of the object. 
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
    at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
    at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
    at Failing.Page_Load(Object sender, EventArgs e) 
    at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
    at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
    at System.Web.UI.Control.OnLoad(EventArgs e)
    at System.Web.UI.Control.LoadRecursive()
    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

For resolution, please update your web config with following key. If you are not able to get the stack trace then please use fiddler. If it still does not help then please try increasing the number to 10000 or something

<configuration>
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
</configuration>

For more details, please read this Microsoft kb article

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

Using If else in SQL Select statement

Here are two ways "IF" Or "CASE".

SELECT IF(COLUMN_NAME = "VALUE", "VALUE_1", "VALUE_2") AS COLUMN_NAME 
FROM TABLE_NAME;

OR

SELECT (CASE WHEN COLUMN_NAME = "VALUE" THEN 'VALUE_1' ELSE 'VALUE_2' END) AS COLUMN_NAME 
FROM TABLE_NAME;

Using jQuery to compare two arrays of Javascript objects

I don't think there's a good "jQuery " way to do this, but if you need efficiency, map one of the arrays by a certain key (one of the unique object fields), and then do comparison by looping through the other array and comparing against the map, or associative array, you just built.

If efficiency is not an issue, just compare every object in A to every object in B. As long as |A| and |B| are small, you should be okay.

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

You can always press CTRL-B + SHIFT-D to choose which client you want to detach from the session.

tmux will list all sessions with their current dimension. Then you simply detach from all the smaller sized sessions.

How to remove duplicates from Python list and keep order?

> but I don't know how to retrieve the list members from the hash in alphabetical order.

Not really your main question, but for future reference Rod's answer using sorted can be used for traversing a dict's keys in sorted order:

for key in sorted(my_dict.keys()):
   print key, my_dict[key]
   ...

and also because tuple's are ordered by the first member of the tuple, you can do the same with items:

for key, val in sorted(my_dict.items()):
    print key, val
    ...

Reflection: How to Invoke Method with parameters

You have a bug right there

result = methodInfo.Invoke(methodInfo, parametersArray);

it should be

result = methodInfo.Invoke(classInstance, parametersArray);

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

It is up to the browser but they behave in similar ways.

I have tested FF, IE7, Opera and Chrome.

F5 usually updates the page only if it is modified. The browser usually tries to use all types of cache as much as possible and adds an "If-modified-since" header to the request. Opera differs by sending a "Cache-Control: no-cache".

CTRL-F5 is used to force an update, disregarding any cache. IE7 adds an "Cache-Control: no-cache", as does FF, which also adds "Pragma: no-cache". Chrome does a normal "If-modified-since" and Opera ignores the key.

If I remember correctly it was Netscape which was the first browser to add support for cache-control by adding "Pragma: No-cache" when you pressed CTRL-F5.

Edit: Updated table

The table below is updated with information on what will happen when the browser's refresh-button is clicked (after a request by Joel Coehoorn), and the "max-age=0" Cache-control-header.

Updated table, 27 September 2010

+------------------------------------------------------------+
¦  UPDATED   ¦                Firefox 3.x                    ¦
¦27 SEP 2010 ¦  +--------------------------------------------¦
¦            ¦  ¦             MSIE 8, 7                      ¦
¦ Version 3  ¦  ¦  +-----------------------------------------¦
¦            ¦  ¦  ¦          Chrome 6.0                     ¦
¦            ¦  ¦  ¦  +--------------------------------------¦
¦            ¦  ¦  ¦  ¦       Chrome 1.0                     ¦
¦            ¦  ¦  ¦  ¦  +-----------------------------------¦
¦            ¦  ¦  ¦  ¦  ¦    Opera 10, 9                    ¦
¦            ¦  ¦  ¦  ¦  ¦  +--------------------------------¦
¦            ¦  ¦  ¦  ¦  ¦  ¦                                ¦
+------------+--+--+--+--+--+--------------------------------¦
¦          F5¦IM¦I ¦IM¦IM¦C ¦                                ¦
¦    SHIFT-F5¦- ¦- ¦CP¦IM¦- ¦ Legend:                        ¦
¦     CTRL-F5¦CP¦C ¦CP¦IM¦- ¦ I = "If-Modified-Since"        ¦
¦      ALT-F5¦- ¦- ¦- ¦- ¦*2¦ P = "Pragma: No-cache"         ¦
¦    ALTGR-F5¦- ¦I ¦- ¦- ¦- ¦ C = "Cache-Control: no-cache"  ¦
+------------+--+--+--+--+--¦ M = "Cache-Control: max-age=0" ¦
¦      CTRL-R¦IM¦I ¦IM¦IM¦C ¦ - = ignored                    ¦
¦CTRL-SHIFT-R¦CP¦- ¦CP¦- ¦- ¦                                ¦
+------------+--+--+--+--+--¦                                ¦
¦       Click¦IM¦I ¦IM¦IM¦C ¦ With 'click' I refer to a      ¦
¦ Shift-Click¦CP¦I ¦CP¦IM¦C ¦ mouse click on the browsers    ¦
¦  Ctrl-Click¦*1¦C ¦CP¦IM¦C ¦ refresh-icon.                  ¦
¦   Alt-Click¦IM¦I ¦IM¦IM¦C ¦                                ¦
¦ AltGr-Click¦IM¦I ¦- ¦IM¦- ¦                                ¦
+------------------------------------------------------------+

Versions tested:

  • Firefox 3.1.6 and 3.0.6 (WINXP)
  • MSIE 8.0.6001 and 7.0.5730.11 (WINXP)
  • Chrome 6.0.472.63 and 1.0.151.48 (WINXP)
  • Opera 10.62 and 9.61 (WINXP)

Notes:

  1. Version 3.0.6 sends I and C, but 3.1.6 opens the page in a new tab, making a normal request with only "I".

  2. Version 10.62 does nothing. 9.61 might do C unless it was a typo in my old table.

Note about Chrome 6.0.472: If you do a forced reload (like CTRL-F5) it behaves like the url is internally marked to always do a forced reload. The flag is cleared if you go to the address bar and press enter.

How do you rebase the current branch's changes on top of changes being merged in?

Another way to look at it is to consider git rebase master as:

Rebase the current branch on top of master

Here , 'master' is the upstream branch, and that explain why, during a rebase, ours and theirs are reversed.

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.

One option is to replace table with CSS4 flex divs:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

That works in new browsers i.e. IE11+ see table at the bottom of the article.

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.

Create two string data type variables namely DirPath and FilePath. Set the value C:\backup\ to the variable DirPath. Do not set any value to the variable FilePath.

Variables

Select the variable FilePath and select F4 to view the properties. Set the EvaluateAsExpression property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)

Expression

Redraw datatables after using ajax to refresh the table content?

Use this:

var table = $(selector).dataTables();
table.api().draw(false);

or

var table = $(selector).DataTables();
table.draw(false);

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.

The for loop you specified is absolutely correct.

Although i will do all the loops for you once again.

int sum = 0;
// for loop

for (int i = 1; i<= 100; i++){
    sum = sum + i;
}
System.out.println(sum);

// while loop

sum = 0;
int j = 1;

while(j<=100){
    sum = sum + j;
    j++;
}

System.out.println(sum);

// do while loop

sum = 0;
j = 1;

do{
    sum = sum + j;
    j++;
}
while(j<=100);

System.out.println(sum);

In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    onmouseover='this.style.textDecoration="none"' 
    onmouseout='this.style.textDecoration="underline"'>
    Click Me
</a>

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href="http://www.w3.org/Style/CSS"
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */
     ">
</a>

but it was never implemented in the release of the spec as far as I know.

http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules

How do I get the width and height of a HTML5 canvas?

It might be worth looking at a tutorial: MDN Canvas Tutorial

You can get the width and height of a canvas element simply by accessing those properties of the element. For example:

var canvas = document.getElementById('mycanvas');
var width = canvas.width;
var height = canvas.height;

If the width and height attributes are not present in the canvas element, the default 300x150 size will be returned. To dynamically get the correct width and height use the following code:

const canvasW = canvas.getBoundingClientRect().width;
const canvasH = canvas.getBoundingClientRect().height;

Or using the shorter object destructuring syntax:

const { width, height } = canvas.getBoundingClientRect();

The context is an object you get from the canvas to allow you to draw into it. You can think of the context as the API to the canvas, that provides you with the commands that enable you to draw on the canvas element.

Can I load a UIImage from a URL?

The way using a Swift Extension to UIImageView (source code here):

Creating Computed Property for Associated UIActivityIndicatorView

import Foundation
import UIKit
import ObjectiveC

private var activityIndicatorAssociationKey: UInt8 = 0

extension UIImageView {
    //Associated Object as Computed Property
    var activityIndicator: UIActivityIndicatorView! {
        get {
            return objc_getAssociatedObject(self, &activityIndicatorAssociationKey) as? UIActivityIndicatorView
        }
        set(newValue) {
            objc_setAssociatedObject(self, &activityIndicatorAssociationKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
        }
    }

    private func ensureActivityIndicatorIsAnimating() {
        if (self.activityIndicator == nil) {
            self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
            self.activityIndicator.hidesWhenStopped = true
            let size = self.frame.size;
            self.activityIndicator.center = CGPoint(x: size.width/2, y: size.height/2);
            NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                self.addSubview(self.activityIndicator)
                self.activityIndicator.startAnimating()
            })
        }
    }

Custom Initializer and Setter

    convenience init(URL: NSURL, errorImage: UIImage? = nil) {
        self.init()
        self.setImageFromURL(URL)
    }

    func setImageFromURL(URL: NSURL, errorImage: UIImage? = nil) {
        self.ensureActivityIndicatorIsAnimating()
        let downloadTask = NSURLSession.sharedSession().dataTaskWithURL(URL) {(data, response, error) in
            if (error == nil) {
                NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                    self.activityIndicator.stopAnimating()
                    self.image = UIImage(data: data)
                })
            }
            else {
                self.image = errorImage
            }
        }
        downloadTask.resume()
    }
}

How to generate an entity-relationship (ER) diagram using Oracle SQL Developer

There is a companion tool called Oracle Data Modeler that you could take a look at. There are online demos available at the site that will get you started. It used to be an added cost item, but I noticed that once again it's free.

From the Data Modeler overview page:

SQL Developer Data Modeler is a free data modeling and design tool, proving a full spectrum of data and database modeling tools and utilities, including modeling for Entity Relationship Diagrams (ERD), Relational (database design), Data Type and Multi-dimensional modeling, with forward and reverse engineering and DDL code generation. The Data Modeler imports from and exports to a variety of sources and targets, provides a variety of formatting options and validates the models through a predefined set of design rules.

Network tools that simulate slow network connection

For Linux or OSX, you can use ipfw.

From Quora (http://www.quora.com/What-is-the-best-tool-to-simulate-a-slow-internet-connection-on-a-Mac)

Essentially using a firewall to throttle all network data:

Define a rule that uses a pipe to reroute all traffic from any source address to any destination address, execute the following command (as root, or using sudo):

$ ipfw add pipe 1 all from any to any

To configure this rule to limit bandwidth to 300Kbit/s and impose 200ms of latency each way:

$ ipfw pipe 1 config bw 300Kbit/s delay 200ms

To remove all rules and recover your original network connection:

$ ipfw flush

Get a json via Http Request in NodeJS

Just setting json option to true, the body will contain the parsed json:

request({
  url: 'http://...',
  json: true
}, function(error, response, body) {
  console.log(body);
});

How to configure WAMP (localhost) to send email using Gmail?

I've answered that here: (WAMP/XAMP) send Mail using SMTP localhost (works not only GMAIL, but for others too).

download and install visual studio 2008

For Microsoft Visual C++ 2008, not the general Visual Studio (go.microsoft.com/?linkid=7729279?)

Google Visual Studio 2008 Express instead of just Visual Studio 2008. Click to the first link that appears which is a download link from Microsoft mentioned above.

iPhone App Minus App Store?

If you patch /Developer/Platforms/iPhoneOS.platform/Info.plist and then try to debug a application running on the device using a real development provisionen profile from Apple it will probably not work. Symptoms are weird error messages from com.apple.debugserver and that you can use any bundle identifier without getting a error when building in Xcode. The solution is to restore Info.plist.

Change link color of the current page with CSS

So for example if you are trying to change the text of the anchor on the current page that you are on only using CSS, then here is a simple solution.

I want to change the anchor text colour on my software page to light blue:

<div class="navbar">
    <ul>
       <a href="../index.html"><li>Home</li></a>
       <a href="usefulsites.html"><li>Useful Sites</li></a>
       <a href="software.html"><li class="currentpage">Software</li></a>
       <a href="workbench.html"><li>The Workbench</li></a>
       <a href="contact.php"><li>Contact</a></li></a>
    </ul>
</div>

And before anyone says that I got the <li> tags and the <a> tags mixed up, this is what makes it work as you are applying the value to the text itself only when you are on that page. Unfortunately, if you are using PHP to input header tags, then this will not work for obvious reasons. Then I put this in my style.css, with all my pages using the same style sheet:

.currentpage {
        color: lightblue;
}

How does += (plus equal) work?

a += b is shorthand for a = a +b which means:

1) 1 += 2 // won't compile

2) 15

SQL Plus change current directory

I think that the SQLPATH environment variable is the best way for this - if you have multiple paths, enter them separated by semi-colons (;). Keep in mind that if there are script files named the same in among the directories, the first one encountered (by order the paths are entered) will be executed, the second one will be ignored.

Custom ImageView with drop shadow

Okay, I don't foresee any more answers on this one, so what I ended up going with for now is just a solution for rectangular images. I've used the following NinePatch:

alt text

along with the appropriate padding in XML:

<ImageView
        android:id="@+id/image_test"
        android:background="@drawable/drop_shadow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="6px"
        android:paddingTop="4px"
        android:paddingRight="8px"
        android:paddingBottom="9px"
        android:src="@drawable/pic1"
        />

to get a fairly good result:

alt text

Not ideal, but it'll do.

Remove Datepicker Function dynamically

what about using the official API?

According to the API doc:

DESTROY: Removes the datepicker functionality completely. This will return the element back to its pre-init state.

Use:

$("#txtSearch").datepicker("destroy");

to restore the input to its normal behaviour and

$("#txtSearch").datepicker(/*options*/);

again to show the datapicker again.

Formatting Numbers by padding with leading zeros in SQL Server

In my version of SQL I can't use REPLICATE. SO I did this:

SELECT 
    CONCAT(REPEAT('0', 6-LENGTH(emplyeeID)), emplyeeID) AS emplyeeID 
FROM 
    dbo.RequestItems`

add an onclick event to a div

Everythings works well. You can't use divtag.onclick, becease "onclick" attribute doesn't exist. You need first create this attribute by using .setAttribute(). Look on this http://reference.sitepoint.com/javascript/Element/setAttribute . You should read documentations first before you start giving "-".

New self vs. new static

In addition to others' answers :

static:: will be computed using runtime information.

That means you can't use static:: in a class property because properties values :

Must be able to be evaluated at compile time and must not depend on run-time information.

class Foo {
    public $name = static::class;

}

$Foo = new Foo;
echo $Foo->name; // Fatal error

Using self::

class Foo {
    public $name = self::class;

}
$Foo = new Foo;
echo $Foo->name; // Foo

Please note that the Fatal error comment in the code i made doesn't indicate where the error happened, the error happened earlier before the object was instantiated as @Grapestain mentioned in the comments

ConfigurationManager.AppSettings - How to modify and save?

I think the problem is that in the debug visual studio don't use the normal exeName.

it use indtead "NameApplication".host.exe

so the name of the config file is "NameApplication".host.exe.config and not "NameApplication".exe.config

and after the application close - it return to the back app.config

so if you check the wrong file or you check on the wrong time you will see that nothing changed.

Starting Docker as Daemon on Ubuntu

There are multiple popular repositories offering docker packages for Ubuntu. The package docker.io is (most likely) from the Ubuntu repository. Another popular one is http://get.docker.io/ubuntu which offers a package lxc-docker (I am running the latter because it ships updates faster). Make sure only one package is installed. Not quite sure if removal of the packages cleans up properly. If sudo service docker restart still does not work, you may have to clean up manually in /etc/.

File path for project files?

Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JukeboxV2.0\JukeboxV2.0\Datos\ich will.mp3")

base directory + your filename

How can I brew link a specific version?

I asked in #machomebrew and learned that you can switch between versions using brew switch.

$ brew switch libfoo mycopy 

to get version mycopy of libfoo.

Using arrays or std::vectors in C++, what's the performance gap?

There is definitely a performance impact to using an std::vector vs a raw array when you want an uninitialized buffer (e.g. to use as destination for memcpy()). An std::vector will initialize all its elements using the default constructor. A raw array will not.

The c++ spec for the std:vector constructor taking a count argument (it's the third form) states:

`Constructs a new container from a variety of data sources, optionally using a user supplied allocator alloc.

  1. Constructs the container with count default-inserted instances of T. No copies are made.

Complexity

2-3) Linear in count

A raw array does not incur this initialization cost.

Note that with a custom allocator, it is possible to avoid "initialization" of the vector's elements (i.e. to use default initialization instead of value initialization). See these questions for more details:

Python: finding an element in a list

how's this one?

def global_index(lst, test):
    return ( pair[0] for pair in zip(range(len(lst)), lst) if test(pair[1]) )

Usage:

>>> global_index([1, 2, 3, 4, 5, 6], lambda x: x>3)
<generator object <genexpr> at ...>
>>> list(_)
[3, 4, 5]

Groovy String to Date

I think the best easy way in this case is to use parseToStringDate which is part of GDK (Groovy JDK enhancements):

Parse a String matching the pattern EEE MMM dd HH:mm:ss zzz yyyy containing US-locale-constants only (e.g. Sat for Saturdays). Such a string is generated by the toString method of Date

Example:

println(Date.parseToStringDate("Tue Aug 10 16:02:43 PST 2010").format('MM-dd-yyyy'))

Angular 2 / 4 / 5 - Set base href dynamically

In angular4, you can also configure the baseHref in .angular-cli.json apps.

in .angular-cli.json

{   ....
 "apps": [
        {
            "name": "myapp1"
            "baseHref" : "MY_APP_BASE_HREF_1"
         },
        {
            "name": "myapp2"
            "baseHref" : "MY_APP_BASE_HREF_2"
         },
    ],
}

this will update base href in index.html to MY_APP_BASE_HREF_1

ng build --app myapp1

Fatal error: Class 'ZipArchive' not found in

I had the same issue with CentOS and cPanel installed server. I installed zipArchive package via cPanel and didn't worked as expected. After trying with so many fixes suggested each and everywhere just the below worked for me.

First find the name for the correct package with the below command

yum search zip |grep -i php

Then use the below code.

yum install your_zip_package_name_with_php_version

In my case correct code to install zipArchive was

yum install php-pecl-zip.x86_64

I had the solution from this link. How can I inslatt zipArchive on PHP 7.2 with CentOS 7?

And this installation somehow enabled that package too and it also restarted the effecting services and after the completion of the execution of the above code zipArchive issue was gone.

How to test which port MySQL is running on and whether it can be connected to?

Both URLs are incorrect - should be

jdbc:mysql://host:port/database

I thought it went without saying, but connecting to a database with Java requires a JDBC driver. You'll need the MySQL JDBC driver.

Maybe you can connect using a socket over TCP/IP. Check out the MySQL docs.

See http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html

UPDATE:

I tried to telnet into MySQL (telnet ip 3306), but it doesn't work:

http://lists.mysql.com/win32/253

I think this is what you had in mind.

Open Redis port for remote connections

Bind & protected-mode both are the essential steps. But if ufw is enabled then you will have to make redis port allow in ufw.

  1. Check ufw status ufw status if Status: active then allow redis-port ufw allow 6379
  2. vi /etc/redis/redis.conf
  3. Change the bind 127.0.0.1 to bind 0.0.0.0
  4. change the protected-mode yes to protected-mode no

Submit a form in a popup, and then close the popup

I know this is an old question, but I stumbled across it when I was having a similar issue, and just wanted to share how I ended achieving the results you requested so future people can pick what works best for their situation.

First, I utilize the onsubmit event in the form, and pass this to the function to make it easier to deal with this particular form.

<form action="/system/wpacert" onsubmit="return closeSelf(this);" method="post" enctype="multipart/form-data"  name="certform">
    <div>Certificate 1: <input type="file" name="cert1"/></div>
    <div>Certificate 2: <input type="file" name="cert2"/></div>
    <div>Certificate 3: <input type="file" name="cert3"/></div>

    <div><input type="submit" value="Upload"/></div>
</form>

In our function, we'll submit the form data, and then we'll close the window. This will allow it to submit the data, and once it's done, then it'll close the window and return you to your original window.

<script type="text/javascript">
  function closeSelf (f) {
     f.submit();
     window.close();
  }
</script>

Hope this helps someone out. Enjoy!


Option 2: This option will let you submit via AJAX, and if it's successful, it'll close the window. This prevents windows from closing prior to the data being submitted. Credits to http://jquery.malsup.com/form/ for their work on the jQuery Form Plugin

First, remove your onsubmit/onclick events from the form/submit button. Place an ID on the form so AJAX can find it.

<form action="/system/wpacert" method="post" enctype="multipart/form-data"  id="certform">
    <div>Certificate 1: <input type="file" name="cert1"/></div>
    <div>Certificate 2: <input type="file" name="cert2"/></div>
    <div>Certificate 3: <input type="file" name="cert3"/></div>

    <div><input type="submit" value="Upload"/></div>
</form>

Second, you'll want to throw this script at the bottom, don't forget to reference the plugin. If the form submission is successful, it'll close the window.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
<script src="http://malsup.github.com/jquery.form.js"></script> 

    <script>
       $(document).ready(function () {
          $('#certform').ajaxForm(function () {
          window.close();
          });
       });
    </script>

How to empty a list in C#?

If by "list" you mean a List<T>, then the Clear method is what you want:

List<string> list = ...;
...
list.Clear();

You should get into the habit of searching the MSDN documentation on these things.

Here's how to quickly search for documentation on various bits of that type:

All of these Google queries lists a bundle of links, but typically you want the first one that google gives you in each case.

Connect Bluestacks to Android Studio

In my case I didn't needed start adb.exe. I only started the BlueStacks before android studio.

After that when I press "Run" in android studio, bluestacks is detected as a new emulator.

enter image description here

enter image description here

Regards.

What does -> mean in Python function definitions?

As other answers have stated, the -> symbol is used as part of function annotations. In more recent versions of Python >= 3.5, though, it has a defined meaning.

PEP 3107 -- Function Annotations described the specification, defining the grammar changes, the existence of func.__annotations__ in which they are stored and, the fact that it's use case is still open.

In Python 3.5 though, PEP 484 -- Type Hints attaches a single meaning to this: -> is used to indicate the type that the function returns. It also seems like this will be enforced in future versions as described in What about existing uses of annotations:

The fastest conceivable scheme would introduce silent deprecation of non-type-hint annotations in 3.6, full deprecation in 3.7, and declare type hints as the only allowed use of annotations in Python 3.8.

(Emphasis mine)

This hasn't been actually implemented as of 3.6 as far as I can tell so it might get bumped to future versions.

According to this, the example you've supplied:

def f(x) -> 123:
    return x

will be forbidden in the future (and in current versions will be confusing), it would need to be changed to:

def f(x) -> int:
    return x

for it to effectively describe that function f returns an object of type int.

The annotations are not used in any way by Python itself, it pretty much populates and ignores them. It's up to 3rd party libraries to work with them.

Replace string within file contents

Using pathlib (https://docs.python.org/3/library/pathlib.html)

from pathlib import Path
file = Path('Stud.txt')
file.write_text(file.read_text().replace('A', 'Orange'))

If input and output files were different you would use two different variables for read_text and write_text.

If you wanted a change more complex than a single replacement, you would assign the result of read_text to a variable, process it and save the new content to another variable, and then save the new content with write_text.

If your file was large you would prefer an approach that does not read the whole file in memory, but rather process it line by line as show by Gareth Davidson in another answer (https://stackoverflow.com/a/4128192/3981273), which of course requires to use two distinct files for input and output.

"Find next" in Vim

If you press Ctrl + Enter after you press something like "/wordforsearch", then you can find the word "wordforsearch" in the current line. Then press n for the next match; press N for previous match.

PHP convert XML to JSON

This is better solution

$fileContents= file_get_contents("https://www.feedforall.com/sample.xml");
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
$array = json_decode($json,TRUE);
return $array;

How to call javascript function from code-behind

This is a way to invoke one or more JavaScript methods from the code behind. By using Script Manager we can call the methods in sequence. Consider the below code for example.

ScriptManager.RegisterStartupScript(this, typeof(Page), "UpdateMsg", 
    "$(document).ready(function(){EnableControls();
    alert('Overrides successfully Updated.');
    DisableControls();});", 
true);

In this first method EnableControls() is invoked. Next the alert will be displayed. Next the DisableControls() method will be invoked.

jquery Ajax call - data parameters are not being passed to MVC Controller action

I tried:

<input id="btnTest" type="button" value="button" />

<script type="text/javascript">
    $(document).ready( function() {
      $('#btnTest').click( function() {
        $.ajax({
          type: "POST", 
          url: "/Login/Test",
          data: { ListID: '1', ItemName: 'test' },
          dataType: "json",
          success: function(response) { alert(response); },
          error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
        });
      });
    });
</script>

and C#:

[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
    return Content(ListID + " " + ItemName);
}

It worked. Remove contentType and set data without double quotes.

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

Setting PATH environment variable in OSX permanently

For a new path to be added to PATH environment variable in MacOS just create a new file under /etc/paths.d directory and add write path to be set in the file. Restart the terminal. You can check with echo $PATH at the prompt to confirm if the path was added to the environment variable.

For example: to add a new path /usr/local/sbin to the PATH variable:

cd /etc/paths.d
sudo vi newfile

Add the path to the newfile and save it.

Restart the terminal and type echo $PATH to confirm

Could not obtain information about Windows NT group user

We encountered similar errors in a testing environment on a virtual machine. If the machine name changes due to VM cloning from a template, you can get this error.

If the computer name changed from OLD to NEW.

A job uses this stored procedure:

msdb.dbo.sp_sqlagent_has_server_access @login_name = 'OLD\Administrator'

Which uses this one:

EXECUTE master.dbo.xp_logininfo 'OLD\Administrator'

Which gives this SQL error 15404

select text from sys.messages where message_id = 15404;
Could not obtain information about Windows NT group/user '%ls', error code %#lx.

Which I guess is correct, under the circumstances. We added a script to the VM cloning/deployment process that re-creates the SQL login.

MongoDB SELECT COUNT GROUP BY

I need some extra operation based on the result of aggregate function. Finally I've found some solution for aggregate function and the operation based on the result in MongoDB. I've a collection Request with field request, source, status, requestDate.

Single Field Group By & Count:

db.Request.aggregate([
    {"$group" : {_id:"$source", count:{$sum:1}}}
])

Multiple Fields Group By & Count:

db.Request.aggregate([
    {"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}}
])

Multiple Fields Group By & Count with Sort using Field:

db.Request.aggregate([
    {"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}},
    {$sort:{"_id.source":1}}
])

Multiple Fields Group By & Count with Sort using Count:

db.Request.aggregate([
    {"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}},
    {$sort:{"count":-1}}
])

Convert UTC dates to local time in PHP

I store date in the DB in UTC format but then I show them to the final user in their local timezone

// retrieve
$d = (new \DateTime($val . ' UTC'))->format('U');
return date("Y-m-d H:i:s", $d);

Change connection string & reload app.config at run time

First you might want to add

using System.Configuration;

To your .cs file. If it not available add it through the Project References as it is not included by default in a new project.

This is my solution to this problem. First I made the ConnectionProperties Class that saves the items I need to change in the original connection string. The _name variable in the ConnectionProperties class is important to be the name of the connectionString The first method takes a connection string and changes the option you want with the new value.

private String changeConnStringItem(string connString,string option, string value)
    {
        String[] conItems = connString.Split(';');
        String result = "";
        foreach (String item in conItems)
        {
            if (item.StartsWith(option))
            {
                result += option + "=" + value + ";";
            }
            else
            {
                result += item + ";";
            }
        }
        return result;
    }

You can change this method to accomodate your own needs. I have both mysql and mssql connections so I needed both of them. Of course you can refine this draft code for yourself.

private void changeConnectionSettings(ConnectionProperties cp)
{
     var cnSection = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
     String connString = cnSection.ConnectionStrings.ConnectionStrings[cp.Name].ConnectionString;
     connString = changeConnStringItem(connString, "provider connection string=\"data source", cp.DataSource);
     connString = changeConnStringItem(connString, "provider connection string=\"server", cp.DataSource);
     connString = changeConnStringItem(connString, "user id", cp.Username);
     connString = changeConnStringItem(connString, "password", cp.Password);
     connString = changeConnStringItem(connString, "initial catalog", cp.InitCatalogue);
     connString = changeConnStringItem(connString, "database", cp.InitCatalogue);
           cnSection.ConnectionStrings.ConnectionStrings[cp.Name].ConnectionString = connString;
     cnSection.Save();
     ConfigurationManager.RefreshSection("connectionStrings");
}

As I didn't want to add trivial information I ommited the Properties region of my code. Please add it if you want this to work.

class ConnectionProperties
{
    private String _name;
    private String _dataSource;
    private String _username;
    private String _password;
    private String _initCatalogue;

    /// <summary>
    /// Basic Connection Properties constructor
    /// </summary>
    public ConnectionProperties()
    {

    }

    /// <summary>
    /// Constructor with the needed settings
    /// </summary>
    /// <param name="name">The name identifier of the connection</param>
    /// <param name="dataSource">The url where we connect</param>
    /// <param name="username">Username for connection</param>
    /// <param name="password">Password for connection</param>
    /// <param name="initCat">Initial catalogue</param>
    public ConnectionProperties(String name,String dataSource, String username, String password, String initCat)
    {
        _name = name;
        _dataSource = dataSource;
        _username = username;
        _password = password;
        _initCatalogue = initCat;
    }
// Enter corresponding Properties here for access to private variables
}

Making href (anchor tag) request POST instead of GET?

Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS

$(function() {
  $("#employeeLink").on("click",function(e) {
    e.preventDefault(); // cancel the link itself
    $.post(this.href,function(data) {
      $("#someContainer").html(data);
    });
  });
});

If you insist on using frames which I strongly discourage, have a form and submit it with the link

<form action="employee.action" method="post" target="myFrame" id="myForm"></form>

and use (in plain JS)

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the link
     document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
   });
 });

Without a form we need to make one

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the actual link
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
   });
 });

Get name of property as a string

I've been using this answer to great effect: Get the property, as a string, from an Expression<Func<TModel,TProperty>>

I realize I already answered this question a while back. The only advantage my other answer has is that it works for static properties. I find the syntax in this answer much more useful because you don't have to create a variable of the type you want to reflect.

How do getters and setters work?

Here is an example to explain the most simple way of using getter and setter in java. One can do this in a more straightforward way but getter and setter have something special that is when using private member of parent class in child class in inheritance. You can make it possible through using getter and setter.

package stackoverflow;

    public class StackoverFlow 

    {

        private int x;

        public int getX()
        {
            return x;
        }

        public int setX(int x)
        {
          return  this.x = x;
        }
         public void showX()
         {
             System.out.println("value of x  "+x);
         }


        public static void main(String[] args) {

            StackoverFlow sto = new StackoverFlow();
            sto.setX(10);
            sto.getX();
            sto.showX();
        }

    }

How to keep the local file or the remote file during merge using Git and the command line?

This approach seems more straightforward, avoiding the need to individually select each file:

# keep remote files
git merge --strategy-option theirs
# keep local files
git merge --strategy-option ours

or

# keep remote files
git pull -Xtheirs
# keep local files
git pull -Xours

Copied directly from: Resolve Git merge conflicts in favor of their changes during a pull

How to specify credentials when connecting to boto3 S3?

I'd like expand on @JustAGuy's answer. The method I prefer is to use AWS CLI to create a config file. The reason is, with the config file, the CLI or the SDK will automatically look for credentials in the ~/.aws folder. And the good thing is that AWS CLI is written in python.

You can get cli from pypi if you don't have it already. Here are the steps to get cli set up from terminal

$> pip install awscli  #can add user flag 
$> aws configure
AWS Access Key ID [****************ABCD]:[enter your key here]
AWS Secret Access Key [****************xyz]:[enter your secret key here]
Default region name [us-west-2]:[enter your region here]
Default output format [None]:

After this you can access boto and any of the api without having to specify keys (unless you want to use a different credentials).

Extracting jar to specified directory

This is what I ended up using inside my .bat file. Windows only of course.

set CURRENT_DIR=%cd%
mkdir ./directoryToExtractTo
cd ./directoryToExtractTo
jar xvf %CURRENT_DIR%\myJar.jar
cd %CURRENT_DIR%

When to use Hadoop, HBase, Hive and Pig?

Use of Hive, Hbase and Pig w.r.t. my real time experience in different projects.

Hive is used mostly for:

  • Analytics purpose where you need to do analysis on history data

  • Generating business reports based on certain columns

  • Efficiently managing the data together with metadata information

  • Joining tables on certain columns which are frequently used by using bucketing concept

  • Efficient Storing and querying using partitioning concept

  • Not useful for transaction/row level operations like update, delete, etc.

Pig is mostly used for:

  • Frequent data analysis on huge data

  • Generating aggregated values/counts on huge data

  • Generating enterprise level key performance indicators very frequently

Hbase is mostly used:

  • For real time processing of data

  • For efficiently managing Complex and nested schema

  • For real time querying and faster result

  • For easy Scalability with columns

  • Useful for transaction/row level operations like update, delete, etc.

ios simulator: how to close an app

You can use this command to quit an app in iOS Simulator

xcrun simctl terminate booted com.apple.mobilesafari

You will need to know the bundle id of the app you have installed in the simulator. You can refer to this link

Table with table-layout: fixed; and how to make one column wider

Are you creating a very large table (hundreds of rows and columns)? If so, table-layout: fixed; is a good idea, as the browser only needs to read the first row in order to compute and render the entire table, so it loads faster.

But if not, I would suggest dumping table-layout: fixed; and changing your css as follows:

table th, table td{
border: 1px solid #000;
width:20px;  //or something similar   
}

table td.wideRow, table th.wideRow{
width: 300px;
}

http://jsfiddle.net/6p9K3/1/

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

How can I find all the subsets of a set, with exactly n elements?

Here is one neat way with easy to understand algorithm.

import copy

nums = [2,3,4,5]
subsets = [[]]

for n in nums:
    prev = copy.deepcopy(subsets)
    [k.append(n) for k in subsets]
    subsets.extend(prev)

print(subsets) 
print(len(subsets))

# [[2, 3, 4, 5], [3, 4, 5], [2, 4, 5], [4, 5], [2, 3, 5], [3, 5], [2, 5], [5], 
# [2, 3, 4], [3, 4], [2, 4], [4], [2, 3], [3], [2], []]

# 16 (2^len(nums))

Upload files with FTP using PowerShell

I recently wrote for powershell several functions for communicating with FTP, see https://github.com/AstralisSomnium/PowerShell-No-Library-Just-Functions/blob/master/FTPModule.ps1. The second function below, you can send a whole local folder to FTP. In the module are even functions for removing / adding / reading folders and files recursively.

#Add-FtpFile -ftpFilePath "ftp://myHost.com/folder/somewhere/uploaded.txt" -localFile "C:\temp\file.txt" -userName "User" -password "pw"
function Add-FtpFile($ftpFilePath, $localFile, $username, $password) {
    $ftprequest = New-FtpRequest -sourceUri $ftpFilePath -method ([System.Net.WebRequestMethods+Ftp]::UploadFile) -username $username -password $password
    Write-Host "$($ftpRequest.Method) for '$($ftpRequest.RequestUri)' complete'"
    $content = $content = [System.IO.File]::ReadAllBytes($localFile)
    $ftprequest.ContentLength = $content.Length
    $requestStream = $ftprequest.GetRequestStream()
    $requestStream.Write($content, 0, $content.Length)
    $requestStream.Close()
    $requestStream.Dispose()
}

#Add-FtpFolderWithFiles -sourceFolder "C:\temp\" -destinationFolder "ftp://myHost.com/folder/somewhere/" -userName "User" -password "pw"
function Add-FtpFolderWithFiles($sourceFolder, $destinationFolder, $userName, $password) {
    Add-FtpDirectory $destinationFolder $userName $password
    $files = Get-ChildItem $sourceFolder -File
    foreach($file in $files) {
        $uploadUrl ="$destinationFolder/$($file.Name)"
        Add-FtpFile -ftpFilePath $uploadUrl -localFile $file.FullName -username $userName -password $password
    }
}

#Add-FtpFolderWithFilesRecursive -sourceFolder "C:\temp\" -destinationFolder "ftp://myHost.com/folder/" -userName "User" -password "pw"
function Add-FtpFolderWithFilesRecursive($sourceFolder, $destinationFolder, $userName, $password) {
    Add-FtpFolderWithFiles -sourceFolder $sourceFolder -destinationFolder $destinationFolder -userName $userName -password $password
    $subDirectories = Get-ChildItem $sourceFolder -Directory
    $fromUri = new-object System.Uri($sourceFolder)
    foreach($subDirectory in $subDirectories) {
        $toUri  = new-object System.Uri($subDirectory.FullName)
        $relativeUrl = $fromUri.MakeRelativeUri($toUri)
        $relativePath = [System.Uri]::UnescapeDataString($relativeUrl.ToString())
        $lastFolder = $relativePath.Substring($relativePath.LastIndexOf("/")+1)
        Add-FtpFolderWithFilesRecursive -sourceFolder $subDirectory.FullName -destinationFolder "$destinationFolder/$lastFolder" -userName $userName -password $password
    }
}

How can I get zoom functionality for images?

You could also try out http://code.google.com/p/android-multitouch-controller/

The library is really great, although initially a little hard to grasp.

How to use onBlur event on Angular2?

HTML

<input name="email" placeholder="Email"  (blur)="$event.target.value=removeSpaces($event.target.value)" value="">

TS

removeSpaces(string) {
 let splitStr = string.split(' ').join('');
  return splitStr;
}

Html/PHP - Form - Input as array

in addition: for those who have a empty POST variable, don't use this:

name="[levels][level][]"

rather use this (as it is already here in this example):

name="levels[level][]"

AppStore - App status is ready for sale, but not in app store

I had "ready for sale" status for 1 week and app still wasn't visible in store. I "changed" the pricing (from free to free starting today) like KlimczakM suggested in one of comments above. Also, I changed promotional text and saved changes. After less than half of hour app was in the store.

Programmatically relaunch/recreate an activity?

Option 1

Call recreate() on your Activity. However this method causes a flashing black screen to appear during the activity re-creation.

Option 2

finish();
startActivity(getIntent());

No "flashing" black screen here, but you'll see a transition between the old and the new instances with a not-so-pleasant black background. We can do better.

Option 3

To fix this, we can add a call to overridePendingTransition() :

finish();
startActivity(getIntent());
overridePendingTransition(0, 0);

Good bye black screen, but in my case I still see some kind of transition (a fade animation), on a colored background this time. That's because you're finishing the current instance of your activity before the new one is created and becomes fully visible, and the in-between color is the value of the windowBackground theme attribute.

Option 4

startActivity(getIntent());
finish();

Calling finish() after startActivity() will use the default transition between activities, often with a little slide-in animation. But the transition is still visible.

Option 5

startActivity(getIntent());
finish();
overridePendingTransition(0, 0);

To me, this is the best solution because it restarts the activity without any visible transition, like if nothing happened.

It could be useful if, for example, in your app you expose a way to change the display language independently of the system's language. In this case, whenever the user changes your app's language you'll probably want to restart your activity without transition, making the language switch look instantaneous.

How to insert a text at the beginning of a file?

my two cents:

sed  -i '1i /path/of/file.sh' filename

This will work even is the string containing forward slash "/"

PHP Session data not being saved

Here is one common problem I haven't seen addressed in the other comments: is your host running a cache of some sort? If they are automatically caching results in some fashion you would get this sort of behavior.

How to restrict the selectable date ranges in Bootstrap Datepicker?

The Bootstrap datepicker is able to set date-range. But it is not available in the initial release/Master Branch. Check the branch as 'range' there (or just see at https://github.com/eternicode/bootstrap-datepicker), you can do it simply with startDate and endDate.

Example:

$('#datepicker').datepicker({
    startDate: '-2m',
    endDate: '+2d'
});

How to assign colors to categorical variables in ggplot2 that have stable mapping?

I am in the same situation pointed out by malcook in his comment: unfortunately the answer by Thierry does not work with ggplot2 version 0.9.3.1.

png("figure_%d.png")
set.seed(2014)
library(ggplot2)
dataset <- data.frame(category = rep(LETTERS[1:5], 100),
    x = rnorm(500, mean = rep(1:5, 100)),
    y = rnorm(500, mean = rep(1:5, 100)))
dataset$fCategory <- factor(dataset$category)
subdata <- subset(dataset, category %in% c("A", "D", "E"))

ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point()

Here it is the first figure:

ggplot A-E, mixed colors

and the second figure:

ggplot ADE, mixed colors

As we can see the colors do not stay fixed, for example E switches from magenta to blu.

As suggested by malcook in his comment and by hadley in his comment the code which uses limits works properly:

ggplot(subdata, aes(x = x, y = y, colour = fCategory)) +       
    geom_point() + 
    scale_colour_discrete(drop=TRUE,
        limits = levels(dataset$fCategory))

gives the following figure, which is correct:

correct ggplot

This is the output from sessionInfo():

R version 3.0.2 (2013-09-25)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] methods   stats     graphics  grDevices utils     datasets  base     

other attached packages:
[1] ggplot2_0.9.3.1

loaded via a namespace (and not attached):
 [1] colorspace_1.2-4   dichromat_2.0-0    digest_0.6.4       grid_3.0.2        
 [5] gtable_0.1.2       labeling_0.2       MASS_7.3-29        munsell_0.4.2     
 [9] plyr_1.8           proto_0.3-10       RColorBrewer_1.0-5 reshape2_1.2.2    
[13] scales_0.2.3       stringr_0.6.2 

How do I trap ctrl-c (SIGINT) in a C# console app

I'd like to add to Jonas' answer. Spinning on a bool will cause 100% CPU utilization, and waste a bunch of energy doing a lot of nothing while waiting for CTRL+C.

The better solution is to use a ManualResetEvent to actually "wait" for the CTRL+C:

static void Main(string[] args) {
    var exitEvent = new ManualResetEvent(false);

    Console.CancelKeyPress += (sender, eventArgs) => {
                                  eventArgs.Cancel = true;
                                  exitEvent.Set();
                              };

    var server = new MyServer();     // example
    server.Run();

    exitEvent.WaitOne();
    server.Stop();
}

How can I get a list of locally installed Python modules?

Solution

Do not use with pip > 10.0!

My 50 cents for getting a pip freeze-like list from a Python script:

import pip
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
     for i in installed_packages])
print(installed_packages_list)

As a (too long) one liner:

sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])

Giving:

['behave==1.2.4', 'enum34==1.0', 'flask==0.10.1', 'itsdangerous==0.24', 
 'jinja2==2.7.2', 'jsonschema==2.3.0', 'markupsafe==0.23', 'nose==1.3.3', 
 'parse-type==0.3.4', 'parse==1.6.4', 'prettytable==0.7.2', 'requests==2.3.0',
 'six==1.6.1', 'vioozer-metadata==0.1', 'vioozer-users-server==0.1', 
 'werkzeug==0.9.4']

Scope

This solution applies to the system scope or to a virtual environment scope, and covers packages installed by setuptools, pip and (god forbid) easy_install.

My use case

I added the result of this call to my flask server, so when I call it with http://example.com/exampleServer/environment I get the list of packages installed on the server's virtualenv. It makes debugging a whole lot easier.

Caveats

I have noticed a strange behaviour of this technique - when the Python interpreter is invoked in the same directory as a setup.py file, it does not list the package installed by setup.py.

Steps to reproduce:

Create a virtual environment
$ cd /tmp
$ virtualenv test_env
New python executable in test_env/bin/python
Installing setuptools, pip...done.
$ source test_env/bin/activate
(test_env) $ 
Clone a git repo with setup.py
(test_env) $ git clone https://github.com/behave/behave.git
Cloning into 'behave'...
remote: Reusing existing pack: 4350, done.
remote: Total 4350 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (4350/4350), 1.85 MiB | 418.00 KiB/s, done.
Resolving deltas: 100% (2388/2388), done.
Checking connectivity... done.

We have behave's setup.py in /tmp/behave:

(test_env) $ ls /tmp/behave/setup.py
/tmp/behave/setup.py
Install the python package from the git repo
(test_env) $ cd /tmp/behave && pip install . 
running install
...
Installed /private/tmp/test_env/lib/python2.7/site-packages/enum34-1.0-py2.7.egg
Finished processing dependencies for behave==1.2.5a1

If we run the aforementioned solution from /tmp

>>> import pip
>>> sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
['behave==1.2.5a1', 'enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1']
>>> import os
>>> os.getcwd()
'/private/tmp'

If we run the aforementioned solution from /tmp/behave

>>> import pip
>>> sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
['enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1']
>>> import os
>>> os.getcwd()
'/private/tmp/behave'

behave==1.2.5a1 is missing from the second example, because the working directory contains behave's setup.py file.

I could not find any reference to this issue in the documentation. Perhaps I shall open a bug for it.

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

By using synchronized on a static method lock you will synchronize the class methods and attributes ( as opposed to instance methods and attributes )

So your assumption is correct.

I am wondering if making the method synchronized is the right approach to ensure thread-safety.

Not really. You should let your RDBMS do that work instead. They are good at this kind of stuff.

The only thing you will get by synchronizing the access to the database is to make your application terribly slow. Further more, in the code you posted you're building a Session Factory each time, that way, your application will spend more time accessing the DB than performing the actual job.

Imagine the following scenario:

Client A and B attempt to insert different information into record X of table T.

With your approach the only thing you're getting is to make sure one is called after the other, when this would happen anyway in the DB, because the RDBMS will prevent them from inserting half information from A and half from B at the same time. The result will be the same but only 5 times ( or more ) slower.

Probably it could be better to take a look at the "Transactions and Concurrency" chapter in the Hibernate documentation. Most of the times the problems you're trying to solve, have been solved already and a much better way.

.NET HttpClient. How to POST string value?

There is an article about your question on asp.net's website. I hope it can help you.

How to call an api with asp net

http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

Here is a small part from the POST section of the article

The following code sends a POST request that contains a Product instance in JSON format:

// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
    // Get the URI of the created resource.
    Uri gizmoUrl = response.Headers.Location;
}

AlertDialog styling - how to change style (color) of title, message, etc

I changed color programmatically in this way :

var builder = new AlertDialog.Builder (this);
...
...
...
var dialog = builder.Show ();
int textColorId = Resources.GetIdentifier ("alertTitle", "id", "android");
TextView textColor = dialog.FindViewById<TextView> (textColorId);
textColor?.SetTextColor (Color.DarkRed);

as alertTitle, you can change other data by this way (next example is for titleDivider):

int titleDividerId = Resources.GetIdentifier ("titleDivider", "id", "android");
View titleDivider = dialog.FindViewById (titleDividerId);
titleDivider?.SetBackgroundColor (Color.Red);

this is in C#, but in java it is the same.

Faking an RS232 Serial Port

If you are developing for Windows, the com0com project might be, what you are looking for.

It provides pairs of virtual COM ports that are linked via a nullmodem connetion. You can then use your favorite terminal application or whatever you like to send data to one COM port and recieve from the other one.

EDIT:

As Thomas pointed out the project lacks of a signed driver, which is especially problematic on certain Windows version (e.g. Windows 7 x64).

There are a couple of unofficial com0com versions around that do contain a signed driver. One recent verion (3.0.0.0) can be downloaded e.g. from here.

Combine two pandas Data Frames (join on a common column)

You can use merge to combine two dataframes into one:

import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')

where on specifies field name that exists in both dataframes to join on, and how defines whether its inner/outer/left/right join, with outer using 'union of keys from both frames (SQL: full outer join).' Since you have 'star' column in both dataframes, this by default will create two columns star_x and star_y in the combined dataframe. As @DanAllan mentioned for the join method, you can modify the suffixes for merge by passing it as a kwarg. Default is suffixes=('_x', '_y'). if you wanted to do something like star_restaurant_id and star_restaurant_review, you can do:

 pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))

The parameters are explained in detail in this link.

Find the max of two or more columns with pandas

You can get the maximum like this:

>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]]
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]].max(axis=1)
0    1
1    8
2    3

and so:

>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

If you know that "A" and "B" are the only columns, you could even get away with

>>> df["C"] = df.max(axis=1)

And you could use .apply(max, axis=1) too, I guess.

How to get the clicked link's href with jquery?

$(".testClick").click(function () {
         var value = $(this).attr("href");
         alert(value );     
}); 

When you use $(".className") you are getting the set of all elements that have that class. Then when you call attr it simply returns the value of the first item in the collection.

Add two numbers and display result in textbox with Javascript

<script>

function sum()
{
    var value1= parseInt(document.getElementById("txtfirst").value);
    var value2=parseInt(document.getElementById("txtsecond").value);
    var sum=value1+value2;
    document.getElementById("result").value=sum;

}
 </script>

Get a DataTable Columns DataType

You can get column type of DataTable with DataType attribute of datatable column like below:

var type = dt.Columns[0].DataType

dt : DataTable object.

0 : DataTable column index.

Hope It Helps

Ty :)

SSIS Excel Import Forcing Incorrect Column Type

I had the same issue, multiple data type values in single column, package load only numeric values. Remains all it updated as null.

Solution

To fix this changing the excel data type is one of the solution. In Excel Copy the column data and paste in different file. Delete that column and insert new column as Text datatype and paste that copied data in new column.

Now in ssis package delete and recreate the Excel source and destination table change the column data type as varchar.

This will work.

Can't use WAMP , port 80 is used by IIS 7.5

I don't recommend changing apaches port itself, because it will need you remember changed port. Its also headache to tell your co-developers about port change.

Go to windows features(By searching turn on or off windows features) -> Find Internet information services(IIS) and uncheck if it checked. Please make a note when you disable it FTP server/ client will not work.(incase you are using it, change httpd.conf as giovannipds 's answer) -> If still port is not free, then change skype port through skype settings.

thanks, enter image description here

Cannot catch toolbar home button click event

I changed the DrawerLayout a bit to get the events and be able to consume and event, such as if you want to use the actionToggle as back if you are in detail view:

public class ListenableDrawerLayout extends DrawerLayout {

    private OnToggleButtonClickedListener mOnToggleButtonClickedListener;
    private boolean mManualCall;

    public ListenableDrawerLayout(Context context) {
        super(context);
    }

    public ListenableDrawerLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ListenableDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * Sets the listener for the toggle button
     *
     * @param mOnToggleButtonClickedListener
     */
    public void setOnToggleButtonClickedListener(OnToggleButtonClickedListener mOnToggleButtonClickedListener) {
        this.mOnToggleButtonClickedListener = mOnToggleButtonClickedListener;
    }

    /**
     * Opens the navigation drawer manually from code<br>
     * <b>NOTE: </b>Use this function instead of the normal openDrawer method
     *
     * @param drawerView
     */
    public void openDrawerManual(View drawerView) {
        mManualCall = true;
        openDrawer(drawerView);
    }

    /**
     * Closes the navigation drawer manually from code<br>
     * <b>NOTE: </b>Use this function instead of the normal closeDrawer method
     *
     * @param drawerView
     */
    public void closeDrawerManual(View drawerView) {
        mManualCall = true;
        closeDrawer(drawerView);
    }


    @Override
    public void openDrawer(View drawerView) {

        // Check for listener and for not manual open
        if (!mManualCall && mOnToggleButtonClickedListener != null) {

            // Notify the listener and behave on its reaction
            if (mOnToggleButtonClickedListener.toggleOpenDrawer()) {
                return;
            }

        }
        // Manual call done
        mManualCall = false;

        // Let the drawer layout to its stuff
        super.openDrawer(drawerView);
    }

    @Override
    public void closeDrawer(View drawerView) {

        // Check for listener and for not manual close
        if (!mManualCall && mOnToggleButtonClickedListener != null) {

            // Notify the listener and behave on its reaction
            if (mOnToggleButtonClickedListener.toggleCloseDrawer()) {
                return;
            }

        }
        // Manual call done
        mManualCall = false;

        // Let the drawer layout to its stuff
        super.closeDrawer(drawerView);
    }

    /**
     * Interface for toggle button callbacks
     */
    public static interface OnToggleButtonClickedListener {

        /**
         * The ActionBarDrawerToggle has been pressed in order to open the drawer
         *
         * @return true if we want to consume the event, false if we want the normal behaviour
         */
        public boolean toggleOpenDrawer();

        /**
         * The ActionBarDrawerToggle has been pressed in order to close the drawer
         *
         * @return true if we want to consume the event, false if we want the normal behaviour
         */
        public boolean toggleCloseDrawer();
    }

}

Reload chart data via JSON with Highcharts

Correct answer is:

$.each(lines, function(lineNo, line) {
                    var items = line.split(',');
                    var data = {};
                    $.each(items, function(itemNo, item) {
                        if (itemNo === 0) {
                            data.name = item;
                        } else {
                            data.y = parseFloat(item);
                        }
                    });
                    options.series[0].data.push(data);
                    data = {};
                });

You need to flush the 'data' array.

data = {};

Is unsigned integer subtraction defined behavior?

Well, the first interpretation is correct. However, your reasoning about the "signed semantics" in this context is wrong.

Again, your first interpretation is correct. Unsigned arithmetic follow the rules of modulo arithmetic, meaning that 0x0000 - 0x0001 evaluates to 0xFFFF for 32-bit unsigned types.

However, the second interpretation (the one based on "signed semantics") is also required to produce the same result. I.e. even if you evaluate 0 - 1 in the domain of signed type and obtain -1 as the intermediate result, this -1 is still required to produce 0xFFFF when later it gets converted to unsigned type. Even if some platform uses an exotic representation for signed integers (1's complement, signed magnitude), this platform is still required to apply rules of modulo arithmetic when converting signed integer values to unsigned ones.

For example, this evaluation

signed int a = 0, b = 1;
unsigned int c = a - b;

is still guaranteed to produce UINT_MAX in c, even if the platform is using an exotic representation for signed integers.

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

Well my client side (a cshtml file) was using DataTables to display a grid (now using Infragistics control which are great). And once the user clicked on the row, I captured the row event and the date associated with that record in order to go back to the server and make additional server-side requests for trades, etc. And no - I DID NOT stringify it...

The DataTables def started as this (leaving lots of stuff out), and the click event is seen below where I PUSH onto my Json object :

    oTablePf = $('#pftable').dataTable({         // INIT CODE
             "aaData": PfJsonData,
             'aoColumnDefs': [                     
                { "sTitle": "Pf Id", "aTargets": [0] },
                { "sClass": "**td_nodedate**", "aTargets": [3] }
              ]
              });

   $("#pftable").delegate("tbody tr", "click", function (event) {   // ROW CLICK EVT!! 

        var rownum = $(this).index(); 
        var thisPfId = $(this).find('.td_pfid').text();  // Find Port Id and Node Date
        var thisDate = $(this).find('.td_nodedate').text();

         //INIT JSON DATA
        var nodeDatesJson = {
            "nodedatelist":[]
        };

         // omitting some code here...
         var dateArry = thisDate.split("/");
         var nodeDate = dateArry[2] + "-" + dateArry[0] + "-" + dateArry[1];

         nodeDatesJson.nodedatelist.push({ nodedate: nodeDate });

           getTradeContribs(thisPfId, nodeDatesJson);     // GET TRADE CONTRIBUTIONS 
    });

Where do I find old versions of Android NDK?

Looks like simply putting the link like this

http://dl.google.com/android/ndk/android-ndk-r7c-windows.zip

on the address bar of your browser

The revision names (r7c, r8c etc.) could be found from the ndk download page

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

make clean removes any intermediate or output files from your source / build tree. However, it only affects the source / build tree; it does not touch the rest of the filesystem and so will not remove previously installed software.

If you're lucky, running make uninstall will work. It's up to the library's authors to provide that, however; some authors provide an uninstall target, others don't.

If you're not lucky, you'll have to manually uninstall it. Running make -n install can be helpful, since it will show the steps that the software would take to install itself but won't actually do anything. You can then manually reverse those steps.

Show a number to two decimal places

If you want to use two decimal digits in your entire project, you can define:

bcscale(2);

Then the following function will produce your desired result:

$myvalue = 10.165445;
echo bcadd(0, $myvalue);
// result=10.11

But if you don't use the bcscale function, you need to write the code as follows to get your desired result.

$myvalue = 10.165445;
echo bcadd(0, $myvalue, 2);
// result=10.11

To know more

PHP validation/regex for URL

I used this on a few projects, I don't believe I've run into issues, but I'm sure it's not exhaustive:

$text = preg_replace(
  '#((https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i',
  "'<a href=\"$1\" target=\"_blank\">$3</a>$4'",
  $text
);

Most of the random junk at the end is to deal with situations like http://domain.com. in a sentence (to avoid matching the trailing period). I'm sure it could be cleaned up but since it worked. I've more or less just copied it over from project to project.

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

Eclipse Intellisense?

Tony is a pure genius. However to achieve even better auto-completion try setting the triggers to this:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz =.(!+-*/~,[{@#$%^&

(specifically aranged in order of usage for faster performance :)

How to determine previous page URL in Angular?

All the Above ANSWER will be loads URL multiple times. If user visited any other component also, these code will loads.

So better to use, Service creating concept. https://community.wia.io/d/22-access-the-previous-route-in-your-angular-5-app

This will works well in all versions of Angular. (please Make sure to add it to the providers array in your app.module file! )

How to compress a String in Java?

If you know that your strings are mostly ASCII you could convert them to UTF-8.

byte[] bytes = string.getBytes("UTF-8");

This may reduce the memory size by about 50%. However, you will get a byte array out and not a string. If you are writing it to a file though, that should not be a problem.

To convert back to a String:

private final Charset UTF8_CHARSET = Charset.forName("UTF-8");
...
String s = new String(bytes, UTF8_CHARSET);

How to call javascript from a href?

Not sure why this worked for me while nothing else did but just in case anyone else is still looking...

In between head tags:

<script>
     function myFunction() {
           script code
     }
</script>

Then for the < a > tag:

<a href='' onclick='myFunction()' > Call Function </a>

Remove the first character of a string

Your problem seems unclear. You say you want to remove "a character from a certain position" then go on to say you want to remove a particular character.

If you only need to remove the first character you would do:

s = ":dfa:sif:e"
fixed = s[1:]

If you want to remove a character at a particular position, you would do:

s = ":dfa:sif:e"
fixed = s[0:pos]+s[pos+1:]

If you need to remove a particular character, say ':', the first time it is encountered in a string then you would do:

s = ":dfa:sif:e"
fixed = ''.join(s.split(':', 1))

How to send email from Terminal?

in the terminal on your mac os or linux os type this code

mail -s (subject) (receiversEmailAddress)  <<< "how are you?"

for an example try this

mail -s "hi" [email protected] <<< "how are you?"<br>

How can I check that JButton is pressed? If the isEnable() is not work?

JButton has a model which answers these question:

  • isArmed(),
  • isPressed(),
  • isRollOVer()

etc. Hence you can ask the model for the answer you are seeking:

     if(jButton1.getModel().isPressed())
        System.out.println("the button is pressed");

How can I escape double quotes in XML attributes values?

A double quote character (") can be escaped as &quot;, but here's the rest of the story...

Double quote character must be escaped in this context:

  • In XML attributes delimited by double quotes:

    <EscapeNeeded name="Pete &quot;Maverick&quot; Mitchell"/>
    

Double quote character need not be escaped in most contexts:

  • In XML textual content:

    <NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
    
  • In XML attributes delimited by single quotes ('):

    <NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
    

    Similarly, (') require no escaping if (") are used for the attribute value delimiters:

    <NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
    

See also

Java String declaration

String s1 = "Welcome"; // Does not create a new instance  
String s2 = new String("Welcome"); // Creates two objects and one reference variable  

What does the arrow operator, '->', do in Java?

It's a lambda expression.

It means that, from the listOfCars, arg0 is one of the items of that list. With that item he is going to do, hence the ->, whatever is inside of the brackets.

In this example, he's going to return a list of cars that fit the condition

Car.SEDAN == ((Car)arg0).getStyle();

Collapsing Sidebar with Bootstrap

Bootstrap 3

Yes, it's possible. This "off-canvas" example should help to get you started.

https://codeply.com/p/esYgHWB2zJ

Basically you need to wrap the layout in an outer div, and use media queries to toggle the layout on smaller screens.

/* collapsed sidebar styles */
@media screen and (max-width: 767px) {
  .row-offcanvas {
    position: relative;
    -webkit-transition: all 0.25s ease-out;
    -moz-transition: all 0.25s ease-out;
    transition: all 0.25s ease-out;
  }
  .row-offcanvas-right
  .sidebar-offcanvas {
    right: -41.6%;
  }

  .row-offcanvas-left
  .sidebar-offcanvas {
    left: -41.6%;
  }
  .row-offcanvas-right.active {
    right: 41.6%;
  }
  .row-offcanvas-left.active {
    left: 41.6%;
  }
  .sidebar-offcanvas {
    position: absolute;
    top: 0;
    width: 41.6%;
  }
  #sidebar {
    padding-top:0;
  }
}

Also, there are several more Bootstrap sidebar examples here


Bootstrap 4

Create a responsive navbar sidebar "drawer" in Bootstrap 4?

Get current index from foreach loop

Use Enumerable.Select<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, Int32, TResult>)

list = list.Cast<object>().Select( (v, i) => new {Value= v, Index = i});

foreach(var row in list)
{
    bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row.Value)).IsChecked;
    row.Index ...
}

What's the difference between ng-model and ng-bind

ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable.

\n or \n in php echo not print

\n must be in double quotes!

 echo '<p>' . $unit1 . "</p>\n";

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

I had to #include <tchar.h> in my windows service application. I left it as a windows console type subsystem. The "Character Set" was set to UNICODE.

Why do we check up to the square root of a prime number to determine if it is prime?

Let's say m = sqrt(n) then m × m = n. Now if n is not a prime then n can be written as n = a × b, so m × m = a × b. Notice that m is a real number whereas n, a and b are natural numbers.

Now there can be 3 cases:

  1. a > m ? b < m
  2. a = m ? b = m
  3. a < m ? b > m

In all 3 cases, min(a, b) = m. Hence if we search till m, we are bound to find at least one factor of n, which is enough to show that n is not prime.

How to clear or stop timeInterval in angularjs?

You can store the promise returned by the interval and use $interval.cancel() to that promise, which cancels the interval of that promise. To delegate the starting and stopping of the interval, you can create start() and stop() functions whenever you want to stop and start them again from a specific event. I have created a snippet below showing the basics of starting and stopping an interval, by implementing it in view through the use of events (e.g. ng-click) and in the controller.

_x000D_
_x000D_
angular.module('app', [])_x000D_
_x000D_
  .controller('ItemController', function($scope, $interval) {_x000D_
  _x000D_
    // store the interval promise in this variable_x000D_
    var promise;_x000D_
  _x000D_
    // simulated items array_x000D_
    $scope.items = [];_x000D_
    _x000D_
    // starts the interval_x000D_
    $scope.start = function() {_x000D_
      // stops any running interval to avoid two intervals running at the same time_x000D_
      $scope.stop(); _x000D_
      _x000D_
      // store the interval promise_x000D_
      promise = $interval(setRandomizedCollection, 1000);_x000D_
    };_x000D_
  _x000D_
    // stops the interval_x000D_
    $scope.stop = function() {_x000D_
      $interval.cancel(promise);_x000D_
    };_x000D_
  _x000D_
    // starting the interval by default_x000D_
    $scope.start();_x000D_
 _x000D_
    // stops the interval when the scope is destroyed,_x000D_
    // this usually happens when a route is changed and _x000D_
    // the ItemsController $scope gets destroyed. The_x000D_
    // destruction of the ItemsController scope does not_x000D_
    // guarantee the stopping of any intervals, you must_x000D_
    // be responsible for stopping it when the scope is_x000D_
    // is destroyed._x000D_
    $scope.$on('$destroy', function() {_x000D_
      $scope.stop();_x000D_
    });_x000D_
            _x000D_
    function setRandomizedCollection() {_x000D_
      // items to randomize 1 - 11_x000D_
      var randomItems = parseInt(Math.random() * 10 + 1); _x000D_
        _x000D_
      // empties the items array_x000D_
      $scope.items.length = 0; _x000D_
      _x000D_
      // loop through random N times_x000D_
      while(randomItems--) {_x000D_
        _x000D_
        // push random number from 1 - 10000 to $scope.items_x000D_
        $scope.items.push(parseInt(Math.random() * 10000 + 1)); _x000D_
      }_x000D_
    }_x000D_
  _x000D_
  });
_x000D_
<div ng-app="app" ng-controller="ItemController">_x000D_
  _x000D_
  <!-- Event trigger to start the interval -->_x000D_
  <button type="button" ng-click="start()">Start Interval</button>_x000D_
  _x000D_
  <!-- Event trigger to stop the interval -->_x000D_
  <button type="button" ng-click="stop()">Stop Interval</button>_x000D_
  _x000D_
  <!-- display all the random items -->_x000D_
  <ul>_x000D_
    <li ng-repeat="item in items track by $index" ng-bind="item"></li>_x000D_
  </ul>_x000D_
  <!-- end of display -->_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
_x000D_
_x000D_
_x000D_

How to change Android usb connect mode to charge only?

To change the connect mode selection try Settings -> Wireless & Networks -> USB Connection. You can shoose to Charging, Mass Storage, Tethered, and ask on connection.

ReferenceError: event is not defined error in Firefox

You're declaring (some of) your event handlers incorrectly:

$('.menuOption').click(function( event ){ // <---- "event" parameter here

    event.preventDefault();
    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();


});

You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.

edit — to clarify: you have to provide some parameter name; using event makes it clear what you intend, but you can call it e or cupcake or anything else.

Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.

Python Accessing Nested JSON Data

I'm using this lib to access nested dict keys

https://github.com/mewwts/addict

 import requests
 from addict import Dict
 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = Dict(r.json())

 print j.state
 print j.places[1]['post code']  # only work with keys without '-', space, or starting with number 

How to start and stop android service from a adb shell?

Starting a service:

adb shell am startservice ...

start a Service. Options are: --user | current: Specify which user to run as; if not specified then run as the current user.

Stopping a service:

adb shell am stopservice ... 

stop a Service. Options are: --user | current: Specify which user to run as; if not specified then run as the current user.

List all files and directories in a directory + subdirectories

using System.IO;
using System.Text;
string[] filePaths = Directory.GetFiles(@"path", "*.*", SearchOption.AllDirectories);

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

try using the Date property on the DateTime Object...

if(dtOne.Date == dtTwo.Date)
    ....

Which @NotNull Java annotation should I use?

While waiting for this to be sorted out upstream (Java 8?), you could also just define your own project-local @NotNull and @Nullable annotations. This can be useful also in case you're working with Java SE, where javax.validation.constraints isn't available by default.

import java.lang.annotation.*;

/**
 * Designates that a field, return value, argument, or variable is
 * guaranteed to be non-null.
 */
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE})
@Documented
@Retention(RetentionPolicy.CLASS)
public @interface NotNull {}

/**
 * Designates that a field, return value, argument, or variable may be null.
 */
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE})
@Documented
@Retention(RetentionPolicy.CLASS)
public @interface Nullable {}

This would admittedly largely be for decorative or future-proofing purposes, since the above obviously doesn't in and of itself add any support for the static analysis of these annotations.

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

Try this. I hope it helps

$options = [
    'cache_wsdl'     => WSDL_CACHE_NONE,
    'trace'          => 1,
    'stream_context' => stream_context_create(
        [
            'ssl' => [
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'allow_self_signed' => true
            ]
        ]
    )
];

$client = new SoapClient($url, $options);

How to throw a C++ exception

Simple:

#include <stdexcept>

int compare( int a, int b ) {
    if ( a < 0 || b < 0 ) {
        throw std::invalid_argument( "received negative value" );
    }
}

The Standard Library comes with a nice collection of built-in exception objects you can throw. Keep in mind that you should always throw by value and catch by reference:

try {
    compare( -1, 3 );
}
catch( const std::invalid_argument& e ) {
    // do stuff with exception... 
}

You can have multiple catch() statements after each try, so you can handle different exception types separately if you want.

You can also re-throw exceptions:

catch( const std::invalid_argument& e ) {
    // do something

    // let someone higher up the call stack handle it if they want
    throw;
}

And to catch exceptions regardless of type:

catch( ... ) { };

How can I add new keys to a dictionary?

This popular question addresses functional methods of merging dictionaries a and b.

Here are some of the more straightforward methods (tested in Python 3)...

c = dict( a, **b ) ## see also https://stackoverflow.com/q/2255878
c = dict( list(a.items()) + list(b.items()) )
c = dict( i for d in [a,b] for i in d.items() )

Note: The first method above only works if the keys in b are strings.

To add or modify a single element, the b dictionary would contain only that one element...

c = dict( a, **{'d':'dog'} ) ## returns a dictionary based on 'a'

This is equivalent to...

def functional_dict_add( dictionary, key, value ):
   temp = dictionary.copy()
   temp[key] = value
   return temp

c = functional_dict_add( a, 'd', 'dog' )

Centering in CSS Grid

This answer has two main sections:

  1. Understanding how alignment works in CSS Grid.
  2. Six methods for centering in CSS Grid.

If you're only interested in the solutions, skip the first section.


The Structure and Scope of Grid layout

To fully understand how centering works in a grid container, it's important to first understand the structure and scope of grid layout.

The HTML structure of a grid container has three levels:

  • the container
  • the item
  • the content

Each of these levels is independent from the others, in terms of applying grid properties.

The scope of a grid container is limited to a parent-child relationship.

This means that a grid container is always the parent and a grid item is always the child. Grid properties work only within this relationship.

Descendants of a grid container beyond the children are not part of grid layout and will not accept grid properties. (At least not until the subgrid feature has been implemented, which will allow descendants of grid items to respect the lines of the primary container.)

Here's an example of the structure and scope concepts described above.

Imagine a tic-tac-toe-like grid.

article {
  display: inline-grid;
  grid-template-rows: 100px 100px 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 3px;
}

enter image description here

You want the X's and O's centered in each cell.

So you apply the centering at the container level:

article {
  display: inline-grid;
  grid-template-rows: 100px 100px 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 3px;
  justify-items: center;
}

But because of the structure and scope of grid layout, justify-items on the container centers the grid items, not the content (at least not directly).

enter image description here

_x000D_
_x000D_
article {_x000D_
  display: inline-grid;_x000D_
  grid-template-rows: 100px 100px 100px;_x000D_
  grid-template-columns: 100px 100px 100px;_x000D_
  grid-gap: 3px;_x000D_
  justify-items: center;_x000D_
}_x000D_
_x000D_
section {_x000D_
    border: 2px solid black;_x000D_
    font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
</article>
_x000D_
_x000D_
_x000D_

Same problem with align-items: The content may be centered as a by-product, but you've lost the layout design.

article {
  display: inline-grid;
  grid-template-rows: 100px 100px 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 3px;
  justify-items: center;
  align-items: center;
}

enter image description here

_x000D_
_x000D_
article {_x000D_
  display: inline-grid;_x000D_
  grid-template-rows: 100px 100px 100px;_x000D_
  grid-template-columns: 100px 100px 100px;_x000D_
  grid-gap: 3px;_x000D_
  justify-items: center;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
section {_x000D_
    border: 2px solid black;_x000D_
    font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
</article>
_x000D_
_x000D_
_x000D_

To center the content you need to take a different approach. Referring again to the structure and scope of grid layout, you need to treat the grid item as the parent and the content as the child.

article {
  display: inline-grid;
  grid-template-rows: 100px 100px 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 3px;
}

section {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 2px solid black;
  font-size: 3em;
}

enter image description here

_x000D_
_x000D_
article {_x000D_
  display: inline-grid;_x000D_
  grid-template-rows: 100px 100px 100px;_x000D_
  grid-template-columns: 100px 100px 100px;_x000D_
  grid-gap: 3px;_x000D_
}_x000D_
_x000D_
section {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  border: 2px solid black;_x000D_
  font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
  <section>X</section>_x000D_
  <section>O</section>_x000D_
  <section>X</section>_x000D_
  <section>O</section>_x000D_
  <section>X</section>_x000D_
  <section>O</section>_x000D_
  <section>X</section>_x000D_
  <section>O</section>_x000D_
  <section>X</section>_x000D_
</article>
_x000D_
_x000D_
_x000D_

jsFiddle demo


Six Methods for Centering in CSS Grid

There are multiple methods for centering grid items and their content.

Here's a basic 2x2 grid:

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_

Flexbox

For a simple and easy way to center the content of grid items use flexbox.

More specifically, make the grid item into a flex container.

There is no conflict, spec violation or other problem with this method. It's clean and valid.

grid-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
  display: flex;            /* new */_x000D_
  align-items: center;      /* new */_x000D_
  justify-content: center;  /* new */_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_

See this post for a complete explanation:


Grid Layout

In the same way that a flex item can also be a flex container, a grid item can also be a grid container. This solution is similar to the flexbox solution above, except centering is done with grid, not flex, properties.

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
  display: grid;            /* new */_x000D_
  align-items: center;      /* new */_x000D_
  justify-items: center;    /* new */_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_


auto margins

Use margin: auto to vertically and horizontally center grid items.

grid-item {
  margin: auto;
}

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
  margin: auto;_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_

To center the content of grid items you need to make the item into a grid (or flex) container, wrap anonymous items in their own elements (since they cannot be directly targeted by CSS), and apply the margins to the new elements.

grid-item {
  display: flex;
}

span, img {
  margin: auto;
}

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
span, img {_x000D_
  margin: auto;_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item><span>this text should be centered</span></grid-item>_x000D_
  <grid-item><span>this text should be centered</span></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_


Box Alignment Properties

When considering using the following properties to align grid items, read the section on auto margins above.

  • align-items
  • justify-items
  • align-self
  • justify-self

https://www.w3.org/TR/css-align-3/#property-index


text-align: center

To center content horizontally in a grid item, you can use the text-align property.

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
  text-align: center;  /* new */_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_

Note that for vertical centering, vertical-align: middle will not work.

This is because the vertical-align property applies only to inline and table-cell containers.

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
  text-align: center;     /* <--- works */_x000D_
  vertical-align: middle; /* <--- fails */_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_

One might say that display: inline-grid establishes an inline-level container, and that would be true. So why doesn't vertical-align work in grid items?

The reason is that in a grid formatting context, items are treated as block-level elements.

6.1. Grid Item Display

The display value of a grid item is blockified: if the specified display of an in-flow child of an element generating a grid container is an inline-level value, it computes to its block-level equivalent.

In a block formatting context, something the vertical-align property was originally designed for, the browser doesn't expect to find a block-level element in an inline-level container. That's invalid HTML.


CSS Positioning

Lastly, there's a general CSS centering solution that also works in Grid: absolute positioning

This is a good method for centering objects that need to be removed from the document flow. For example, if you want to:

Simply set position: absolute on the element to be centered, and position: relative on the ancestor that will serve as the containing block (it's usually the parent). Something like this:

grid-item {
  position: relative;
  text-align: center;
}

span {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
  position: relative;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
span, img {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  top: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item><span>this text should be centered</span></grid-item>_x000D_
  <grid-item><span>this text should be centered</span></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_

Here's a complete explanation for how this method works:

Here's the section on absolute positioning in the Grid spec:

Create space at the beginning of a UITextField

Swift 4, Xcode 9

I like Pheepster's answer, but how about we do it all from the extension, without requiring VC code or any subclassing:

import UIKit

@IBDesignable
extension UITextField {

    @IBInspectable var paddingLeftCustom: CGFloat {
        get {
            return leftView!.frame.size.width
        }
        set {
            let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
            leftView = paddingView
            leftViewMode = .always
        }
    }

    @IBInspectable var paddingRightCustom: CGFloat {
        get {
            return rightView!.frame.size.width
        }
        set {
            let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
            rightView = paddingView
            rightViewMode = .always     
        }
    }
}

How do I measure execution time of a command on the Windows command line?

There's also TimeMem (March 2012):

This is a Windows utility which executes a program and displays its execution time, memory usage, and IO statistics. It is similar in functionality to the Unix time utility.

How to add a new audio (not mixing) into a video using ffmpeg?

Replace audio

diagram of audio stream replacement

ffmpeg -i video.mp4 -i audio.wav -map 0:v -map 1:a -c:v copy -shortest output.mp4
  • The -map option allows you to manually select streams / tracks. See FFmpeg Wiki: Map for more info.
  • This example uses -c:v copy to stream copy (mux) the video. No re-encoding of the video occurs. Quality is preserved and the process is fast.
    • If your input audio format is compatible with the output format then change -c:v copy to -c copy to stream copy both the video and audio.
    • If you want to re-encode video and audio then remove -c:v copy / -c copy.
  • The -shortest option will make the output the same duration as the shortest input.

Add audio

diagram of audio stream addition

ffmpeg -i video.mkv -i audio.mp3 -map 0 -map 1:a -c:v copy -shortest output.mkv
  • The -map option allows you to manually select streams / tracks. See FFmpeg Wiki: Map for more info.
  • This example uses -c:v copy to stream copy (mux) the video. No re-encoding of the video occurs. Quality is preserved and the process is fast.
    • If your input audio format is compatible with the output format then change -c:v copy to -c copy to stream copy both the video and audio.
    • If you want to re-encode video and audio then remove -c:v copy / -c copy.
  • The -shortest option will make the output the same duration as the shortest input.

Mixing/combining two audio inputs into one

diagram of audio downmix

Use video from video.mkv. Mix audio from video.mkv and audio.m4a using the amerge filter:

ffmpeg -i video.mkv -i audio.m4a -filter_complex "[0:a][1:a]amerge=inputs=2[a]" -map 0:v -map "[a]" -c:v copy -ac 2 -shortest output.mkv

See FFmpeg Wiki: Audio Channels for more info.

Generate silent audio

You can use the anullsrc filter to make a silent audio stream. The filter allows you to choose the desired channel layout (mono, stereo, 5.1, etc) and the sample rate.

ffmpeg -i video.mp4 -f lavfi -i anullsrc=channel_layout=stereo:sample_rate=44100 \
-c:v copy -shortest output.mp4

Also see

How to get the previous page URL using JavaScript?

You want in page A to know the URL of page B?

Or to know in page B the URL of page A?

In Page B: document.referrer if set. As already shown here: How to get the previous URL in JavaScript?

In page A you would need to read a cookie or local/sessionStorage you set in page B, assuming the same domains

How do I get the n-th level parent of an element in jQuery?

Depends on your needs, if you know what parent your looking for you can use the .parents() selector.

E.G: http://jsfiddle.net/HenryGarle/Kyp5g/2/

<div id="One">
    <div id="Two">
        <div id="Three">
            <div id="Four">

            </div>
        </div>
    </div>
</div>


var top = $("#Four").parents("#One");

alert($(top).html());

Example using index:

//First parent - 2 levels up from #Four
// I.e Selects div#One
var topTwo = $("#Four").parents().eq(2);

alert($(topTwo ).html());

Should functions return null or an empty object?

You should be throwing an exception if it is an exceptional circumstance that you call that code with an invalid user ID. If it is NOT an exceptional circumstance, then what you are essentially doing is using a "getter" method to test whether a user exists or not. That is like trying to open a file to see if it exists or not (lets stick to c#/java here) instead of using the exists method, or trying to access dictionary elements and seeing if they exist by looking at the return value instead of using the "contains" method first.

Therefore, it is likely you are after an additional method such as "exists" to first check if there is such a user. Performance of exceptions is definitely not a reason to just not use them at all unless you have genuine performance issues.

How to maintain page scroll position after a jquery event is carried out?

$('html,body').animate({
  scrollTop: $('#answer-<%= @answer.id %>').offset().top - 50
}, 700);

HTTP Error 503, the service is unavailable

In our case, nothing was logged (other than the HTTP error log entry for the 503), but the Enabled Protocols value for the web application in IIS had a typo in it! Instead of http,https there was a period in-between the protocols: http.https

Getting an element from a Set

it looks like the proper object to use is the Interner from guava :

Provides equivalent behavior to String.intern() for other immutable types. Common implementations are available from the Interners class.

It also has a few very interesting levers, like concurrencyLevel, or the type of references used (it might be worth noting that it doesn't offer a SoftInterner which I could see as more useful than a WeakInterner).

Run class in Jar file

Use java -cp myjar.jar com.mypackage.myClass.

  1. If the class is not in a package then simply java -cp myjar.jar myClass.

  2. If you are not within the directory where myJar.jar is located, then you can do:

    1. On Unix or Linux platforms:

      java -cp /location_of_jar/myjar.jar com.mypackage.myClass

    2. On Windows:

      java -cp c:\location_of_jar\myjar.jar com.mypackage.myClass

Working with a List of Lists in Java

 public class TEst {

    public static void main(String[] args) {

        List<Integer> ls=new ArrayList<>();
        ls.add(1);
        ls.add(2);
        List<Integer> ls1=new ArrayList<>();
        ls1.add(3);
        ls1.add(4);
        List<List<Integer>> ls2=new ArrayList<>();
        ls2.add(ls);
        ls2.add(ls1);

        List<List<List<Integer>>> ls3=new ArrayList<>();
        ls3.add(ls2);


        methodRecursion(ls3);
    }

    private static void methodRecursion(List ls3) {
        for(Object ls4:ls3)
        {
             if(ls4 instanceof List)    
             {
                methodRecursion((List)ls4);
             }else {
                 System.out.print(ls4);
             }

        }
    }

}

How to write dynamic variable in Ansible playbook

my_var: the variable declared

VAR: the variable, whose value is to be checked

param_1, param_2: values of the variable VAR

value_1, value_2, value_3: the values to be assigned to my_var according to the values of my_var

my_var: "{{ 'value_1' if VAR == 'param_1' else 'value_2' if VAR == 'param_2' else 'value_3' }}"

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

Erik, You can just kill all the other node processes by

pkill -f node

and then restart your server again. It'll work just fine then.

bash: pip: command not found

Not sure why this wasnt mentioned before, but the only thing that worked for me (on my NVIDIA Xavier) was:

sudo apt-get install python3-pip

(or sudo apt-get install python-pip for python 2)

Does "\d" in regex mean a digit?

[0-9] is not always equivalent to \d. In python3, [0-9] matches only 0123456789 characters, while \d matches [0-9] and other digit characters, for example Eastern Arabic numerals ??????????.

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

You'll have to pass your arguments as reference types.

#First create the variables (note you have to set them to something)
$global:var1 = $null
$global:var2 = $null
$global:var3 = $null

#The type of the reference argument should be of type [REF]
function foo ($a, $b, [REF]$c)
{
    # add $a and $b and set the requested global variable to equal to it
    # Note how you modify the value.
    $c.Value = $a + $b
}

#You can then call it like this:
foo 1 2 [REF]$global:var3

Replace or delete certain characters from filenames of all files in a folder

Use PowerShell to do anything smarter for a DOS prompt. Here, I've shown how to batch rename all the files and directories in the current directory that contain spaces by replacing them with _ underscores.

Dir |
Rename-Item -NewName { $_.Name -replace " ","_" }

EDIT :
Optionally, the Where-Object command can be used to filter out ineligible objects for the successive cmdlet (command-let). The following are some examples to illustrate the flexibility it can afford you:

  • To skip any document files

    Dir |
    Where-Object { $_.Name -notmatch "\.(doc|xls|ppt)x?$" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    
  • To process only directories (pre-3.0 version)

    Dir |
    Where-Object { $_.Mode -match "^d" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    

    PowerShell v3.0 introduced new Dir flags. You can also use Dir -Directory there.

  • To skip any files already containing an underscore (or some other character)

    Dir |
    Where-Object { -not $_.Name.Contains("_") } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    

How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

so easy find the file "applicationHost.config" in Windows -> System32 ->inetsrv -> config 1. backup "applicationHost.config" to another filename 2. open file "applicationHost.config" clear data and save 3. open browser and call url internal website , finished.

replacing NA's with 0's in R dataframe

dataset <- matrix(sample(c(NA, 1:5), 25, replace = TRUE), 5);
data <- as.data.frame(dataset)
[,1] [,2] [,3] [,4] [,5] 
[1,]    2    3    5    5    4
[2,]    2    4    3    2    4
[3,]    2   NA   NA   NA    2
[4,]    2    3   NA    5    5
[5,]    2    3    2    2    3
data[is.na(data)] <- 0

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

I'm not familiar with python 3 yet, but it seems like urllib.request.urlopen().read() returns a byte object rather than string.

You might try to feed it into a StringIO object, or even do a str(response).

Concatenate a NumPy array to another NumPy array

Sven said it all, just be very cautious because of automatic type adjustments when append is called.

In [2]: import numpy as np

In [3]: a = np.array([1,2,3])

In [4]: b = np.array([1.,2.,3.])

In [5]: c = np.array(['a','b','c'])

In [6]: np.append(a,b)
Out[6]: array([ 1.,  2.,  3.,  1.,  2.,  3.])

In [7]: a.dtype
Out[7]: dtype('int64')

In [8]: np.append(a,c)
Out[8]: 
array(['1', '2', '3', 'a', 'b', 'c'], 
      dtype='|S1')

As you see based on the contents the dtype went from int64 to float32, and then to S1

Running vbscript from batch file

Batch files are processed row by row and terminate whenever you call an executable directly.
- To make the batch file wait for the process to terminate and continue, put call in front of it.
- To make the batch file continue without waiting, put start "" in front of it.

I recommend using this single line script to accomplish your goal:

@call cscript "%~dp0necdaily.vbs"

(because this is a single line, you can use @ instead of @echo off)

If you believe your script can only be called from the SysWOW64 versions of cmd.exe, you might try:

@%WINDIR%\SysWOW64\cmd.exe /c call cscript "%~dp0necdaily.vbs"

If you need the window to remain, you can replace /c with /k

Hidden property of a button in HTML

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>

function showButtons () { $('#b1, #b2, #b3').show(); }

</script>
<style type="text/css">
#b1, #b2, #b3 {
display: none;
}

</style>
</head>
<body>

<a href="#" onclick="showButtons();">Show me the money!</a>

<input type="submit" id="b1" value="B1" />
<input type="submit" id="b2" value="B2"/>
<input type="submit" id="b3" value="B3" />

</body>
</html>

Add a string of text into an input field when user clicks a button

Here it is: http://jsfiddle.net/tQyvp/

Here's the code if you don't like going to jsfiddle:

html

<input id="myinputfield" value="This is some text" type="button">?

Javascript:

$('body').on('click', '#myinputfield', function(){
    var textField = $('#myinputfield');
    textField.val(textField.val()+' after clicking')       
});?

Find nearest value in numpy array

For 2d array, to determine the i, j position of nearest element:

import numpy as np
def find_nearest(a, a0):
    idx = (np.abs(a - a0)).argmin()
    w = a.shape[1]
    i = idx // w
    j = idx - i * w
    return a[i,j], i, j

CSS fixed width in a span

You can do it using a table, but it is not pure CSS.

<style>
ul{
    text-indent: 40px;
}

li{
    list-style-type: none;
    padding: 0;
}

span{
    color: #ff0000;
    position: relative;
    left: -40px;
}
</style>


<ul>
<span></span><li>The lazy dog.</li>
<span>AND</span><li>The lazy cat.</li>
<span>OR</span><li>The active goldfish.</li>
</ul>

Note that it doesn't display exactly like you want, because it switches line on each option. However, I hope that this helps you come closer to the answer.

How do I convert from int to String?

It depends on how you want to use your String. This can help:

String total =  Integer.toString(123) + Double.toString(456.789);

Use of #pragma in C

Putting #pragma once at the top of your header file will ensure that it is only included once. Note that #pragma once is not standard C99, but supported by most modern compilers.

An alternative is to use include guards (e.g. #ifndef MY_FILE #define MY_FILE ... #endif /* MY_FILE */)

How to create a library project in Android Studio and an application project that uses the library project

You can add a new module to any application as Blundell says on his answer and then reference it from any other application.

If you want to move the module to any place on your computer just move the module folder (modules are completely independent), then you will have to reference the module.

To reference this module you should:

  • On build.gradle file of your app add:

    dependencies {
    ...
    compile project(':myandroidlib')
    }
    
  • On settings.gradle file add the following:

     include ':app', ':myandroidlib'
     project(':myandroidlib').projectDir = new File(PATH_TO_YOUR_MODULE)
    

Undefined reference to `pow' and `floor'

In regards to the answer provided by Fuzzy:

I actually had to do something slightly different.

Project -> Properties -> C/C++ Build -> Settings -> GCC C Linker -> Libraries

Click the little green add icon, type m and hit ok. Everything in this window automatically has -l applied to it since it is a library.

How to suppress scientific notation when printing float values?

'%f' % (x/y)

but you need to manage precision yourself. e.g.,

'%f' % (1/10**8)

will display zeros only.
details are in the docs

Or for Python 3 the equivalent old formatting or the newer style formatting

Is there a max array length limit in C++?

One thing I don't think has been mentioned in the previous answers.

I'm always sensing a "bad smell" in the refactoring sense when people are using such things in their design.

That's a huge array and possibly not the best way to represent your data both from an efficiency point of view and a performance point of view.

cheers,

Rob

How do I put my website's logo to be the icon image in browser tabs?

It is called 'favicon' and you need to add below code to the header section of your website.

Simply add this to the <head> section.

<link rel="icon" href="/your_path_to_image/favicon.jpg">

Java: Clear the console

Create a method in your class like this: [as @Holger said here.]

public static void clrscr(){
    //Clears Screen in java
    try {
        if (System.getProperty("os.name").contains("Windows"))
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
        else
            Runtime.getRuntime().exec("clear");
    } catch (IOException | InterruptedException ex) {}
}

This works for windows at least, I have not checked for Linux so far. If anyone checks it for Linux please let me know if it works (or not).

As an alternate method is to write this code in clrscr():

for(int i = 0; i < 80*300; i++) // Default Height of cmd is 300 and Default width is 80
    System.out.print("\b"); // Prints a backspace

I will not recommend you to use this method.

Convert char* to string C++

There seems to be a few details left out of your explanation, but I will do my best...

If these are NUL-terminated strings or the memory is pre-zeroed, you can just iterate down the length of the memory segment until you hit a NUL (0) character or the maximum length (whichever comes first). Use the string constructor, passing the buffer and the size determined in the previous step.

string retrieveString( char* buf, int max ) {

    size_t len = 0;
    while( (len < max) && (buf[ len ] != '\0') ) {
        len++;
    }

    return string( buf, len );

}

If the above is not the case, I'm not sure how you determine where a string ends.

How do I implement __getattribute__ without an infinite recursion error?

You get a recursion error because your attempt to access the self.__dict__ attribute inside __getattribute__ invokes your __getattribute__ again. If you use object's __getattribute__ instead, it works:

class D(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self,name):
        if name=='test':
            return 0.
        else:
            return object.__getattribute__(self, name)

This works because object (in this example) is the base class. By calling the base version of __getattribute__ you avoid the recursive hell you were in before.

Ipython output with code in foo.py:

In [1]: from foo import *

In [2]: d = D()

In [3]: d.test
Out[3]: 0.0

In [4]: d.test2
Out[4]: 21

Update:

There's something in the section titled More attribute access for new-style classes in the current documentation, where they recommend doing exactly this to avoid the infinite recursion.

How to check if a string array contains one string in JavaScript?

There is an indexOf method that all arrays have (except Internet Explorer 8 and below) that will return the index of an element in the array, or -1 if it's not in the array:

if (yourArray.indexOf("someString") > -1) {
    //In the array!
} else {
    //Not in the array
}

If you need to support old IE browsers, you can polyfill this method using the code in the MDN article.

Finding the number of days between two dates

Looking all answers I compose universal function what working on all PHP versions.

if(!function_exists('date_between')) :
    function date_between($date_start, $date_end)
    {
        if(!$date_start || !$date_end) return 0;

        if( class_exists('DateTime') )
        {
            $date_start = new DateTime( $date_start );
            $date_end   = new DateTime( $date_end );
            return $date_end->diff($date_start)->format('%a');
        }
        else
        {           
            return abs( round( ( strtotime($date_start) - strtotime($date_end) ) / 86400 ) );
        }
    }
endif;

In the general, I use 'DateTime' to find days between 2 dates. But if in the some reason, some server setup not have 'DateTime' enabled, it will use simple (but not safe) calculation with 'strtotime()'.

LINQ to read XML

Here are a couple of complete working examples that build on the @bendewey & @dommer examples. I needed to tweak each one a bit to get it to work, but in case another LINQ noob is looking for working examples, here you go:

//bendewey's example using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ1
{
    static void Main( )
    {
        //Load xml
        XDocument xdoc = XDocument.Load(@"c:\\data.xml"); //you'll have to edit your path

        //Run query
        var lv1s = from lv1 in xdoc.Descendants("level1")
           select new 
           { 
               Header = lv1.Attribute("name").Value,
               Children = lv1.Descendants("level2")
            };

        StringBuilder result = new StringBuilder(); //had to add this to make the result work
        //Loop through results
        foreach (var lv1 in lv1s)
        {
            result.AppendLine("  " + lv1.Header);
            foreach(var lv2 in lv1.Children)
            result.AppendLine("    " + lv2.Attribute("name").Value);
        }
        Console.WriteLine(result.ToString()); //added this so you could see the output on the console
    }
}

And next:

//Dommer's example, using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ
{
static void Main( )
    {
        XElement rootElement = XElement.Load(@"c:\\data.xml"); //you'll have to edit your path
        Console.WriteLine(GetOutline(0, rootElement));  
    }

static private string GetOutline(int indentLevel, XElement element)
    {
        StringBuilder result = new StringBuilder();
        if (element.Attribute("name") != null)
        {
            result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
        }
        foreach (XElement childElement in element.Elements())
        {
            result.Append(GetOutline(indentLevel + 1, childElement));
        }
        return result.ToString();
    }
}

These both compile & work in VS2010 using csc.exe version 4.0.30319.1 and give the exact same output. Hopefully these help someone else who's looking for working examples of code.

EDIT: added @eglasius' example as well since it became useful to me:

//@eglasius example, still using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ2
{
    static void Main( )
    {
        StringBuilder result = new StringBuilder(); //needed for result below
        XDocument xdoc = XDocument.Load(@"c:\\deg\\data.xml"); //you'll have to edit your path
        var lv1s = xdoc.Root.Descendants("level1"); 
        var lvs = lv1s.SelectMany(l=>
             new string[]{ l.Attribute("name").Value }
             .Union(
                 l.Descendants("level2")
                 .Select(l2=>"   " + l2.Attribute("name").Value)
              )
            );
        foreach (var lv in lvs)
        {
           result.AppendLine(lv);
        }
        Console.WriteLine(result);//added this so you could see the result
    }
}

LEFT function in Oracle

LEFT is not a function in Oracle. This probably came from someone familiar with SQL Server:

Returns the left part of a character string with the specified number of characters.

-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse  
LEFT ( character_expression , integer_expression )  

What is the best alternative IDE to Visual Studio

I still like Source Insight a lot, but I'm hesitant to recommend it anymore as I'm not sure anybody's still maintaining it. They released a very minor update back in March but haven't had a major release in years. And there seems to be no web community presence. It's a shame because I still like its auto-completion-friendly file open and symbol browsing panels (as well as syntax formatting) better than anything else I've ever used.

.NET unique object identifier

If you are writing a module in your own code for a specific usage, majkinetor's method MIGHT have worked. But there are some problems.

First, the official document does NOT guarantee that the GetHashCode() returns an unique identifier (see Object.GetHashCode Method ()):

You should not assume that equal hash codes imply object equality.

Second, assume you have a very small amount of objects so that GetHashCode() will work in most cases, this method can be overridden by some types.
For example, you are using some class C and it overrides GetHashCode() to always return 0. Then every object of C will get the same hash code. Unfortunately, Dictionary, HashTable and some other associative containers will make use this method:

A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary<TKey, TValue> class, the Hashtable class, or a type derived from the DictionaryBase class. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.

So, this approach has great limitations.

And even more, what if you want to build a general purpose library? Not only are you not able to modify the source code of the used classes, but their behavior is also unpredictable.

I appreciate that Jon and Simon have posted their answers, and I will post a code example and a suggestion on performance below.

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Collections.Generic;


namespace ObjectSet
{
    public interface IObjectSet
    {
        /// <summary> check the existence of an object. </summary>
        /// <returns> true if object is exist, false otherwise. </returns>
        bool IsExist(object obj);

        /// <summary> if the object is not in the set, add it in. else do nothing. </summary>
        /// <returns> true if successfully added, false otherwise. </returns>
        bool Add(object obj);
    }

    public sealed class ObjectSetUsingConditionalWeakTable : IObjectSet
    {
        /// <summary> unit test on object set. </summary>
        internal static void Main() {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ObjectSetUsingConditionalWeakTable objSet = new ObjectSetUsingConditionalWeakTable();
            for (int i = 0; i < 10000000; ++i) {
                object obj = new object();
                if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }


        public bool IsExist(object obj) {
            return objectSet.TryGetValue(obj, out tryGetValue_out0);
        }

        public bool Add(object obj) {
            if (IsExist(obj)) {
                return false;
            } else {
                objectSet.Add(obj, null);
                return true;
            }
        }

        /// <summary> internal representation of the set. (only use the key) </summary>
        private ConditionalWeakTable<object, object> objectSet = new ConditionalWeakTable<object, object>();

        /// <summary> used to fill the out parameter of ConditionalWeakTable.TryGetValue(). </summary>
        private static object tryGetValue_out0 = null;
    }

    [Obsolete("It will crash if there are too many objects and ObjectSetUsingConditionalWeakTable get a better performance.")]
    public sealed class ObjectSetUsingObjectIDGenerator : IObjectSet
    {
        /// <summary> unit test on object set. </summary>
        internal static void Main() {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ObjectSetUsingObjectIDGenerator objSet = new ObjectSetUsingObjectIDGenerator();
            for (int i = 0; i < 10000000; ++i) {
                object obj = new object();
                if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }


        public bool IsExist(object obj) {
            bool firstTime;
            idGenerator.HasId(obj, out firstTime);
            return !firstTime;
        }

        public bool Add(object obj) {
            bool firstTime;
            idGenerator.GetId(obj, out firstTime);
            return firstTime;
        }


        /// <summary> internal representation of the set. </summary>
        private ObjectIDGenerator idGenerator = new ObjectIDGenerator();
    }
}

In my test, the ObjectIDGenerator will throw an exception to complain that there are too many objects when creating 10,000,000 objects (10x than in the code above) in the for loop.

Also, the benchmark result is that the ConditionalWeakTable implementation is 1.8x faster than the ObjectIDGenerator implementation.

How to show all of columns name on pandas dataframe?

If you just want to see all the columns you can do something of this sort as a quick fix

cols = data_all2.columns

now cols will behave as a iterative variable that can be indexed. for example

cols[11:20]

Authentication failed because remote party has closed the transport stream

If you want to use an older version of .net, create your own flag and cast it.

    //
    // Summary:
    //     Specifies the security protocols that are supported by the Schannel security
    //     package.
    [Flags]
    private enum MySecurityProtocolType
    {
        //
        // Summary:
        //     Specifies the Secure Socket Layer (SSL) 3.0 security protocol.
        Ssl3 = 48,
        //
        // Summary:
        //     Specifies the Transport Layer Security (TLS) 1.0 security protocol.
        Tls = 192,
        //
        // Summary:
        //     Specifies the Transport Layer Security (TLS) 1.1 security protocol.
        Tls11 = 768,
        //
        // Summary:
        //     Specifies the Transport Layer Security (TLS) 1.2 security protocol.
        Tls12 = 3072
    }
    public Session()
    {
        System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)(MySecurityProtocolType.Tls12 | MySecurityProtocolType.Tls11 | MySecurityProtocolType.Tls);
    }

Representing Directory & File Structure in Markdown Syntax

There is an NPM module for this:

npm dree

It allows you to have a representation of a directory tree as a string or an object. Using it with the command line will allow you to save the representation in a txt file.

Example:

$ npm dree parse myDirectory --dest ./generated --name tree

Decompile Python 2.7 .pyc

Decompyle++ (pycdc) appears to work for a range of python versions: https://github.com/zrax/pycdc

For example:

git clone https://github.com/zrax/pycdc   
cd pycdc
make  
./bin/pycdc Example.pyc > Example.py

How can I remount my Android/system as read-write in a bash script using adb?

mount -o rw,remount $(mount | grep /dev/root | awk '{print $3}')

this does the job for me, and should work for any android version.

join on multiple columns

Below is the structure of SQL that you may write. You can do multiple joins by using "AND" or "OR".

Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA, 
INNER JOIN TableB
 ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2

How do you convert between 12 hour time and 24 hour time in PHP?

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));

Re-doing a reverted merge in Git

To revert a revert in GIT:

git revert <commit-hash-of-previous-revert>

How to set a CMake option() at command line

Delete the CMakeCache.txt file and try this:

cmake -G %1 -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DBUILD_TESTS=ON ..

You have to enter all your command-line definitions before including the path.

add a temporary column with a value

I giving you an example in wich the TABLE registrofaena doesn't have the column called minutos. Minutos is created and it content is a result of divide demora/60, in other words, i created a column to show the values of the delay in minutes.

This is the query:

SELECT idfaena,fechahora,demora, demora/60 as minutos,comentario 
FROM registrofaena  
WHERE fecha>='2018-10-17' AND comentario <> '' 
ORDER BY idfaena ASC;

This is the view:

This is the result

Hide axis values but keep axis tick labels in matplotlib

plt.gca().axes.yaxis.set_ticklabels([])

enter image description here

How to change DataTable columns order

If you have more than 2-3 columns, SetOrdinal is not the way to go. A DataView's ToTable method accepts a parameter array of column names. Order your columns there:

DataView dataView = dataTable.DefaultView;
dataTable = dataView.ToTable(true, "Qty", "Unit", "Id");

How can I use ":" as an AWK field separator?

There isn't any need to write this much. Just put your desired field separator with the -F option in the AWK command and the column number you want to print segregated as per your mentioned field separator.

echo "1: " | awk -F: '{print $1}'
1

echo "1#2" | awk -F# '{print $1}'
1

How to do INSERT into a table records extracted from another table

I believe your problem in this instance is the "values" keyword. You use the "values" keyword when you are inserting only one row of data. For inserting the results of a select, you don't need it.

Also, you really don't need the parentheses around the select statement.

From msdn:

Multiple-record append query:

INSERT INTO target [(field1[, field2[, …]])] [IN externaldatabase]
SELECT [source.]field1[, field2[, …]
FROM tableexpression

Single-record append query:

INSERT INTO target [(field1[, field2[, …]])]     
VALUES (value1[, value2[, …])