Programs & Examples On #Shared cache

Convert integer to hexadecimal and back again

int to hex:

int a = 72;

Console.WriteLine("{0:X}", a);

hex to int:

int b = 0xB76;

Console.WriteLine(b);

HtmlEncode from Class Library

In case you're using SharePoint 2010, using the following line of code will avoid having to reference the whole System.Web library:

Microsoft.SharePoint.Utilities.SPHttpUtility.HtmlEncode(stringToEncode);

Why fragments, and when to use fragments instead of activities?

Adding to above answers, I shall tell using example of an app I released on playstore.

This was the first app I developed when learning android there fore I worked only with activities There are multiple activity pages I think about 12. Most of these had content that could be reused in other pages yet I ended up with a separate activity page for almost every single click on the app. Once I learnt fragments I realised how all reusables could just be implemented and separate fragments and just be used with very few activities. My user may not see any difference, but the same can be done with lesser code besides fragments are light weight, apart from the reusability and modularity they offer.

JavaScript: undefined !== undefined?

That's a bad practice to use the == equality operator instead of ===.

undefined === undefined // true
null == undefined // true
null === undefined // false

The object.x === undefined should return true if x is unknown property.

In chapter Bad Parts of JavaScript: The Good Parts, Crockford writes the following:

If you attempt to extract a value from an object, and if the object does not have a member with that name, it returns the undefined value instead.

In addition to undefined, JavaScript has a similar value called null. They are so similar that == thinks they are equal. That confuses some programmers into thinking that they are interchangeable, leading to code like

value = myObject[name];
if (value == null) {
    alert(name + ' not found.');
}

It is comparing the wrong value with the wrong operator. This code works because it contains two errors that cancel each other out. That is a crazy way to program. It is better written like this:

value = myObject[name];
if (value === undefined) {
    alert(name + ' not found.');
}

How to get week number of the month from the date in sql server 2008

Code is below:

set datefirst 7
declare @dt datetime='29/04/2016 00:00:00'
select (day(@dt)+datepart(WEEKDAY,dateadd(d,-day(@dt),@dt+1)))/7

Two models in one view in ASP MVC 3

If you are a fan of having very flat models, just to support the view, you should create a model specific to this particular view...

public class EditViewModel
    public int PersonID { get; set; }
    public string PersonName { get; set; }
    public int OrderID { get; set; }
    public int TotalSum { get; set; }
}

Many people use AutoMapper to map from their domain objects to their flat views.

The idea of the view model is that it just supports the view - nothing else. You have one per view to ensure that it only contains what is required for that view - not loads of properties that you want for other views.

Integer to IP Address - C

void ul2chardec(char*pcIP, unsigned long ulIPN){
int i; int k=0; char c0, c1;
for (i = 0; i<4; i++){
    c0 = ((((ulIPN & (0xff << ((3 - i) * 8))) >> ((3 - i) * 8))) / 100) + 0x30;
    if (c0 != '0'){ *(pcIP + k) = c0; k++; }
    c1 = (((((ulIPN & (0xff << ((3 - i) * 8))) >> ((3 - i) * 8))) % 100) / 10) + 0x30;
    if (!(c1 =='0' && c0=='0')){ *(pcIP + k) = c1; k++; }
    *(pcIP +k) = (((((ulIPN & (0xff << ((3 - i) * 8)))) >> ((3 - i) * 8))) % 10) + 0x30;
    k++;
    if (i<3){ *(pcIP + k) = '.'; k++;}
}
*(pcIP + k) = 0; // pcIP should be x10 bytes

}

check android application is in foreground or not?

With the new Android Architecture of Lifecycle extensions, we can achieve this with utmost ease.

Just ensure you pull this dependency in your build.gradle file:

dependencies {
    implementation "android.arch.lifecycle:extensions:1.1.0"
}

Then in your Application class, use this:

class ArchLifecycleApp : Application(), LifecycleObserver {

    override fun onCreate() {
        super.onCreate()
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgrounded() {
        Log.d("MyApp", "App in background")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onAppForegrounded() {
        Log.d("MyApp", "App in foreground")
    }
}

In the end, update your AndroidManifest.xml file with:

<application
    android:name=".ArchLifecycleApp"
    //Your extra code
    ....>
</application>

Now, on everytime the Application goes to Foreground or Background, we are going to receive the Logs associated with the two methods declared.

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

Send and receive messages through NSNotificationCenter in Objective-C?

SWIFT 5.1 of selected answer for newbies

class TestClass {
    deinit {
        // If you don't remove yourself as an observer, the Notification Center
        // will continue to try and send notification objects to the deallocated
        // object.
        NotificationCenter.default.removeObserver(self)
    }

    init() {
        super.init()

        // Add this instance of TestClass as an observer of the TestNotification.
        // We tell the notification center to inform us of "TestNotification"
        // notifications using the receiveTestNotification: selector. By
        // specifying object:nil, we tell the notification center that we are not
        // interested in who posted the notification. If you provided an actual
        // object rather than nil, the notification center will only notify you
        // when the notification was posted by that particular object.

        NotificationCenter.default.addObserver(self, selector: #selector(receiveTest(_:)), name: NSNotification.Name("TestNotification"), object: nil)
    }

    @objc func receiveTest(_ notification: Notification?) {
        // [notification name] should always be @"TestNotification"
        // unless you use this method for observation of other notifications
        // as well.

        if notification?.name.isEqual(toString: "TestNotification") != nil {
            print("Successfully received the test notification!")
        }
    }
}

... somewhere else in another class ...

 func someMethod(){
        // All instances of TestClass will be notified
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "TestNotification"), object: self)
 }

Change the borderColor of the TextBox

set Text box Border style to None then write this code to container form "paint" event

private void Form1_Paint(object sender, PaintEventArgs e)
{
    System.Drawing.Rectangle rect = new Rectangle(TextBox1.Location.X, 
    TextBox1.Location.Y, TextBox1.ClientSize.Width, TextBox1.ClientSize.Height);
                
                rect.Inflate(1, 1); // border thickness
                System.Windows.Forms.ControlPaint.DrawBorder(e.Graphics, rect, 
    Color.DeepSkyBlue, ButtonBorderStyle.Solid);
}

Does Java have an exponential operator?

There is no operator, but there is a method.

Math.pow(2, 3) // 8.0

Math.pow(3, 2) // 9.0

FYI, a common mistake is to assume 2 ^ 3 is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.

If statement in aspx page

A complete answer for optional content in the header of a VB.NET aspx page using a master page:

 <%@ Page Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="some_vb_page.aspx.vb" Inherits="some_vb_page" %> 
 <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">          
     <% If Request.QueryString("id_query_param") = 123 Then 'Add some VB comment here, 
         'which will not be visible in the rendered source code of the aspx page later %>        
         <!-- add some html content depending on -->
         <!-- the condition in the if statement: -->                
         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript" charset="utf-8"></script>
     <% End If %>
</asp:Content>

Where your current page url is something like:

http://mywebpage.com/some_vb_page.aspx?id_query_param=123

nginx error connect to php5-fpm.sock failed (13: Permission denied)

Please NOTICE (at least in centos 8) the user who you are assigning listen.owner and other stuff to it MUST be in the same POOL with the user for example given I am the foo user

[www] # WRONG | IN MY CASE I WAS UNDER www POOL SO IT WASNT WORKING FOR ME.
[foo] # CORRECT | THE POOL AND THE USER MATCHES.

listen.owner = foo
listen.group = foo
listen.mode = 0660
user = foo
group = foo

I dont know if there's a global pool but after hours of searching I finlly did it.

Use VBA to Clear Immediate Window?

For cleaning Immediate window I use (VBA Excel 2016) next function:

Private Sub ClrImmediate()
   With Application.VBE.Windows("Immediate")
       .SetFocus
       Application.SendKeys "^g", True
       Application.SendKeys "^a", True
       Application.SendKeys "{DEL}", True
   End With
End Sub

But direct call of ClrImmediate() like this:

Sub ShowCommandBarNames()
    ClrImmediate
 '--   DoEvents    
    Debug.Print "next..."
End Sub

works only if i put the breakpoint on Debug.Print, otherwise the clearing will be done after execution of ShowCommandBarNames() - NOT before Debug.Print. Unfortunately, call of DoEvents() did not help me... And no matter: TRUE or FALSE is set for SendKeys.

To solve this I use next couple of calls:

Sub ShowCommandBarNames()
 '--    ClrImmediate
    Debug.Print "next..."
End Sub

Sub start_ShowCommandBarNames()
   ClrImmediate
   Application.OnTime Now + TimeSerial(0, 0, 1), "ShowCommandBarNames"
End Sub

It seems to me that using Application.OnTime might be very useful in programming for VBA IDE. In this case it's can be used even TimeSerial(0, 0, 0).

Importing JSON into an Eclipse project

Download json from java2s website then include in your project. In your class add these package java_basic;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

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

@zdan. Good answer. I'd improve it like this...

I think that the closest you can come to a true return value in PowerShell is to use a local variable to pass the value and never to use return as it may be 'corrupted' by any manner of output situations

function CheckRestart([REF]$retval)
{
    # Some logic
    $retval.Value = $true
}
[bool]$restart = $false
CheckRestart( [REF]$restart)
if ( $restart )
{
    Restart-Computer -Force
}

The $restart variable is used either side of the call to the function CheckRestart making clear the scope of the variable. The return value can by convention be either the first or last parameter declared. I prefer last.

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

  1. Delete these entries mentioned in this post: http://manfredlange.blogspot.ca/2008/03/visual-studio-unable-to-find-manifest.html.

  2. Also remove the .snk or .pfx files from the project root.

Don't forget to push these changes to GitHub, for Jenkins only pulls source from GitHub.

When to use: Java 8+ interface default method, vs. abstract method

Default methods in Java Interface are to be used more for providing dummy implementation of a function thus saving any implementing class of that interface from the pain of declaring all the abstract methods even if they want to deal with only one. Default methods in interface are thus in a way more a replacement for the concept of adapter classes.

The methods in abstract class are however supposed to give a meaningful implementation which any child class should override only if needed to override a common functionality.

What is the best way to uninstall gems from a rails3 project?

You must use 'gem uninstall gem_name' to uninstall a gem.

Note that if you installed the gem system-wide (ie. sudo bundle install) then you may need to specify the binary directory using the -n option, to ensure binaries belonging to the gem are removed. For example

sudo gem uninstall gem_name  -n /usr/lib/ruby/gems/1.9.1/bin

Can you test google analytics on a localhost address?

After spending about two hours trying to come up with a solution I realized that I had adblockers blocking the call to GA. Once I turned them off I was good to go.

How to display loading message when an iFrame is loading?

You can use below code .

 iframe {background:url(../images/loader.gif) center center no-repeat; height: 100%;}

How do I install Maven with Yum?

For future reference and for simplicity sake for the lazy people out there that don't want much explanations but just run things and make it work asap:

1) sudo wget https://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo

2) sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo

3) sudo yum install -y apache-maven

4) mvn --version

Hope you enjoyed this copy & paste session.

Delete specific values from column with where condition?

UPDATE myTable 
   SET myColumn = NULL 
 WHERE myCondition

How can I change the size of a Bootstrap checkbox?

I used just "save in zoom", in example:

.my_checkbox {
    width:5vw;
    height:5vh;
}

Force IE10 to run in IE10 Compatibility View?

You can try :

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" >

Just like you tried before, but caution:

It seems like the X-UA-Compatible tag has to be the first tag in the < head > section

If this conclusion is correct, then I believe it is undocumented in Microsoft’s blogs/msdn (and if it is documented, then it isn’t sticking out well enough from the docs). Ensuring that this was the first meta tag in the forced IE9 to switch to IE8 mode successfully

How can I split a string with a string delimiter?

There is a version of string.Split that takes an array of strings and a StringSplitOptions parameter:

http://msdn.microsoft.com/en-us/library/tabh47cf.aspx

What is the difference between Subject and BehaviorSubject?

BehaviourSubject

BehaviourSubject will return the initial value or the current value on Subscription

var bSubject= new Rx.BehaviorSubject(0);  // 0 is the initial value

bSubject.subscribe({
  next: (v) => console.log('observerA: ' + v)  // output initial value, then new values on `next` triggers
});

bSubject.next(1);  // output new value 1 for 'observer A'
bSubject.next(2);  // output new value 2 for 'observer A', current value 2 for 'Observer B' on subscription

bSubject.subscribe({
  next: (v) => console.log('observerB: ' + v)  // output current value 2, then new values on `next` triggers
});

bSubject.next(3);

With output:

observerA: 0
observerA: 1
observerA: 2
observerB: 2
observerA: 3
observerB: 3

Subject

Subject does not return the current value on Subscription. It triggers only on .next(value) call and return/output the value

var subject = new Rx.Subject();

subject.next(1); //Subjects will not output this value

subject.subscribe({
  next: (v) => console.log('observerA: ' + v)
});
subject.subscribe({
  next: (v) => console.log('observerB: ' + v)
});

subject.next(2);
subject.next(3);

With the following output on the console:

observerA: 2
observerB: 2
observerA: 3
observerB: 3

What is the difference between instanceof and Class.isAssignableFrom(...)?

some tests we did in our team show that A.class.isAssignableFrom(B.getClass()) works faster than B instanceof A. this can be very useful if you need to check this on large number of elements.

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

I like this method:

using Newtonsoft.Json.Linq;
// jsonString is your JSON-formatted string
JObject jsonObj = JObject.Parse(jsonString);
Dictionary<string, object> dictObj = jsonObj.ToObject<Dictionary<string, object>>();

You can now access anything you want using the dictObj as a dictionary. You can also use Dictionary<string, string> if you prefer to get the values as strings.

You can use this same method to cast as any kind of .NET object.

Opening a remote machine's Windows C drive

By default, Windows makes the root of each drive available (provided you've got Administrator privileges) as (e.g.) \\server\c$. These are known as Administrative Shares.

Database Diagram Support Objects cannot be Installed ... no valid owner

1.Right click on your Database , 2.Then select properties . 3.Select the option in compatibility levels choose sql 2008[100] if you are working with Microsoft sql 2008.

4.Then select the file and write ( sa ) in owner`s textbox

100% works for me.

How to make bootstrap column height to 100% row height?

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.

Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/

.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}

What is monkey patching?

No, it's not like any of those things. It's simply the dynamic replacement of attributes at runtime.

For instance, consider a class that has a method get_data. This method does an external lookup (on a database or web API, for example), and various other methods in the class call it. However, in a unit test, you don't want to depend on the external data source - so you dynamically replace the get_data method with a stub that returns some fixed data.

Because Python classes are mutable, and methods are just attributes of the class, you can do this as much as you like - and, in fact, you can even replace classes and functions in a module in exactly the same way.

But, as a commenter pointed out, use caution when monkeypatching:

  1. If anything else besides your test logic calls get_data as well, it will also call your monkey-patched replacement rather than the original -- which can be good or bad. Just beware.

  2. If some variable or attribute exists that also points to the get_data function by the time you replace it, this alias will not change its meaning and will continue to point to the original get_data. (Why? Python just rebinds the name get_data in your class to some other function object; other name bindings are not impacted at all.)

How does += (plus equal) work?

That is just a short form for:

sum = sum + value;

Rails 4 - Strong Parameters - Nested Objects

As odd as it sound when you want to permit nested attributes you do specify the attributes of nested object within an array. In your case it would be

Update as suggested by @RafaelOliveira

params.require(:measurement)
      .permit(:name, :groundtruth => [:type, :coordinates => []])

On the other hand if you want nested of multiple objects then you wrap it inside a hash… like this

params.require(:foo).permit(:bar, {:baz => [:x, :y]})


Rails actually have pretty good documentation on this: http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit

For further clarification, you could look at the implementation of permit and strong_parameters itself: https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/strong_parameters.rb#L246-L247

How to set a dropdownlist item as selected in ASP.NET?

You can use the FindByValue method to search the DropDownList for an Item with a Value matching the parameter.

dropdownlist.ClearSelection();
dropdownlist.Items.FindByValue(value).Selected = true;

Alternatively you can use the FindByText method to search the DropDownList for an Item with Text matching the parameter.

Before using the FindByValue method, don't forget to reset the DropDownList so that no items are selected by using the ClearSelection() method. It clears out the list selection and sets the Selected property of all items to false. Otherwise you will get the following exception.

"Cannot have multiple items selected in a DropDownList"

AngularJS ng-style with a conditional expression

For single css property

ng-style="1==1 && {'color':'red'}"

For multiple css properties below can be referred

ng-style="1==1 && {'color':'red','font-style': 'italic'}"

Replace 1==1 with your condition expression

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

Here's a setTimeout equivalent, mostly useful when trying to update the User Interface after a delay.

As you may know, updating the user interface can only by done from the UI thread. AsyncTask does that for you by calling its onPostExecute method from that thread.

new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // Update the User Interface
        }

    }.execute();

How to find a user's home directory on linux or unix?

If your are trying to do this for a user name that you cannot hard code, it can be challenging. Sure echo ~rbronosky would tell you the path to my home dir /home/rbronosky, but what if rbronosky is in a variable? If you do name=rbronosky; echo ~$name you get ~rbronosky

Here is a real world case and the solution:

You have a script that the user has to run via sudo. The script has to access the user's home folder. You can't reference ~/.ssh or else it will expand to /root/.ssh. Instead you do:

# Up near the top of your script add
export HOME=$(bash <<< "echo ~${SUDO_USER:-}")
# Then you can use $HOME like you would expect
cat rsa_key.pub >> $HOME/.ssh/authorized_keys

The beauty of it is that if the script is not run as sudo then $SUDO_USER is empty, so it's basically the same thing as doing "echo ~". It still works as you' expect.

If you use set -o nounset, which you should be using, the variable reference ${SUDO_USER:-} will default to blank, where $SUDO_USER or ${SUDO_USER} would give an error (because it is unset) if not run via sudo.

python: SyntaxError: EOL while scanning string literal

In my case, I forgot (' or ") at the end of string. E.g 'ABC' or "ABC"

Jquery mouseenter() vs mouseover()

Old question, but still no good up-to-date answer with insight imo.

As jQuery uses Javascript wording for events and handlers, but does its own undocumented, but different interpretation of those, let me first shed light on the difference from the pure Javascript viewpoint:

  • both event pairs
    • the mouse can “jump” from outside/outer elements to inner/innermost elements when moved faster than the browser samples its position
    • any enter/over gets a corresponding leave/out (possibly late/jumpy)
    • events go to the visible element below the pointer (invisible elements can’t be target)
  • mouseenter/mouseleave
    • does not bubble (event not useful for delegate handlers)
    • the event registration itself defines the area of observation and abstraction
    • works on the target area, like a park with a pond: the pond is considered part of the park
    • the event is emitted on the target/area whenever the element itself or any descendant directly is entered/left the first time
    • entering a descendant, moving from one descendant to another or moving back into the target does not finish/restart the mouseenter/mouseleave cycle (i.e. no events fire)
    • if you want to observe multiple areas with one handler, register it on each area/element or use the other event pair discussed next
    • descendants of registered areas/elements can have their own handlers, creating an independent observation area with its independent mouseenter/mouseleave event cycles
    • if you think about how a bubbling version of mouseenter/mouseleave could look like, you end up with with something like mouseover/mouseout
  • mouseover/mouseout
    • events bubble
    • events fire whenever the element below the pointer changes
      • mouseout on the previously sampled element
      • followed by mouseover on the new element
      • the events don’t “nest”: before e.g. a child is “overed” the parent will be “out”
    • target/relatedTarget indicate new and previous element
    • if you want to watch different areas
      • register one handler on a common parent (or multiple parents, which together cover all elements you want to watch)
      • look for the element you are interested in between the handler element and the target element; maybe $(event.target).closest(...) suits your needs

Not-so-trivial mouseover/mouseout example:

$('.side-menu, .top-widget')
  .on('mouseover mouseout', event => {
    const target = event.type === 'mouseover' ? event.target : event.relatedTarget;
    const thing = $(target).closest('[data-thing]').attr('data-thing') || 'default';
    // do something with `thing`
  });

These days, all browsers support mouseover/mouseout and mouseenter/mouseleave natively. Nevertheless, jQuery does not register your handler to mouseenter/mouseleave, but silently puts them on a wrappers around mouseover/mouseout as the code below exposes.

The emulation is unnecessary, imperfect and a waste of CPU cycles: it filters out mouseover/mouseout events that a mouseenter/mouseleave would not get, but the target is messed. The real mouseenter/mouseleave would give the handler element as target, the emulation might indicate children of that element, i.e. whatever the mouseover/mouseout carried.

For that reason I do not use jQuery for those events, but e.g.:

$el[0].addEventListener('mouseover', e => ...);

_x000D_
_x000D_
const list = document.getElementById('log');
const outer = document.getElementById('outer');
const $outer = $(outer);

function log(tag, event) {
  const li = list.insertBefore(document.createElement('li'), list.firstChild);
  // only jQuery handlers have originalEvent
  const e = event.originalEvent || event;
  li.append(`${tag} got ${e.type} on ${e.target.id}`);
}

outer.addEventListener('mouseenter', log.bind(null, 'JSmouseenter'));
$outer.on('mouseenter', log.bind(null, '$mouseenter'));
_x000D_
div {
  margin: 20px;
  border: solid black 2px;
}

#inner {
  min-height: 80px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <div id=outer>
    <ul id=log>
    </ul>
  </div>
</body>
_x000D_
_x000D_
_x000D_


Note: For delegate handlers never use jQuery’s “delegate handlers with selector registration”. (Reason in another answer.) Use this (or similar):

$(parent).on("mouseover", e => {
  if ($(e.target).closest('.gold').length) {...};
});

instead of

$(parent).on("mouseover", '.gold', e => {...});

How to save the output of a console.log(object) to a file?

This is really late to the party, but maybe it will help someone. My solution seems similar to what the OP described as problematic, but maybe it's a feature that Chrome offers now, but not then. I tried right-clicking and saving the .log file after the object was written to the console, but all that gave me was a text file with this:

console.js:230 Done: Array(50000)[0 … 9999][10000 … 19999][20000 … 29999][30000 … 39999][40000 … 49999]length: 50000__proto__: Array(0)

which was of no use to anyone.

What I ended up doing was finding the console.log(data) in the code, dropped a breakpoint on it and then typed JSON.Stringify(data) in the console which displayed the entire object as a JSON string and the Chrome console actually gives you a button to copy it. Then paste into a text editor and there's your JSON

enter image description here

Checking for an empty file in C++

pFile = fopen("file", "r");
fseek (pFile, 0, SEEK_END);
size=ftell (pFile);
if (size) {
  fseek(pFile, 0, SEEK_SET);
  do something...
}

fclose(pFile)

Count number of occurrences by month

Make column B in sheet1 the dates but where the day of the month is always the first day of the month, e.g. in B2 put =DATE(YEAR(A2),MONTH(A2),1). Then make E5 on sheet 2 contain the first date of the month you need, e.g. Date(2013,4,1). After that, putting in F5 COUNTIF(Sheet1!B2:B50, E5) will give you the count for the month specified in E5.

Accessing the index in 'for' loops?

If I were to iterate nums = [1, 2, 3, 4, 5] I would do

for i, num in enumerate(nums, start=1):
    print(i, num)

Or get the length as l = len(nums)

for i in range(l):
    print(i+1, nums[i])

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

I tried to execute specific plugging right after clean up i.e. post-clean (default is clean phase). This worked for me with eclipse indigo. Just added post-clean resolved the problem for me.

<executions>
  <execution>
    <configuration>
    </configuration>
   <phase>post-clean</phase>
    <goals>
      <goal>update-widgetset</goal>
    </goals>
  </execution>
</executions> 

MySQL Update Column +1?

update post set count = count + 1 where id = 101

Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

The SQLite command line utility has a .schema TABLENAME command that shows you the create statements.

How to generate Javadoc from command line

its simple go to the folder where your all java code is saved say E:/javaFolder and then javadoc *.java

example

E:\javaFolder> javadoc *.java

Grid of responsive squares

I use this solution for responsive boxes of different rations:

HTML:

<div class="box ratio1_1">
  <div class="box-content">
            ... CONTENT HERE ...
  </div>
</div>

CSS:

.box-content {
  width: 100%; height: 100%;
  top: 0;right: 0;bottom: 0;left: 0;
  position: absolute;
}
.box {
  position: relative;
  width: 100%;
}
.box::before {
    content: "";
    display: block;
    padding-top: 100%; /*square for no ratio*/
}
.ratio1_1::before { padding-top: 100%; }
.ratio1_2::before { padding-top: 200%; }
.ratio2_1::before { padding-top: 50%; }
.ratio4_3::before { padding-top: 75%; }
.ratio16_9::before { padding-top: 56.25%; }

See demo on JSfiddle.net

Why does a base64 encoded string have an = sign at the end

It's padding. From http://en.wikipedia.org/wiki/Base64:

In theory, the padding character is not needed for decoding, since the number of missing bytes can be calculated from the number of Base64 digits. In some implementations, the padding character is mandatory, while for others it is not used. One case in which padding characters are required is concatenating multiple Base64 encoded files.

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You can write a PL/SQL function to return that cursor (or you could put that function in a package if you have more code related to this):

CREATE OR REPLACE FUNCTION get_allitems
  RETURN SYS_REFCURSOR
AS
  my_cursor SYS_REFCURSOR;
BEGIN
  OPEN my_cursor FOR SELECT * FROM allitems;
  RETURN my_cursor;
END get_allitems;

This will return the cursor.

Make sure not to put your SELECT-String into quotes in PL/SQL when possible. Putting it in strings means that it can not be checked at compile time, and that it has to be parsed whenever you use it.


If you really need to use dynamic SQL you can put your query in single quotes:

  OPEN my_cursor FOR 'SELECT * FROM allitems';

This string has to be parsed whenever the function is called, which will usually be slower and hides errors in your query until runtime.

Make sure to use bind-variables where possible to avoid hard parses:

  OPEN my_cursor FOR 'SELECT * FROM allitems WHERE id = :id' USING my_id;

Pretty-print an entire Pandas Series / DataFrame

You can also use the option_context, with one or more options:

with pd.option_context('display.max_rows', None, 'display.max_columns', None):  # more options can be specified also
    print(df)

This will automatically return the options to their previous values.

If you are working on jupyter-notebook, using display(df) instead of print(df) will use jupyter rich display logic (like so).

How do I detect when someone shakes an iPhone?

First off, I know this is an old post, but it is still relevant, and I found that the two highest voted answers did not detect the shake as early as possible. This is how to do it:

  1. Link CoreMotion to your project in the target's build phases: CoreMotion
  2. In your ViewController:

    - (BOOL)canBecomeFirstResponder {
        return YES;
    }
    
    - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
    {
        if (motion == UIEventSubtypeMotionShake) {
            // Shake detected.
        }
    }
    

How do I put variables inside javascript strings?

if you are using ES6, the you should use the Template literals.

//you can do this
let sentence = `My name is ${ user.name }. Nice to meet you.`

read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

onCreateOptionsMenu inside Fragments

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_add_customer, container, false);
        setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_sample, menu);
    super.onCreateOptionsMenu(menu,inflater);
}

How can I generate a random number in a certain range?

Also, from API level 21 this is possible:

int random = ThreadLocalRandom.current().nextInt(min, max);

What is default color for text in textview?

There are some default colors defined in android.R.color

int c = getResources().getColor(android.R.color.primary_text_dark);

How do I resolve this "ORA-01109: database not open" error?

If you are using 19c then just follow the following steps

  1. Login with sys user.
  2. alter the session to the pluggable database with the following command.
  3. SQL>alter session set container=orclpdb;
  4. Next startup the database.
  5. SQL>startup After that database will not show the above error.

call javascript function on hyperlink click

I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.

attachEvent / addEventListening allow multiple event handlers to be created.

How to resolve "local edit, incoming delete upon update" message

Try to resolve the conflict using

svn resolve --accept=working PATH

MongoDB vs Firebase

In my experience, working with Firebase is a huge advantage if you are trying to do user management, database, messaging sort of app since all of these features are already well integrated.

Like others have said, if you're just focused on the database/querying aspect, stick to mongo.

What is the difference between Bootstrap .container and .container-fluid classes?

You are right in 3.1 .container-fluid and .container are same and works like container but if you remove them it works like .container-fluid (full width). They had removed .container-fluid for "Mobile First Approach", but now it's back in 3.3.4 (and they will work differently)

To get latest bootstrap please read this post on stackoverflow it will help check it out.

Could not install packages due to an EnvironmentError: [Errno 13]

I had the same problem while installing numpy with pip install numpy.

Then I tried

sudo -H pip3 install --upgrade pip

sudo -H pip3 install numpy

It worked well for me.

Explanation : The -H (HOME) option with sudo sets the HOME environment variable to the home directory of the target user (root by default). By default, sudo does not modify HOME.

failed to load ad : 3

Your ad units are not displaying ads because you haven't yet verified your address (PIN).

Maybe it helps to others, i received this notification on my AdSense account. enter image description here

Is there a "theirs" version of "git merge -s ours"?

Why doesn't it exist?

While I mention in "git command for making one branch like another" how to simulate git merge -s theirs, note that Git 2.15 (Q4 2017) is now clearer:

The documentation for '-X<option>' for merges was misleadingly written to suggest that "-s theirs" exists, which is not the case.

See commit c25d98b (25 Sep 2017) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 4da3e23, 28 Sep 2017)

merge-strategies: avoid implying that "-s theirs" exists

The description of -Xours merge option has a parenthetical note that tells the readers that it is very different from -s ours, which is correct, but the description of -Xtheirs that follows it carelessly says "this is the opposite of ours", giving a false impression that the readers also need to be warned that it is very different from -s theirs, which in reality does not even exist.

-Xtheirs is a strategy option applied to recursive strategy. This means that recursive strategy will still merge anything it can, and will only fall back to "theirs" logic in case of conflicts.

That debate for the pertinence or not of a theirs merge strategy was brought back recently in this Sept. 2017 thread.
It acknowledges older (2008) threads

In short, the previous discussion can be summarized to "we don't want '-s theirs' as it encourages the wrong workflow".

It mentions the alias:

mtheirs = !sh -c 'git merge -s ours --no-commit $1 && git read-tree -m -u $1' -

Yaroslav Halchenko tries to advocate once more for that strategy, but Junio C. Hamano adds:

The reason why ours and theirs are not symmetric is because you are you and not them---the control and ownership of our history and their history is not symmetric.

Once you decide that their history is the mainline, you'd rather want to treat your line of development as a side branch and make a merge in that direction, i.e. the first parent of the resulting merge is a commit on their history and the second parent is the last bad one of your history. So you would end up using "checkout their-history && merge -s ours your-history" to keep the first-parenthood sensible.

And at that point, use of "-s ours" is no longer a workaround for lack of "-s theirs".
It is a proper part of the desired semantics, i.e. from the point of view of the surviving canonical history line, you want to preserve what it did, nullifying what the other line of history did.

Junio adds, as commented by Mike Beaton:

git merge -s ours <their-ref> effectively says 'mark commits made up to <their-ref> on their branch as commits to be permanently ignored';
and this matters because, if you subsequently merge from later states of their branch, their later changes will be brought in without the ignored changes ever being brought in.

how concatenate two variables in batch script?

You can do it without setlocal, because of the setlocal command the variable won't survive an endlocal because it was created in setlocal. In this way the variable will be defined the right way.

To do that use this code:

set var1=A

set var2=B

set AB=hi

call set newvar=%%%var1%%var2%%%

echo %newvar% 

Note: You MUST use call before you set the variable or it won't work.

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

You need either

  • A unique index on Title in BookTitle
  • An ISBN column in BookCopy and the FK is on both columns

A foreign key needs to uniquely identify the parent row: you currently have no way to do that because Title is not unique.

Can you force Vue.js to reload/re-render?

<my-component :key="uniqueKey" />

along with it use this.$set(obj,'obj_key',value) and update uniqueKey for every update in object (obj) value for every update this.uniqueKey++

it worked for me this way

What is the difference between declarative and imperative paradigm in programming?

In computer science, declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow.

From http://en.wikipedia.org/wiki/Declarative_programming

in a nutshell the declarative language is simpler because it lacks the complexity of control flow ( loops, if statements, etc. )

A good comparison is the ASP.Net 'code-behind' model. You have declarative '.ASPX' files and then the imperative 'ASPX.CS' code files. I often find that if I can do all I need in the declarative half of the script a lot more people can follow what's being done.

How can getContentResolver() be called in Android?

You can use like this:

getApplicationContext().getContentResolver()

with the proper context.

TypeScript: correct way to do string equality?

The === is not for checking string equalit , to do so you can use the Regxp functions for example

if (x.match(y) === null) {
// x and y are not equal 
}

there is also the test function

Are nested try/except blocks in Python a good programming practice?

For your specific example, you don't actually need to nest them. If the expression in the try block succeeds, the function will return, so any code after the whole try/except block will only be run if the first attempt fails. So you can just do:

def __getattribute__(self, item):
    try:
        return object.__getattribute__(item)
    except AttributeError:
        pass
    # execution only reaches here when try block raised AttributeError
    try:
        return self.dict[item]
    except KeyError:
        print "The object doesn't have such attribute"

Nesting them isn't bad, but I feel like leaving it flat makes the structure more clear: you're sequentially trying a series of things and returning the first one that works.

Incidentally, you might want to think about whether you really want to use __getattribute__ instead of __getattr__ here. Using __getattr__ will simplify things because you'll know that the normal attribute lookup process has already failed.

<script> tag vs <script type = 'text/javascript'> tag

In HTML 4, the type attribute is required. In my experience, all browsers will default to text/javascript if it is absent, but that behaviour is not defined anywhere. While you can in theory leave it out and assume it will be interpreted as JavaScript, it's invalid HTML, so why not add it.

In HTML 5, the type attribute is optional and defaults to text/javascript

Use <script type="text/javascript"> or simply <script> (if omitted, the type is the same). Do not use <script language="JavaScript">; the language attribute is deprecated

Ref :
http://social.msdn.microsoft.com/Forums/vstudio/en-US/65aaf5f3-09db-4f7e-a32d-d53e9720ad4c/script-languagejavascript-or-script-typetextjavascript-?forum=netfxjscript
and
Difference between <script> tag with type and <script> without type?

Do you need type attribute at all?

I am using HTML5- No

I am not using HTML5 - Yes

git add only modified changes and ignore untracked files

Not sure if this is a feature or a bug but this worked for us:

git commit '' -m "Message"

Note the empty file list ''. Git interprets this to commit all modified tracked files, even if they are not staged, and ignore untracked files.

How do I find the PublicKeyToken for a particular dll?

Assembly.LoadFile(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319\system.data.dll").FullName

Will result in

System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Effectively use async/await with ASP.NET Web API

I am not very sure whether it will make any difference in performance of my API.

Bear in mind that the primary benefit of asynchronous code on the server side is scalability. It won't magically make your requests run faster. I cover several "should I use async" considerations in my article on async ASP.NET.

I think your use case (calling other APIs) is well-suited for asynchronous code, just bear in mind that "asynchronous" does not mean "faster". The best approach is to first make your UI responsive and asynchronous; this will make your app feel faster even if it's slightly slower.

As far as the code goes, this is not asynchronous:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
  var response = _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
  return Task.FromResult(response);
}

You'd need a truly asynchronous implementation to get the scalability benefits of async:

public async Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
  return await _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}

Or (if your logic in this method really is just a pass-through):

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
  return _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}

Note that it's easier to work from the "inside out" rather than the "outside in" like this. In other words, don't start with an asynchronous controller action and then force downstream methods to be asynchronous. Instead, identify the naturally asynchronous operations (calling external APIs, database queries, etc), and make those asynchronous at the lowest level first (Service.ProcessAsync). Then let the async trickle up, making your controller actions asynchronous as the last step.

And under no circumstances should you use Task.Run in this scenario.

80-characters / right margin line in Sublime Text 3

Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80 (there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80. Make sure that View ? Word Wrap is selected.

To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User and use any of the following rules:

{
    // set vertical rulers in specified columns.
    // Use "rulers": [80] for just one ruler
    // default value is []
    "rulers": [80, 100, 120],

    // turn on word wrap for source and text
    // default value is "auto", which means off for source and on for text
    "word_wrap": true,

    // set word wrapping at this column
    // default value is 0, meaning wrapping occurs at window width
    "wrap_width": 80
}

These settings can also be used in a .sublime-project file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings file if you only want them to apply to files written in a certain language (Python.sublime-settings vs. JavaScript.sublime-settings, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User.

As always, if you have multiple entries in your settings file, separate them with commas , except for after the last one. The entire content should be enclosed in curly braces { }. Basically, make sure it's valid JSON.

If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.

Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0 and O (digit zero and capital letter oh) and 1 and l (digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).

Coding Conventions - Naming Enums

Enums are classes and should follow the conventions for classes. Instances of an enum are constants and should follow the conventions for constants. So

enum Fruit {APPLE, ORANGE, BANANA, PEAR};

There is no reason for writing FruitEnum any more than FruitClass. You are just wasting four (or five) characters that add no information.

Java itself recommends this approach and it is used in their examples.

Create a zip file and download it

I just ran into this problem. For me the issue was with:

readfile("$archive_file_name");

It was resulting in a out of memory error.

Allowed memory size of 134217728 bytes exhausted (tried to allocate 292982784 bytes)

I was able to correct the problem by replacing readfile() with the following:

    $handle = fopen($zipPath, "rb");
    while (!feof($handle)){
        echo fread($handle, 8192);
    }
    fclose($handle);

Not sure if this is your same issue or not seeing that your file is only 1.2 MB. Maybe this will help someone else with a similar problem.

c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)

If you will place your definitions in this order then the code will be compiled

class Ball;

class Player {
public:
    void doSomething(Ball& ball);
private:
};

class Ball {
public:
    Player& PlayerB;
    float ballPosX = 800;
private:

};

void Player::doSomething(Ball& ball) {
    ball.ballPosX += 10;                   // incomplete type error occurs here.
}

int main()
{
}

The definition of function doSomething requires the complete definition of class Ball because it access its data member.

In your code example module Player.cpp has no access to the definition of class Ball so the compiler issues an error.

How do I add BundleConfig.cs to my project?

BundleConfig is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)

To add this file, first you need to add the Microsoft.AspNet.Web.Optimization nuget package to your web project:

Install-Package Microsoft.AspNet.Web.Optimization

Then under the App_Start folder create a new cs file called BundleConfig.cs. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):

using System.Web;
using System.Web.Optimization;

namespace CodeRepository.Web
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

Then modify your Global.asax and add a call to RegisterBundles() in Application_Start():

using System.Web.Optimization;

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app

How to center form in bootstrap 3

<div class="col-md-4 offset-md-4"> 
put your form here
</div>

How to keep environment variables when using sudo

If you have the need to keep the environment variables in a script you can put your command in a here document like this. Especially if you have lots of variables to set things look tidy this way.

# prepare a script e.g. for running maven
runmaven=/tmp/runmaven$$
# create the script with a here document 
cat << EOF > $runmaven
#!/bin/bash
# run the maven clean with environment variables set
export ANT_HOME=/usr/share/ant
export MAKEFLAGS=-j4
mvn clean install
EOF
# make the script executable
chmod +x $runmaven
# run it
sudo $runmaven
# remove it or comment out to keep
rm $runmaven

Replace multiple characters in one replace call

You could also try this :

function replaceStr(str, find, replace) {
    for (var i = 0; i < find.length; i++) {
        str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
    }
    return str;
}

var text = "#here_is_the_one#";
var find = ["#","_"];
var replace = ['',' '];
text = replaceStr(text, find, replace);
console.log(text);

find refers to the text to be found and replace to the text to be replaced with

This will be replacing case insensitive characters. To do otherway just change the Regex flags as required. Eg: for case sensitive replace :

new RegExp(find[i], 'g')

passing JSON data to a Spring MVC controller

  1. Html

    $('#save').click(function(event) {        
        var jenis = $('#jenis').val();
        var model = $('#model').val();
        var harga = $('#harga').val();
        var json = { "jenis" : jenis, "model" : model, "harga": harga};
        $.ajax({
            url: 'phone/save',
            data: JSON.stringify(json),
            type: "POST",           
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            success: function(data){ 
                alert(data);
            }
        });
    
        event.preventDefault();
    });
    
    1. Controller

      @Controller
      @RequestMapping(value="/phone")
      public class phoneController {
      
          phoneDao pd=new phoneDao();
      
          @RequestMapping(value="/save",method=RequestMethod.POST)
          public @ResponseBody
          int save(@RequestBody Smartphones phone)
          {
              return pd.save(phone);
          }
      
    2. Dao

      public Integer save(Smartphones i) {
          int id = 0;
          Session session=HibernateUtil.getSessionFactory().openSession();
          Transaction trans=session.beginTransaction();
          try {
              session.save(i);   
              id=i.getId();
              trans.commit();
          }
          catch(HibernateException he){}
          return id;
      }
      

Nginx: stat() failed (13: permission denied)

This is how i fixed this

sudo chmod o+x /home/ec2-user

SQL Server ON DELETE Trigger

I would suggest the use of exists instead of in because in some scenarios that implies null values the behavior is different, so

CREATE TRIGGER sampleTrigger
    ON database1.dbo.table1
    FOR DELETE
AS
    DELETE FROM database2.dbo.table2 childTable
    WHERE bar = 4 AND exists (SELECT id FROM deleted where deleted.id = childTable.id)
GO

How to view the list of compile errors in IntelliJ?

You should disable Power Save Mode

For me I clicked over this button

enter image description here

then disable Power Save Mode

How can I capture packets in Android?

Option 1 - Android PCAP

Limitation

Android PCAP should work so long as:

Your device runs Android 4.0 or higher (or, in theory, the few devices which run Android 3.2). Earlier versions of Android do not have a USB Host API

Option 2 - TcpDump

Limitation

Phone should be rooted

Option 3 - bitshark (I would prefer this)

Limitation

Phone should be rooted

Reason - the generated PCAP files can be analyzed in WireShark which helps us in doing the analysis.

Other Options without rooting your phone

  1. tPacketCapture

https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en

Advantages

Using tPacketCapture is very easy, captured packet save into a PCAP file that can be easily analyzed by using a network protocol analyzer application such as Wireshark.

  1. You can route your android mobile traffic to PC and capture the traffic in the desktop using any network sniffing tool.

http://lifehacker.com/5369381/turn-your-windows-7-pc-into-a-wireless-hotspot

Using Git, show all commits that are in one branch, but not the other(s)

You can use this simple script to see commits that are not merged

#!/bin/bash
# Show commits that exists only on branch and not in current
# Usage:
#   git branch-notmerge <branchname>
#
# Setup git alias
#   git config alias.branch-notmerge [path/to/this/script]
grep -Fvf <(git log --pretty=format:'%H - %s') <(git log $1 --pretty=format:'%H - %s')

You can use also tool git-wtf that will display state of branches

How to delete from select in MySQL?

you can use inner join :

DELETE 
    ps 
FROM 
    posts ps INNER JOIN 
         (SELECT 
           distinct id 
         FROM 
             posts 
         GROUP BY id  
      HAVING COUNT(id) > 1 ) dubids on dubids.id = ps.id  

How to transform numpy.matrix or array to scipy sparse matrix

You can pass a numpy array or matrix as an argument when initializing a sparse matrix. For a CSR matrix, for example, you can do the following.

>>> import numpy as np
>>> from scipy import sparse
>>> A = np.array([[1,2,0],[0,0,3],[1,0,4]])
>>> B = np.matrix([[1,2,0],[0,0,3],[1,0,4]])

>>> A
array([[1, 2, 0],
       [0, 0, 3],
       [1, 0, 4]])

>>> sA = sparse.csr_matrix(A)   # Here's the initialization of the sparse matrix.
>>> sB = sparse.csr_matrix(B)

>>> sA
<3x3 sparse matrix of type '<type 'numpy.int32'>'
        with 5 stored elements in Compressed Sparse Row format>

>>> print sA
  (0, 0)        1
  (0, 1)        2
  (1, 2)        3
  (2, 0)        1
  (2, 2)        4

Avoid line break between html elements

There are several ways to prevent line breaks in content. Using &nbsp; is one way, and works fine between words, but using it between an empty element and some text does not have a well-defined effect. The same would apply to the more logical and more accessible approach where you use an image for an icon.

The most robust alternative is to use nobr markup, which is nonstandard but universally supported and works even when CSS is disabled:

<td><nobr><i class="flag-bfh-ES"></i> +34 666 66 66 66</nobr></td>

(You can, but need not, use &nbsp; instead of spaces in this case.)

Another way is the nowrap attribute (deprecated/obsolete, but still working fine, except for some rare quirks):

<td nowrap><i class="flag-bfh-ES"></i> +34 666 66 66 66</td>

Then there’s the CSS way, which works in CSS enabled browsers and needs a bit more code:

<style>
.nobr { white-space: nowrap }
</style>
...
<td class=nobr><i class="flag-bfh-ES"></i> +34 666 66 66 66</td>

Delete specified file from document directory

I want to delete my sqlite db from document directory.I delete the sqlite db successfully by below answer

NSString *strFileName = @"sqlite";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
NSEnumerator *enumerator = [contents objectEnumerator];
NSString *filename;
while ((filename = [enumerator nextObject])) {
    NSLog(@"The file name is - %@",[filename pathExtension]);
    if ([[filename pathExtension] isEqualToString:strFileName]) {
       [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
        NSLog(@"The sqlite is deleted successfully");
    }
}

onClick function of an input type="button" not working

You have to change the ID of the button to be different from the function name JSFiddle

_x000D_
_x000D_
var counter = 0;_x000D_
_x000D_
_x000D_
function moreFields() {_x000D_
  counter++;_x000D_
  var newFields = document.getElementById('readroot').cloneNode(true);_x000D_
  newFields.id = '';_x000D_
  newFields.style.display = 'block';_x000D_
  var newField = newFields.childNodes;_x000D_
  for (var i = 0; i < newField.length; i++) {_x000D_
    var theName = newField[i].name_x000D_
    if (theName) newField[i].name = theName + counter;_x000D_
  }_x000D_
  var insertHere = document.getElementById('writeroot');_x000D_
  insertHere.parentNode.insertBefore(newFields, insertHere);_x000D_
}_x000D_
_x000D_
window.onload = moreFields();
_x000D_
<div id="readroot" style="display: none">_x000D_
  <input type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />_x000D_
  <br />_x000D_
  <br />_x000D_
  <input name="cd" value="title" />_x000D_
  <select name="rankingsel">_x000D_
    <option>Rating</option>_x000D_
    <option value="excellent">Excellent</option>_x000D_
    <option value="good">Good</option>_x000D_
    <option value="ok">OK</option>_x000D_
    <option value="poor">Poor</option>_x000D_
    <option value="bad">Bad</option>_x000D_
  </select>_x000D_
  <br />_x000D_
  <br />_x000D_
  <textarea rows="5" cols="20" name="review">Short review</textarea>_x000D_
  <br />Radio buttons included to test them in Explorer:_x000D_
  <br />_x000D_
  <input type="radio" name="something" value="test1" />Test 1_x000D_
  <br />_x000D_
  <input type="radio" name="something" value="test2" />Test 2</div>_x000D_
<form method="post" action="index1.php"> <span id="writeroot"></span>_x000D_
_x000D_
  <input type="button" onclick="moreFields();" id="moreFieldsButton" value="Give me more fields!" />_x000D_
  <input type="submit" value="Send form" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Excel compare two columns and highlight duplicates

I was trying to compare A-B columns and highlight equal text, but usinng the obove fomrulas some text did not match at all. So I used form (VBA macro to compare two columns and color highlight cell differences) codes and I modified few things to adapt it to my application and find any desired column (just by clicking it). In my case, I use large and different numbers of rows on each column. Hope this helps:

Sub ABTextCompare()

Dim Report As Worksheet
Dim i, j, colNum, vMatch As Integer
Dim lastRowA, lastRowB, lastRow, lastColumn As Integer
Dim ColumnUsage As String
Dim colA, colB, colC As String
Dim A, B, C As Variant

Set Report = Excel.ActiveSheet
vMatch = 1

'Select A and B Columns to compare
On Error Resume Next
 Set A = Application.InputBox(Prompt:="Select column to compare", Title:="Column A", Type:=8)
  If A Is Nothing Then Exit Sub
colA = Split(A(1).Address(1, 0), "$")(0)
 Set B = Application.InputBox(Prompt:="Select column being searched", Title:="Column B", Type:=8)
   If A Is Nothing Then Exit Sub
  colB = Split(B(1).Address(1, 0), "$")(0)
 'Select Column to show results
 Set C = Application.InputBox("Select column  to show results", "Results", Type:=8)
    If C Is Nothing Then Exit Sub
  colC = Split(C(1).Address(1, 0), "$")(0)

'Get Last Row
lastRowA = Report.Cells.Find("", Range(colA & 1), xlFormulas, xlByRows, xlPrevious).Row - 1 ' Last row in column A
lastRowB = Report.Cells.Find("", Range(colB & 1), xlFormulas, xlByRows, xlPrevious).Row - 1 ' Last row in column B

 Application.ScreenUpdating = False
'***************************************************
For i = 2 To lastRowA
      For j = 2 To lastRowB
          If Report.Cells(i, A.Column).Value <> "" Then
              If InStr(1, Report.Cells(j, B.Column).Value, Report.Cells(i, A.Column).Value, vbTextCompare) > 0 Then
                  vMatch = vMatch + 1
                  Report.Cells(i, A.Column).Interior.ColorIndex = 35 'Light green background
                  Range(colC & 1).Value = "Items Found"
                  Report.Cells(i, A.Column).Copy Destination:=Range(colC & vMatch)
                  Exit For
              Else
                  'Do Nothing
              End If
          End If
      Next j
  Next i
If vMatch = 1 Then
    MsgBox Prompt:="No Itmes Found", Buttons:=vbInformation
End If
'***************************************************
Application.ScreenUpdating = True

End Sub

converting CSV/XLS to JSON?

Since Powershell 3.0 (shipped with Windows 8, available for Windows 7 and windows Server 2008 but not Windows Vista ) you can use the built-in convertto-json commandlet:

PS E:> $topicsjson = import-csv .\itinerary-all.csv | ConvertTo-Json 

PS E:\> $topicsjson.Length
11909

PS E:\> $topicsjson.getType()

IsPublic IsSerial Name                                     BaseType                  
-------- -------- ----                                     --------                  
True     True     Object[]                                 System.Array              

Online Help Page on Technet

Stretch image to fit full container width bootstrap

First of all if the size of the image is smaller than the container, then only "img-fluid" class will not solve your problem. you have to set the width of image to 100%, for that you can use Bootstrap class "w-100". keep in mind that "container-fluid" and "col-12" class sets left and right padding to 15px and "row" class sets left and right margin to "-15px" by default. make sure to set them to 0.

Note: "px-0" is a bootstrap class which sets left and right padding to 0 and
"mx-0" is a bootstrap class which sets left and right margin to 0

P.S. i am using Bootstrap 4.0 version.

 <div class="container-fluid px-0">
        <div class="row mx-0">
            <div class="col-12 px-0">
            <img src="images/top.jpg" class="img-fluid w-100">
            </div>
        </div>
    </div>

Reading binary file and looping over each byte

If the file is not too big that holding it in memory is a problem:

with open("filename", "rb") as f:
    bytes_read = f.read()
for b in bytes_read:
    process_byte(b)

where process_byte represents some operation you want to perform on the passed-in byte.

If you want to process a chunk at a time:

with open("filename", "rb") as f:
    bytes_read = f.read(CHUNKSIZE)
    while bytes_read:
        for b in bytes_read:
            process_byte(b)
        bytes_read = f.read(CHUNKSIZE)

The with statement is available in Python 2.5 and greater.

How to detect control+click in Javascript from an onclick div attribute?

From above only , just edited so it works right away

<script>
    var control = false;
    $(document).on('keyup keydown', function (e) {
        control = e.ctrlKey;
    });

    $(function () {
        $('#1x').on('click', function () {
            if (control) {
                // control-click
                alert("Control+Click");
            } else {
                // single-click
                alert("Single Click");
            }
        });
    }); 

</script>
<p id="1x">Click me</p>

Correct way to use StringBuilder in SQL

In the code you have posted there would be no advantages, as you are misusing the StringBuilder. You build the same String in both cases. Using StringBuilder you can avoid the + operation on Strings using the append method. You should use it this way:

return new StringBuilder("select id1, ").append(" id2 ").append(" from ").append(" table").toString();

In Java, the String type is an inmutable sequence of characters, so when you add two Strings the VM creates a new String value with both operands concatenated.

StringBuilder provides a mutable sequence of characters, which you can use to concat different values or variables without creating new String objects, and so it can sometimes be more efficient than working with strings

This provides some useful features, as changing the content of a char sequence passed as parameter inside another method, which you can't do with Strings.

private void addWhereClause(StringBuilder sql, String column, String value) {
   //WARNING: only as an example, never append directly a value to a SQL String, or you'll be exposed to SQL Injection
   sql.append(" where ").append(column).append(" = ").append(value);
}

More info at http://docs.oracle.com/javase/tutorial/java/data/buffers.html

How to increase the timeout period of web service in asp.net?

you can do this in different ways:

  1. Setting a timeout in the web service caller from code (not 100% sure but I think I have seen this done);
  2. Setting a timeout in the constructor of the web service proxy in the web references;
  3. Setting a timeout in the server side, web.config of the web service application.

see here for more details on the second case:

http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14

and here for details on the last case:

How to increase the timeout to a web service request?

cout is not a member of std

I had a similar issue and it turned out that i had to add an extra entry in cmake to include the files.

Since i was also using the zmq library I had to add this to the included libraries as well.

Creating and appending text to txt file in VB.NET

This should work for you without changing program logic (by not outputting "Start error" on the top of each file) like the other answers do :) Remember to add exception handling code.

Dim filePath As String = String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))

Dim fileExists As Boolean = File.Exists(filePath)

Using writer As New StreamWriter(filePath, True)
    If Not fileExists Then
        writer.WriteLine("Start Error Log for today")
    End If
    writer.WriteLine("Error Message in  Occured at-- " & DateTime.Now)
End Using

How can I disable editing cells in a WPF Datagrid?

If you want to disable editing the entire grid, you can set IsReadOnly to true on the grid. If you want to disable user to add new rows, you set the property CanUserAddRows="False"

<DataGrid IsReadOnly="True" CanUserAddRows="False" />

Further more you can set IsReadOnly on individual columns to disable editing.

What is the difference between React Native and React?

React is a declarative, efficient, and flexible JavaScript library for building user interfaces.Your components tell React what you want to render – then React will efficiently update and render just the right components when your data changes. Here, ShoppingList is a React component class, or React component type.

A React Native app is a real mobile app. With React Native, you don't build a “mobile web app”, an “HTML5 app”, or a “hybrid app”. You build a real mobile app that's indistinguishable from an app built using Objective-C or Java. React Native uses the same fundamental UI building blocks as regular iOS and Android apps.

More info

How to disable CSS in Browser for testing purposes

Actually, it's easier than you think. In any browsers press F12 to bring up the debug console. This works for IE, Firefox, and Chrome. Not sure about Opera. Then comment out the CSS in the element windows. That's it.

format a Date column in a Data Frame

The data.table package has its IDate class and functionalities similar to lubridate or the zoo package. You could do:

dt = data.table(
  Name = c('Joe', 'Amy', 'John'),
  JoiningDate = c('12/31/09', '10/28/09', '05/06/10'),
  AmtPaid = c(1000, 100, 200)
)

require(data.table)
dt[ , JoiningDate := as.IDate(JoiningDate, '%m/%d/%y') ]

Check if current date is between two dates Oracle SQL

TSQL: Dates- need to look for gaps in dates between Two Date

select
distinct
e1.enddate,
e3.startdate,
DATEDIFF(DAY,e1.enddate,e3.startdate)-1 as [Datediff]
from #temp e1 
   join #temp e3 on e1.enddate < e3.startdate          
       /* Finds the next start Time */
and e3.startdate = (select min(startdate) from #temp e5
where e5.startdate > e1.enddate)
and not exists (select *  /* Eliminates e1 rows if it is overlapped */
from #temp e5 
where e5.startdate < e1.enddate and e5.enddate > e1.enddate);

How to get the difference between two arrays in JavaScript?

I wanted a similar function which took in an old array and a new array and gave me an array of added items and an array of removed items, and I wanted it to be efficient (so no .contains!).

You can play with my proposed solution here: http://jsbin.com/osewu3/12.

Can anyone see any problems/improvements to that algorithm? Thanks!

Code listing:

function diff(o, n) {
  // deal with empty lists
  if (o == undefined) o = [];
  if (n == undefined) n = [];

  // sort both arrays (or this won't work)
  o.sort(); n.sort();

  // don't compare if either list is empty
  if (o.length == 0 || n.length == 0) return {added: n, removed: o};

  // declare temporary variables
  var op = 0; var np = 0;
  var a = []; var r = [];

  // compare arrays and add to add or remove lists
  while (op < o.length && np < n.length) {
      if (o[op] < n[np]) {
          // push to diff?
          r.push(o[op]);
          op++;
      }
      else if (o[op] > n[np]) {
          // push to diff?
          a.push(n[np]);
          np++;
      }
      else {
          op++;np++;
      }
  }

  // add remaining items
  if( np < n.length )
    a = a.concat(n.slice(np, n.length));
  if( op < o.length )
    r = r.concat(o.slice(op, o.length));

  return {added: a, removed: r}; 
}

SQL get the last date time record

SELECT * FROM table
WHERE Dates IN (SELECT max(Dates) FROM table);

Remove useless zero digits from decimals in PHP

You can use:

print (floatval)(number_format( $Value), 2 ) );    

How do I access refs of a child component in the parent component

  1. Inside the child component add a ref to the node you need
  2. Inside the parent component add a ref to the child component.
/*
* Child component
*/
class Child extends React.Component {
  render() {
    return (
      <div id="child">
        <h1 ref={(node) => { this.heading = node; }}>
          Child
        </h1>
      </div>
    );
  }
}

/*
 * Parent component
 */
class Parent extends React.Component {
  componentDidMount() {
    // Access child component refs via parent component instance like this
    console.log(this.child.heading.getDOMNode());
  }

  render() {
    return (
      <div>
        <Child
          ref={(node) => { this.child = node; }}
        />
      </div>
    );
  }
}

Demo: https://codepen.io/itsfadnis/pen/aLWVVx?editors=0011

Using Jquery Datatable with AngularJs

visit this link for reference:http://codepen.io/kalaiselvan/pen/RRBzda

<script>  
var app=angular.module('formvalid', ['ui.bootstrap','ui.utils']);
app.controller('validationCtrl',function($scope){
  $scope.data=[
        [
            "Tiger Nixon",
            "System Architect",
            "Edinburgh",
            "5421",
            "2011\/04\/25",
            "$320,800"
        ],
        [
            "Garrett Winters",
            "Accountant",
            "Tokyo",
            "8422",
            "2011\/07\/25",
            "$170,750"
        ],
        [
            "Ashton Cox",
            "Junior Technical Author",
            "San Francisco",
            "1562",
            "2009\/01\/12",
            "$86,000"
        ],
        [
            "Cedric Kelly",
            "Senior Javascript Developer",
            "Edinburgh",
            "6224",
            "2012\/03\/29",
            "$433,060"
        ],
        [
            "Airi Satou",
            "Accountant",
            "Tokyo",
            "5407",
            "2008\/11\/28",
            "$162,700"
        ],
        [
            "Brielle Williamson",
            "Integration Specialist",
            "New York",
            "4804",
            "2012\/12\/02",
            "$372,000"
        ],
        [
            "Herrod Chandler",
            "Sales Assistant",
            "San Francisco",
            "9608",
            "2012\/08\/06",
            "$137,500"
        ],
        [
            "Rhona Davidson",
            "Integration Specialist",
            "Tokyo",
            "6200",
            "2010\/10\/14",
            "$327,900"
        ],
        [
            "Colleen Hurst",
            "Javascript Developer",
            "San Francisco",
            "2360",
            "2009\/09\/15",
            "$205,500"
        ],
        [
            "Sonya Frost",
            "Software Engineer",
            "Edinburgh",
            "1667",
            "2008\/12\/13",
            "$103,600"
        ],
        [
            "Jena Gaines",
            "Office Manager",
            "London",
            "3814",
            "2008\/12\/19",
            "$90,560"
        ],
        [
            "Quinn Flynn",
            "Support Lead",
            "Edinburgh",
            "9497",
            "2013\/03\/03",
            "$342,000"
        ],
        [
            "Charde Marshall",
            "Regional Director",
            "San Francisco",
            "6741",
            "2008\/10\/16",
            "$470,600"
        ],
        [
            "Haley Kennedy",
            "Senior Marketing Designer",
            "London",
            "3597",
            "2012\/12\/18",
            "$313,500"
        ],
        [
            "Tatyana Fitzpatrick",
            "Regional Director",
            "London",
            "1965",
            "2010\/03\/17",
            "$385,750"
        ],
        [
            "Michael Silva",
            "Marketing Designer",
            "London",
            "1581",
            "2012\/11\/27",
            "$198,500"
        ],
        [
            "Paul Byrd",
            "Chief Financial Officer (CFO)",
            "New York",
            "3059",
            "2010\/06\/09",
            "$725,000"
        ],
        [
            "Gloria Little",
            "Systems Administrator",
            "New York",
            "1721",
            "2009\/04\/10",
            "$237,500"
        ],
        [
            "Bradley Greer",
            "Software Engineer",
            "London",
            "2558",
            "2012\/10\/13",
            "$132,000"
        ],
        [
            "Dai Rios",
            "Personnel Lead",
            "Edinburgh",
            "2290",
            "2012\/09\/26",
            "$217,500"
        ],
        [
            "Jenette Caldwell",
            "Development Lead",
            "New York",
            "1937",
            "2011\/09\/03",
            "$345,000"
        ],
        [
            "Yuri Berry",
            "Chief Marketing Officer (CMO)",
            "New York",
            "6154",
            "2009\/06\/25",
            "$675,000"
        ],
        [
            "Caesar Vance",
            "Pre-Sales Support",
            "New York",
            "8330",
            "2011\/12\/12",
            "$106,450"
        ],
        [
            "Doris Wilder",
            "Sales Assistant",
            "Sidney",
            "3023",
            "2010\/09\/20",
            "$85,600"
        ],
        [
            "Angelica Ramos",
            "Chief Executive Officer (CEO)",
            "London",
            "5797",
            "2009\/10\/09",
            "$1,200,000"
        ],
        [
            "Gavin Joyce",
            "Developer",
            "Edinburgh",
            "8822",
            "2010\/12\/22",
            "$92,575"
        ],
        [
            "Jennifer Chang",
            "Regional Director",
            "Singapore",
            "9239",
            "2010\/11\/14",
            "$357,650"
        ],
        [
            "Brenden Wagner",
            "Software Engineer",
            "San Francisco",
            "1314",
            "2011\/06\/07",
            "$206,850"
        ],
        [
            "Fiona Green",
            "Chief Operating Officer (COO)",
            "San Francisco",
            "2947",
            "2010\/03\/11",
            "$850,000"
        ],
        [
            "Shou Itou",
            "Regional Marketing",
            "Tokyo",
            "8899",
            "2011\/08\/14",
            "$163,000"
        ],
        [
            "Michelle House",
            "Integration Specialist",
            "Sidney",
            "2769",
            "2011\/06\/02",
            "$95,400"
        ],
        [
            "Suki Burks",
            "Developer",
            "London",
            "6832",
            "2009\/10\/22",
            "$114,500"
        ],
        [
            "Prescott Bartlett",
            "Technical Author",
            "London",
            "3606",
            "2011\/05\/07",
            "$145,000"
        ],
        [
            "Gavin Cortez",
            "Team Leader",
            "San Francisco",
            "2860",
            "2008\/10\/26",
            "$235,500"
        ],
        [
            "Martena Mccray",
            "Post-Sales support",
            "Edinburgh",
            "8240",
            "2011\/03\/09",
            "$324,050"
        ],
        [
            "Unity Butler",
            "Marketing Designer",
            "San Francisco",
            "5384",
            "2009\/12\/09",
            "$85,675"
        ],
        [
            "Howard Hatfield",
            "Office Manager",
            "San Francisco",
            "7031",
            "2008\/12\/16",
            "$164,500"
        ],
        [
            "Hope Fuentes",
            "Secretary",
            "San Francisco",
            "6318",
            "2010\/02\/12",
            "$109,850"
        ],
        [
            "Vivian Harrell",
            "Financial Controller",
            "San Francisco",
            "9422",
            "2009\/02\/14",
            "$452,500"
        ],
        [
            "Timothy Mooney",
            "Office Manager",
            "London",
            "7580",
            "2008\/12\/11",
            "$136,200"
        ],
        [
            "Jackson Bradshaw",
            "Director",
            "New York",
            "1042",
            "2008\/09\/26",
            "$645,750"
        ],
        [
            "Olivia Liang",
            "Support Engineer",
            "Singapore",
            "2120",
            "2011\/02\/03",
            "$234,500"
        ],
        [
            "Bruno Nash",
            "Software Engineer",
            "London",
            "6222",
            "2011\/05\/03",
            "$163,500"
        ],
        [
            "Sakura Yamamoto",
            "Support Engineer",
            "Tokyo",
            "9383",
            "2009\/08\/19",
            "$139,575"
        ],
        [
            "Thor Walton",
            "Developer",
            "New York",
            "8327",
            "2013\/08\/11",
            "$98,540"
        ],
        [
            "Finn Camacho",
            "Support Engineer",
            "San Francisco",
            "2927",
            "2009\/07\/07",
            "$87,500"
        ],
        [
            "Serge Baldwin",
            "Data Coordinator",
            "Singapore",
            "8352",
            "2012\/04\/09",
            "$138,575"
        ],
        [
            "Zenaida Frank",
            "Software Engineer",
            "New York",
            "7439",
            "2010\/01\/04",
            "$125,250"
        ],
        [
            "Zorita Serrano",
            "Software Engineer",
            "San Francisco",
            "4389",
            "2012\/06\/01",
            "$115,000"
        ],
        [
            "Jennifer Acosta",
            "Junior Javascript Developer",
            "Edinburgh",
            "3431",
            "2013\/02\/01",
            "$75,650"
        ],
        [
            "Cara Stevens",
            "Sales Assistant",
            "New York",
            "3990",
            "2011\/12\/06",
            "$145,600"
        ],
        [
            "Hermione Butler",
            "Regional Director",
            "London",
            "1016",
            "2011\/03\/21",
            "$356,250"
        ],
        [
            "Lael Greer",
            "Systems Administrator",
            "London",
            "6733",
            "2009\/02\/27",
            "$103,500"
        ],
        [
            "Jonas Alexander",
            "Developer",
            "San Francisco",
            "8196",
            "2010\/07\/14",
            "$86,500"
        ],
        [
            "Shad Decker",
            "Regional Director",
            "Edinburgh",
            "6373",
            "2008\/11\/13",
            "$183,000"
        ],
        [
            "Michael Bruce",
            "Javascript Developer",
            "Singapore",
            "5384",
            "2011\/06\/27",
            "$183,000"
        ],
        [
            "Donna Snider",
            "Customer Support",
            "New York",
            "4226",
            "2011\/01\/25",
            "$112,000"
        ]
    ]


$scope.dataTableOpt = {
  //if any ajax call 
  };
});
</script>
<div class="container" ng-app="formvalid">
      <div class="panel" data-ng-controller="validationCtrl">
      <div class="panel-heading border">    
        <h2>Data table using jquery datatable in Angularjs </h2>
      </div>
      <div class="panel-body">
          <table class="table table-bordered bordered table-striped table-condensed datatable" ui-jq="dataTable" ui-options="dataTableOpt">
          <thead>
            <tr>
              <th>#</th>
              <th>Name</th>
              <th>Position</th>
              <th>Office</th>
              <th>Age</th>
              <th>Start Date</th>
            </tr>
          </thead>
            <tbody>
              <tr ng-repeat="n in data">
                <td>{{$index+1}}</td>
                <td>{{n[0]}}</td>
                <td>{{n[1]}}</td>
                <td>{{n[2]}}</td>
                <td>{{n[3]}}</td>
                <td>{{n[4] | date:'dd/MM/yyyy'}}</td>
              </tr>
            </tbody>
        </table>
      </div>
    </div>
    </div>

How do browser cookie domains work?

The last (third to be exactly) RFC for this issue is RFC-6265 (Obsoletes RFC-2965 that in turn obsoletes RFC-2109).

According to it if the server omits the Domain attribute, the user agent will return the cookie only to the origin server (the server on which a given resource resides). But it's also warning that some existing user agents treat an absent Domain attribute as if the Domain attribute were present and contained the current host name (For example, if example.com returns a Set-Cookie header without a Domain attribute, these user agents will erroneously send the cookie to www.example.com as well).

When the Domain attribute have been specified, it will be treated as complete domain name (if there is the leading dot in attribute it will be ignored). Server should match the domain specified in attribute (have exactly the same domain name or to be a subdomain of it) to get this cookie. More accurately it specified here.

So, for example:

  • cookie attribute Domain=.example.com is equivalent to Domain=example.com
  • cookies with such Domain attributes will be available for example.com and www.example.com
  • cookies with such Domain attributes will be not available for another-example.com
  • specifying cookie attribute like Domain=www.example.com will close the way for www4.example.com

PS: trailing comma in Domain attribute will cause the user agent to ignore the attribute =(

how to get the selected index of a drop down

the actual index is available as a property of the select element.

var sel = document.getElementById('CCards');
alert(sel.selectedIndex);

you can use the index to get to the selection option, where you can pull the text and value.

var opt = sel.options[sel.selectedIndex];
alert(opt.text);
alert(opt.value);

Converting String to Int with Swift

Swift5 float or int string to int:

extension String {
    func convertStringToInt() -> Int {
        return Int(Double(self) ?? 0.0)
    }
}

let doubleStr = "4.2"
// print 4
print(doubleStr.convertStringToInt())

let intStr = "4"
// print 4
print(intStr.convertStringToInt())

how do you filter pandas dataframes by multiple columns

Using & operator, don't forget to wrap the sub-statements with ():

males = df[(df[Gender]=='Male') & (df[Year]==2014)]

To store your dataframes in a dict using a for loop:

from collections import defaultdict
dic={}
for g in ['male', 'female']:
  dic[g]=defaultdict(dict)
  for y in [2013, 2014]:
    dic[g][y]=df[(df[Gender]==g) & (df[Year]==y)] #store the DataFrames to a dict of dict

EDIT:

A demo for your getDF:

def getDF(dic, gender, year):
  return dic[gender][year]

print genDF(dic, 'male', 2014)

Secure hash and salt for PHP passwords

Though the question has been answered, I just want to reiterate that salts used for hashing should be random and not like email address as suggested in first answer.

More explanation is available at- http://www.pivotalsecurity.com/blog/password-hashing-salt-should-it-be-random/

Recently I had a discussion whether password hashes salted with random bits are more secure than the one salted with guessable or known salts. Let’s see: If the system storing password is compromised as well as the system which stores the random salt, the attacker will have access to hash as well as salt, so whether the salt is random or not, doesn’t matter. The attacker will can generate pre-computed rainbow tables to crack the hash. Here comes the interesting part- it is not so trivial to generate pre-computed tables. Let us take example of WPA security model. Your WPA password is actually never sent to Wireless Access Point. Instead, it is hashed with your SSID (the network name- like Linksys, Dlink etc). A very good explanation of how this works is here. In order to retrieve password from hash, you will need to know the password as well as salt (network name). Church of Wifi has already pre-computed hash tables which has top 1000 SSIDs and about 1 million passwords. The size is of all tables is about 40 GB. As you can read on their site, someone used 15 FGPA arrays for 3 days to generate these tables. Assuming victim is using the SSID as “a387csf3" and password as “123456", will it be cracked by those tables? No! .. it cannot. Even if the password is weak, the tables don’t have hashes for SSID a387csf3. This is the beauty of having random salt. It will deter crackers who thrive upon pre-computed tables. Can it stop a determined hacker? Probably not. But using random salts does provide additional layer of defense. While we are on this topic, let us discuss additional advantage of storing random salts on a separate system. Scenario #1 : Password hashes are stored on system X and salt values used for hashing are stored on system Y. These salt values are guessable or known (e.g. username) Scenario#2 : Password hashes are stored on system X and salt values used for hashing are stored on system Y. These salt values are random. In case system X has been compromised, as you can guess, there is a huge advantage of using random salt on a separate system (Scenario #2) . The attacker will need to guess addition values to be able to crack hashes. If a 32 bit salt is used, 2^32= 4,294,967,296 (about 4.2 billion) iterations will can be required for each password guessed.

datetime dtypes in pandas read_csv

I tried using the dtypes=[datetime, ...] option, but

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime, datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

I encountered the following error:

TypeError: data type not understood

The only change I had to make is to replace datetime with datetime.datetime

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime.datetime, datetime.datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

SQL NVARCHAR and VARCHAR Limits

You mus use nvarchar text too. that's mean you have to simply had a "N" before your massive string and that's it! no limitation anymore

DELARE @SQL NVARCHAR(MAX);
SET @SQL = N'SomeMassiveString > 4000 chars...';
EXEC(@SQL);
GO

How do I install a module globally using npm?

On a Mac, I found the output contained the information I was looking for:

$> npm install -g karma
...
...
> [email protected] install /usr/local/share/npm/lib/node_modules/karma/node_modules/socket.io/node_modules/socket.io-client/node_modules/ws
> (node-gyp rebuild 2> builderror.log) || (exit 0)
...
$> ls /usr/local/share/npm/bin
karma nf

After adding /usr/local/share/npm/bin to the export PATH line in my .bash_profile, saving it, and sourceing it, I was able to run

$> karma --help

normally.

How to filter array when object key value is in array

In case you have key value pairs in your input array, I used:

.filter(
          this.multi_items[0] != null && store.state.isSearchBox === false
            ? item =>
                _.map(this.multi_items, "value").includes(item["wijknaam"])
            : item => item["wijknaam"].includes("")
        );

where the input array is multi_items as: [{"text": "bla1", "value": "green"}, {"text": etc. etc.}]

_.map is a lodash function.

Use a normal link to submit a form

You can't really do this without some form of scripting to the best of my knowledge.

<form id="my_form">
<!-- Your Form -->    
<a href="javascript:{}" onclick="document.getElementById('my_form').submit(); return false;">submit</a>
</form>

Example from Here.

Twitter Bootstrap - add top space between rows

<div class="row row-padding">

simple code

Creating a LINQ select from multiple tables

If the anonymous type causes trouble for you, you can create a simple data class:

public class PermissionsAndPages
{
     public ObjectPermissions Permissions {get;set}
     public Pages Pages {get;set}
}

and then in your query:

select new PermissionsAndPages { Permissions = op, Page = pg };

Then you can pass this around:

return queryResult.SingleOrDefault(); // as PermissionsAndPages

Can an Android App connect directly to an online mysql database

Yes definitely you can connect to the MySql online database for that you need to create a web service. This web service will provide you access to the MySql database. Then you can easily pull and push data to MySql Database. PHP will be a good option for creating web service its simple to implement. Good luck...

Should I use PATCH or PUT in my REST API?

The PATCH method is the correct choice here as you're updating an existing resource - the group ID. PUT should only be used if you're replacing a resource in its entirety.

Further information on partial resource modification is available in RFC 5789. Specifically, the PUT method is described as follows:

Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

href="file://" doesn't work

%20 is the space between AmberCRO SOP.

Try -

href="http://file:///K:/AmberCRO SOP/2011-07-05/SOP-SOP-3.0.pdf"

Or rename the folder as AmberCRO-SOP and write it as -

href="http://file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf"

PHP function to get the subdomain of a URL

Simply...

    preg_match('/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i', $url, $match);

Just read $match[1]

Working example

It works perfectly with this list of urls

$url = array(
    'http://www.domain.com', // www
    'http://domain.com', // --nothing--
    'https://domain.com', // --nothing--
    'www.domain.com', // www
    'domain.com', // --nothing--
    'www.domain.com/some/path', // www
    'http://sub.domain.com/domain.com', // sub
    '???????????????.????????.ua', // ??????????????? ;)
    '????????.ua', // --nothing--
    'http://sub-domain.domain.net/domain.net', // sub-domain
    'sub-domain.third-Level_DomaIN.domain.uk.co/domain.net' // sub-domain
);

foreach ($url as $u) {
    preg_match('/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i', $u, $match);
    var_dump($match);
}

twitter bootstrap 3.0 typeahead ajax example

Here is my step by step experience, inspired by typeahead examples, from a Scala/PlayFramework app we are working on.

In a script LearnerNameTypeAhead.coffee (convertible of course to JS) I have:

$ ->
  learners = new Bloodhound(
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value")
    queryTokenizer: Bloodhound.tokenizers.whitespace
    remote: "/learner/namelike?nameLikeStr=%QUERY"
  )
  learners.initialize()
  $("#firstName").typeahead 
    minLength: 3
    hint: true
    highlight:true
   ,
    name: "learners"
    displayKey: "value"
    source: learners.ttAdapter()

I included the typeahead bundle and my script on the page, and there is a div around my input field as follows:

<script [email protected]("javascripts/typeahead.bundle.js")></script>
<script [email protected]("javascripts/LearnerNameTypeAhead.js") type="text/javascript" ></script>
<div>
  <input name="firstName" id="firstName" class="typeahead" placeholder="First Name" value="@firstName">
</div>

The result is that for each character typed in the input field after the first minLength (3) characters, the page issues a GET request with a URL looking like /learner/namelike?nameLikeStr= plus the currently typed characters. The server code returns a json array of objects containing fields "id" and "value", for example like this:

[ {
    "id": "109",
    "value": "Graham Jones"
  },
  {
    "id": "5833",
    "value": "Hezekiah Jones"
} ]

For play I need something in the routes file:

GET /learner/namelike controllers.Learners.namesLike(nameLikeStr:String)

And finally, I set some of the styling for the dropdown, etc. in a new typeahead.css file which I included in the page's <head> (or accessible .css)

.tt-dropdown-menu {
  width: 252px;
  margin-top: 12px;
  padding: 8px 0;
  background-color: #fff;
  border: 1px solid #ccc;
  border: 1px solid rgba(0, 0, 0, 0.2);
  -webkit-border-radius: 8px;
     -moz-border-radius: 8px;
          border-radius: 8px;
  -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
     -moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
          box-shadow: 0 5px 10px rgba(0,0,0,.2);
}
.typeahead {
  background-color: #fff;
}
.typeahead:focus {
  border: 2px solid #0097cf;
}
.tt-query {
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
     -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.tt-hint {
  color: #999
}
.tt-suggestion {
  padding: 3px 20px;
  font-size: 18px;
  line-height: 24px;
}
.tt-suggestion.tt-cursor {
  color: #fff;
  background-color: #0097cf;
}
.tt-suggestion p {
  margin: 0;
}

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

If your system is using SELinux, make sure that you use the right context for the directory you created:

ls -dZ /data/db/
ls -dZ /var/lib/mongo/

and clone the context with:

chcon -R --reference=/var/lib/mongo /data/db

Service vs IntentService in the Android platform

Android IntentService vs Service

1.Service

  • A Service is invoked using startService().
  • A Service can be invoked from any thread.
  • A Service runs background operations on the Main Thread of the Application by default. Hence it can block your Application’s UI.
  • A Service invoked multiple times would create multiple instances.
  • A service needs to be stopped using stopSelf() or stopService().
  • Android service can run parallel operations.

2. IntentService

  • An IntentService is invoked using Intent.
  • An IntentService can in invoked from the Main thread only.
  • An IntentService creates a separate worker thread to run background operations.
  • An IntentService invoked multiple times won’t create multiple instances.
  • An IntentService automatically stops after the queue is completed. No need to trigger stopService() or stopSelf().
  • In an IntentService, multiple intent calls are automatically Queued and they would be executed sequentially.
  • An IntentService cannot run parallel operation like a Service.

Refer from Here

Check if datetime instance falls in between other two datetime objects

DateTime.Ticks will account for the time. Use .Ticks on the DateTime to convert your dates into longs. Then just use a simple if stmt to see if your target date falls between.

// Assuming you know d2 > d1
if (targetDt.Ticks > d1.Ticks && targetDt.Ticks < d2.Ticks)
{
    // targetDt is in between d1 and d2
}  

Responsive table handling in Twitter Bootstrap

Bootstrap 3 now has Responsive tables out of the box. Hooray! :)

You can check it here: https://getbootstrap.com/docs/3.3/css/#tables-responsive

Add a <div class="table-responsive"> surrounding your table and you should be good to go:

<div class="table-responsive">
  <table class="table">
    ...
  </table>
</div>

To make it work on all layouts you can do this:

.table-responsive
{
    overflow-x: auto;
}

in python how do I convert a single digit number into a double digits string?

Branching off of Mohommad's answer:

str_years = [x for x in range(24)]
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

#Or, if you're starting with ints:
int_years = [int(x) for x in str_years]

#Formatted here
form_years = ["%02d" % x for x in int_years]

print(form_years)
#['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']

Clear text area

When you do $("#vinanghinguyen_images_bbocde").val('');, it removes all the content of the textarea, so if that's not what is happening, the problem is probably somewhere else.

It might help if you post a little bit larger portion of your code, since the example you provided works.

How to part DATE and TIME from DATETIME in MySQL

You can achieve that using DATE_FORMAT() (click the link for more other formats)

SELECT DATE_FORMAT(colName, '%Y-%m-%d') DATEONLY, 
       DATE_FORMAT(colName,'%H:%i:%s') TIMEONLY

SQLFiddle Demo

jQuery and TinyMCE: textarea value doesn't submit

You can also simply use the jQuery plugin and package for TinyMCE it sorts out these kinds of issues.

How to install pip for Python 3 on Mac OS X?

I had the same problem with python3 and pip3. Decision: solving all conflicts with links and other stuff when do

brew doctor

After that

brew reinstall python3

Delete last char of string

In C# 8 ranges and indices were introduced, giving us a new more succinct solution:

strgroupids = strgroupids[..^1];

How to get the path of a running JAR file?

Try this:

String path = new File("").getAbsolutePath();

How to run a method every X seconds

The solution you will use really depends on how long you need to wait between each execution of your function.

If you are waiting for longer than 10 minutes, I would suggest using AlarmManager.

// Some time when you want to run
Date when = new Date(System.currentTimeMillis());

try {
    Intent someIntent = new Intent(someContext, MyReceiver.class); // intent to be launched

    // Note: this could be getActivity if you want to launch an activity
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
        context,
        0, // id (optional)
        someIntent, // intent to launch
        PendingIntent.FLAG_CANCEL_CURRENT // PendingIntent flag
    );

    AlarmManager alarms = (AlarmManager) context.getSystemService(
        Context.ALARM_SERVICE
    );

    alarms.setRepeating(
        AlarmManager.RTC_WAKEUP,
        when.getTime(),
        AlarmManager.INTERVAL_FIFTEEN_MINUTES,
        pendingIntent
    );
} catch(Exception e) {
    e.printStackTrace();
}

Once you have broadcasted the above Intent, you can receive your Intent by implementing a BroadcastReceiver. Note that this will need to be registered either in your application manifest or via the context.registerReceiver(receiver, intentFilter); method. For more information on BroadcastReceiver's please refer to the official documentation..

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent)
    {
        System.out.println("MyReceiver: here!") // Do your work here
    }
}

If you are waiting for shorter than 10 minutes then I would suggest using a Handler.

final Handler handler = new Handler();
final int delay = 1000; // 1000 milliseconds == 1 second

handler.postDelayed(new Runnable() {
    public void run() {
        System.out.println("myHandler: here!"); // Do your work here
        handler.postDelayed(this, delay);
    }
}, delay);

Running a simple shell script as a cronjob

What directory is file.txt in? cron runs jobs in your home directory, so unless your script cds somewhere else, that's where it's going to look for/create file.txt.

EDIT: When you refer to a file without specifying its full path (e.g. file.txt, as opposed to the full path /home/myUser/scripts/file.txt) in shell, it's taken that you're referring to a file in your current working directory. When you run a script (whether interactively or via crontab), the script's working directory has nothing at all to do with the location of the script itself; instead, it's inherited from whatever ran the script.

Thus, if you cd (change working directory) to the directory the script's in and then run it, file.txt will refer to a file in the same directory as the script. But if you don't cd there first, file.txt will refer to a file in whatever directory you happen to be in when you ran the script. For instance, if your home directory is /home/myUser, and you open a new shell and immediately run the script (as scripts/test.sh or /home/myUser/scripts/test.sh; ./test.sh won't work), it'll touch the file /home/myUser/file.txt because /home/myUser is your current working directory (and therefore the script's).

When you run a script from cron, it does essentially the same thing: it runs it with the working directory set to your home directory. Thus all file references in the script are taken relative to your home directory, unless the script cds somewhere else or specifies an absolute path to the file.

Show/hide 'div' using JavaScript

I found this question and recently I was implementing some UIs using Vue.js so this can be a good alternative.

First your code is not hiding target when you click on View Profile. You are overriding the content target with div2.

_x000D_
_x000D_
let multiple = new Vue({_x000D_
  el: "#multiple",_x000D_
  data: {_x000D_
    items: [{_x000D_
        id: 0,_x000D_
        name: 'View Profile',_x000D_
        desc: 'Show profile',_x000D_
        show: false,_x000D_
      },_x000D_
      {_x000D_
        id: 1,_x000D_
        name: 'View Results',_x000D_
        desc: 'Show results',_x000D_
        show: false,_x000D_
      },_x000D_
    ],_x000D_
    selected: '',_x000D_
    shown: false,_x000D_
  },_x000D_
  methods: {_x000D_
    showItem: function(item) {_x000D_
      if (this.selected && this.selected.id === item.id) {_x000D_
        item.show = item.show && this.shown ? false : !item.show;_x000D_
      } else {_x000D_
        item.show = (this.selected.show || !item.show) && this.shown ? true : !this.shown;_x000D_
      }_x000D_
      this.shown = item.show;_x000D_
      this.selected = item;_x000D_
    },_x000D_
  },_x000D_
});
_x000D_
<div id="multiple">_x000D_
  <button type="button" v-for="item in items" v-on:click="showItem(item)">{{item.name}}</button>_x000D_
_x000D_
  <div class="" v-if="shown">: {{selected.desc}}</div>_x000D_
</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.7/vue.js"></script>
_x000D_
_x000D_
_x000D_

How to open local file on Jupyter?

Here's a possibile solution (in Python):

Let's say you have a notebook with a file name, call it Notebook.ipynb. You are currently working in that notebook, and want to access other folders and files around it. Here's it's path:

import os
notebook_path = os.path.abspath("Notebook.ipynb")

In other words, just use the os module, and get the absolute path of your notebook (it's a file, too!). From there, use the os module and your path to navigate.

For example, if your train.csv is in a folder called 'Datasets', and the notebook is sitting right next to that folder, you could get the data like this:

train_csv = os.path.join(os.path.dirname(notebook_path), "Datasets/train.csv")
with open(train_csv) as file:
    #....etc

The takeaway is that the notebook has a file name, and as long as your language supports pathname manipulations (e.g. the os module in Python) you can likely use the notebook filename.

Lastly, the reason your code fails is probably because you're either trying to access local files (like your Mac's 'Downloads' folder) when you're working in an online Notebook (like Kaggle, which hosts your environment for you, online and away from your Mac), or you moved or deleted something in that path. This is what the os module in Python is meant to do; it will find the file's path whether it's on your Mac or in a Kaggle server.

Python - OpenCV - imread - Displaying Image

Looks like the image is too big and the window simply doesn't fit the screen. Create window with the cv2.WINDOW_NORMAL flag, it will make it scalable. Then you can resize it to fit your screen like this:

from __future__ import division
import cv2


img = cv2.imread('1.jpg')

screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)

cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)

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

According to the OpenCV documentation CV_WINDOW_KEEPRATIO flag should do the same, yet it doesn't and it's value not even presented in the python module.

Disable future dates after today in Jquery Ui Datepicker

You can simply do this

$(function() {
    $( "#datepicker" ).datepicker({  maxDate: new Date });
  });

JSFiddle

FYI: while checking the documentation, found that it also accepts numeric values too.

Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.

so 0 represents today. Therefore you can do this too

 $( "#datepicker" ).datepicker({  maxDate: 0 });

Perform commands over ssh with Python

paramiko finally worked for me after adding additional line, which is really important one (line 3):

import paramiko

p = paramiko.SSHClient()
p.set_missing_host_key_policy(paramiko.AutoAddPolicy())   # This script doesn't work for me unless this line is added!
p.connect("server", port=22, username="username", password="password")
stdin, stdout, stderr = p.exec_command("your command")
opt = stdout.readlines()
opt = "".join(opt)
print(opt)

Make sure that paramiko package is installed. Original source of the solution: Source

makefile:4: *** missing separator. Stop

Using .editorconfig to fix the tabs automagically:

root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4

[Makefile]
indent_style = tab

Why is &#65279; appearing in my HTML?

yeah, its so simple to fix that, just open that file by notepad++ and step follow --> Encoding\ encoding UTF-8 without BOM. then save that. It work for me as well!

C++ vector's insert & push_back difference

The biggest difference is their functionality. push_back always puts a new element at the end of the vector and insert allows you to select new element's position. This impacts the performance. vector elements are moved in the memory only when it's necessary to increase it's length because too little memory was allocated for it. On the other hand insert forces to move all elements after the selected position of a new element. You simply have to make a place for it. This is why insert might often be less efficient than push_back.

Setting selected values for ng-options bound select elements

If using AngularJS 1.2 you can use 'track by' to tell Angular how to compare objects.

<select 
    ng-model="Choice.SelectedOption"                 
    ng-options="choice.Name for choice in Choice.Options track by choice.ID">
</select>

Updated fiddle http://jsfiddle.net/gFCzV/34/

What is the difference between a definition and a declaration?

A declaration introduces an identifier and describes its type, be it a type, object, or function. A declaration is what the compiler needs to accept references to that identifier. These are declarations:

extern int bar;
extern int g(int, int);
double f(int, double); // extern can be omitted for function declarations
class foo; // no extern allowed for type declarations

A definition actually instantiates/implements this identifier. It's what the linker needs in order to link references to those entities. These are definitions corresponding to the above declarations:

int bar;
int g(int lhs, int rhs) {return lhs*rhs;}
double f(int i, double d) {return i+d;}
class foo {};

A definition can be used in the place of a declaration.

An identifier can be declared as often as you want. Thus, the following is legal in C and C++:

double f(int, double);
double f(int, double);
extern double f(int, double); // the same as the two above
extern double f(int, double);

However, it must be defined exactly once. If you forget to define something that's been declared and referenced somewhere, then the linker doesn't know what to link references to and complains about a missing symbols. If you define something more than once, then the linker doesn't know which of the definitions to link references to and complains about duplicated symbols.


Since the debate what is a class declaration vs. a class definition in C++ keeps coming up (in answers and comments to other questions) , I'll paste a quote from the C++ standard here.
At 3.1/2, C++03 says:

A declaration is a definition unless it [...] is a class name declaration [...].

3.1/3 then gives a few examples. Amongst them:

[Example: [...]
struct S { int a; int b; }; // defines S, S::a, and S::b [...]
struct S; // declares S
—end example

To sum it up: The C++ standard considers struct x; to be a declaration and struct x {}; a definition. (In other words, "forward declaration" a misnomer, since there are no other forms of class declarations in C++.)

Thanks to litb (Johannes Schaub) who dug out the actual chapter and verse in one of his answers.

How to loop through an array containing objects and access their properties

Some use cases of looping through an array in the functional programming way in JavaScript:

1. Just loop through an array

const myArray = [{x:100}, {x:200}, {x:300}];

myArray.forEach((element, index, array) => {
    console.log(element.x); // 100, 200, 300
    console.log(index); // 0, 1, 2
    console.log(array); // same myArray object 3 times
});

Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.

2. Check if any of the elements in an array pass a test

const people = [
    {name: 'John', age: 23}, 
    {name: 'Andrew', age: 3}, 
    {name: 'Peter', age: 8}, 
    {name: 'Hanna', age: 14}, 
    {name: 'Adam', age: 37}];

const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true

3. Transform to a new array

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]

Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.

4. Sum up a particular property, and calculate its average

const myArray = [{x:100}, {x:200}, {x:300}];

const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300

const average = sum / myArray.length;
console.log(average); // 200

5. Create a new array based on the original but without modifying it

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => {
    return {
        ...element,
        x: element.x * 2
    };
});

console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]

6. Count the number of each category

const people = [
    {name: 'John', group: 'A'}, 
    {name: 'Andrew', group: 'C'}, 
    {name: 'Peter', group: 'A'}, 
    {name: 'James', group: 'B'}, 
    {name: 'Hanna', group: 'A'}, 
    {name: 'Adam', group: 'B'}];

const groupInfo = people.reduce((groups, person) => {
    const {A = 0, B = 0, C = 0} = groups;
    if (person.group === 'A') {
        return {...groups, A: A + 1};
    } else if (person.group === 'B') {
        return {...groups, B: B + 1};
    } else {
        return {...groups, C: C + 1};
    }
}, {});

console.log(groupInfo); // {A: 3, C: 1, B: 2}

7. Retrieve a subset of an array based on particular criteria

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}] 

Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.

8. Sort an array

const people = [
  { name: "John", age: 21 },
  { name: "Peter", age: 31 },
  { name: "Andrew", age: 29 },
  { name: "Thomas", age: 25 }
];

let sortByAge = people.sort(function (p1, p2) {
  return p1.age - p2.age;
});

console.log(sortByAge);

enter image description here

9. Find an element in an array

const people = [ {name: "john", age:23},
                {name: "john", age:43},
                {name: "jim", age:101},
                {name: "bob", age:67} ];

const john = people.find(person => person.name === 'john');
console.log(john);

enter image description here

The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.

References

Read XML file into XmlDocument

XmlDocument doc = new XmlDocument();
   doc.Load("MonFichierXML.xml");

    XmlNode node = doc.SelectSingleNode("Magasin");

    XmlNodeList prop = node.SelectNodes("Items");

    foreach (XmlNode item in prop)
    {
        items Temp = new items();
        Temp.AssignInfo(item);
        lstitems.Add(Temp);
    }

Python debugging tips

PDB

You can use the pdb module, insert pdb.set_trace() anywhere and it will function as a breakpoint.

>>> import pdb
>>> a="a string"
>>> pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb) p a
'a string'
(Pdb)

To continue execution use c (or cont or continue).

It is possible to execute arbitrary Python expressions using pdb. For example, if you find a mistake, you can correct the code, then type a type expression to have the same effect in the running code

ipdb is a version of pdb for IPython. It allows the use of pdb with all the IPython features including tab completion.

It is also possible to set pdb to automatically run on an uncaught exception.

Pydb was written to be an enhanced version of Pdb. Benefits?

dropping rows from dataframe based on a "not in" condition

You can use pandas.Dataframe.isin.

pandas.Dateframe.isin will return boolean values depending on whether each element is inside the list a or not. You then invert this with the ~ to convert True to False and vice versa.

import pandas as pd

a = ['2015-01-01' , '2015-02-01']

df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})

print(df)
#         date
#0  2015-01-01
#1  2015-02-01
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

df = df[~df['date'].isin(a)]

print(df)
#         date
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

Get single row result with Doctrine NativeQuery

Both getSingleResult() and getOneOrNullResult() will throw an exception if there is more than one result. To fix this problem you could add setMaxResults(1) to your query builder.

 $firstSubscriber = $entity->createQueryBuilder()->select('sub')
        ->from("\Application\Entity\Subscriber", 'sub')
        ->where('sub.subscribe=:isSubscribe')
        ->setParameter('isSubscribe', 1)  
        ->setMaxResults(1)
        ->getQuery()
        ->getOneOrNullResult();

Add IIS 7 AppPool Identities as SQL Server Logons

The "IIS APPPOOL\AppPoolName" will work, but as mentioned previously, it does not appear to be a valid AD name so when you search for it in the "Select User or Group" dialog box, it won't show up (actually, it will find it, but it will think its an actual system account, and it will try to treat it as such...which won't work, and will give you the error message about it not being found).

How I've gotten it to work is:

  1. In SQL Server Management Studio, look for the Security folder (the security folder at the same level as the Databases, Server Objects, etc. folders...not the security folder within each individual database)
  2. Right click logins and select "New Login"
  3. In the Login name field, type IIS APPPOOL\YourAppPoolName - do not click search
  4. Fill whatever other values you like (i.e., authentication type, default database, etc.)
  5. Click OK

As long as the AppPool name actually exists, the login should now be created.

Vue template or render function not defined yet I am using neither?

If you used to calle a component like this:

Vue.component('dashboard', require('./components/Dashboard.vue'));

I suppose that problem occurred when you update to laravel mix 5.0 or another libraries, so you have to put .default. As like below:

Vue.component('dashboard', require('./components/Dashboard.vue').default);

I solved the same problem.

How to get a substring of text?

if you need it in rails you can use first (source code)

'1234567890'.first(5) # => "12345"

there is also last (source code)

'1234567890'.last(2) # => "90"

alternatively check from/to (source code):

"hello".from(1).to(-2) # => "ell"

Package structure for a Java project?

The way i usually have my hierarchy of folder-

  • Project Name
    • src
    • bin
    • tests
    • libs
    • docs

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

For me everything else was almost ok, but somehow my project settings changed & iisExpress was getting used instead of IISLocal. When I changed & pointed to the virtual directory (in IISLocal), it stared working perfectly again.

Disable button in jQuery

Here's how you do it with ajax.

$("#updatebtn").click(function () {
    $("#updatebtn").prop("disabled", true);
    urlToHandler = 'update.ashx';
            jsonData = data;
            $.ajax({
                url: urlToHandler,
                data: jsonData,
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json',
                success: function (data) {
                    $("#lbl").html(data.response);
                    $("#updatebtn").prop("disabled", false);
                    //setAutocompleteData(data.response);
                },
                error: function (data, status, jqXHR) {
                    alert('There was an error.');
                    $("#updatebtn").prop("disabled", false);
                }
            }); // end $.ajax

ng-options with simple array init

<select ng-model="option" ng-options="o for o in options">

$scope.option will be equal to 'var1' after change, even you see value="0" in generated html

plunker

Determining if an Object is of primitive type

I'm late to the show, but if you're testing a field, you can use getGenericType:

import static org.junit.Assert.*;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;

import org.junit.Test;

public class PrimitiveVsObjectTest {

    private static final Collection<String> PRIMITIVE_TYPES = 
            new HashSet<>(Arrays.asList("byte", "short", "int", "long", "float", "double", "boolean", "char"));

    private static boolean isPrimitive(Type type) {
        return PRIMITIVE_TYPES.contains(type.getTypeName());
    }

    public int i1 = 34;
    public Integer i2 = 34;

    @Test
    public void primitive_type() throws NoSuchFieldException, SecurityException {
        Field i1Field = PrimitiveVsObjectTest.class.getField("i1");
        Type genericType1 = i1Field.getGenericType();
        assertEquals("int", genericType1.getTypeName());
        assertNotEquals("java.lang.Integer", genericType1.getTypeName());
        assertTrue(isPrimitive(genericType1));
    }

    @Test
    public void object_type() throws NoSuchFieldException, SecurityException {
        Field i2Field = PrimitiveVsObjectTest.class.getField("i2");
        Type genericType2 = i2Field.getGenericType();
        assertEquals("java.lang.Integer", genericType2.getTypeName());
        assertNotEquals("int", genericType2.getTypeName());
        assertFalse(isPrimitive(genericType2));
    }
}

The Oracle docs list the 8 primitive types.

Laravel - Form Input - Multiple select for a one to many relationship

Laravel 4.2

@SamMonk gave the best alternative, I followed his example and build the final piece of code

<select class="chosen-select" multiple="multiple" name="places[]" id="places">
    @foreach($places as $place)
        <option value="{{$place->id}}" @foreach($job->places as $p) @if($place->id == $p->id)selected="selected"@endif @endforeach>{{$place->name}}</option>
    @endforeach
</select>

In my project I'm going to have many table relationships like this so I wrote an extension to keep it clean. To load it, put it in some configuration file like "app/start/global.php". I've created a file "macros.php" under "app/" directory and included it in the EOF of global.php

// app/start/global.php
require app_path().'/macros.php';

// macros.php
Form::macro("chosen", function($name, $defaults = array(), $selected = array(), $options = array()){

    // For empty Input::old($name) session, $selected is an empty string
    if(!$selected) $selected = array();

    $opts = array(
        'class' => 'chosen-select',
        'id' => $name,
        'name' => $name . '[]',
        'multiple' => true
    );
    $options = array_merge($opts, $options);
    $attributes = HTML::attributes($options);

    // need an empty array to send if all values are unselected
    $ret = '<input type="hidden" name="' . HTML::entities($name) . '[]">';
    $ret .= '<select ' . $attributes . '>';
    foreach($defaults as $def) {
        $ret .= '<option value="' . $def->id . '"';
        foreach($selected as $p) {
            // session array or passed stdClass obj
            $current = @$p->id ? $p->id: $p;
            if($def->id == $current) {
                $ret .= ' selected="selected"';
            }
        }
        $ret .= '>' . HTML::entities($def->name) . '</option>';
    }
    $ret .= '</select>';
    return $ret;
});

Usage

List without pre-selected items (create view)

{{ Form::chosen('places', $places, Input::old('places')) }}

Preselections (edit view)

{{ Form::chosen('places', $places, $job->places) }}

Complete usage

{{ Form::chosen('places', $places, $job->places, ['multiple': false, 'title': 'I\'m a selectbox', 'class': 'bootstrap_is_mainstream']) }}

Redirect to an external URL from controller action in Spring MVC

Did you try RedirectView where you can provide the contextRelative parameter?

SQL Server datetime LIKE select?

There's no direct support for LIKE operator against DATETIME variables, but you can always cast the DATETIME to a VARCHAR:

SELECT (list of fields) FROM YourTable
WHERE CONVERT(VARCHAR(25), register_date, 126) LIKE '2009-10-10%'

Check the MSDN docs for a complete list of available "styles" in the CONVERT function.

Marc

Cannot connect to repo with TortoiseSVN

As stated by David W. "First of all, check your URL" - Our dns entry changed breaking all svn repo connections. Connecting on ip instead of url as Wes stated worked - (now we have to fix our dns)

In Chart.js set chart title, name of x axis and y axis?

In Chart.js version 2.0, it is possible to set labels for axes:

options = {
  scales: {
    yAxes: [{
      scaleLabel: {
        display: true,
        labelString: 'probability'
      }
    }]
  }     
}

See Labelling documentation for more details.

Run php function on button click

You are trying to call a javascript function. If you want to call a PHP function, you have to use for example a form:

    <form action="action_page.php">
       First name:<br>
       <input type="text" name="firstname" value="Mickey">
       <br>
       Last name:<br>
       <input type="text" name="lastname" value="Mouse">
       <br><br>
       <input type="submit" value="Submit">
     </form> 

(Original Code from: http://www.w3schools.com/html/html_forms.asp)

So if you want do do a asynchron call, you could use 'Ajax' - and yeah, that's the Javascript-Way. But I think, that my code example is enough for this time :)

Auto margins don't center image in page

Under some circumstances (such as earlier versions of IE, Gecko, Webkit) and inheritance, elements with position:relative; will prevent margin:0 auto; from working, even if top, right, bottom, and left aren't set.

Setting the element to position:static; (the default) may fix it under these circumstances. Generally, block level elements with a specified width will respect margin:0 auto; using either relative or static positioning.

How do I split a string on a delimiter in Bash?

Use the set built-in to load up the $@ array:

IN="[email protected];[email protected]"
IFS=';'; set $IN; IFS=$' \t\n'

Then, let the party begin:

echo $#
for a; do echo $a; done
ADDR1=$1 ADDR2=$2

Postgresql SELECT if string contains

You should use 'tag_name' outside of quotes; then its interpreted as a field of the record. Concatenate using '||' with the literal percent signs:

SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' LIKE '%' || tag_name || '%';

How do I change Eclipse to use spaces instead of tabs?

As an augmentation to the other answers, on Mac OS X, the "Preferences" menu is under Eclipse, not Window (unlike Windows/Linux Eclipse distributions). Everything else is still the same as pointed out by other answers past this point.

IE: Java Formatter available under:

Eclipse >      | # Not Window!
Preferences >  |
Java >         |
Code Style >   |
Formatter      |

From here, edit the formatter and the tab policy can be set under "Indentation".

javascript password generator

I got insprired by the answers above (especially by the hint from @e.vyushin regarding the security of Math.random() ) and I came up with the following solution that uses the crypto.getRandomValues() to generate a rondom array of UInt32 values with the length of the password length.

Then, it loops through the array and devides each element by 2^32 (max value of a UInt32) to calculate the ratio between the actual value and the max. possible value. This ratio is then mapped to the charset string to determine which character of the string is picked.

console.log(createPassword(16,"letters+numbers+signs"));
function createPassword(len, charset) {
    if (charset==="letters+numbers") {
        var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    } else if (charset==="letters+numbers+signs") {
        var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!§$%&/?#+-_@";
    }
    var arr = new Uint32Array(len);
    var maxRange = Math.pow(2,32);
    var passwd = '';
    window.crypto.getRandomValues(arr);
    

    for (let i=0;i<len;i++) {
        var c = Math.floor(arr[i] / maxRange  * chars.length + 1);
        passwd += chars.charAt(c);
    }
    return passwd;
}

Thus, the code is able to use the advantage of the crypto-Class (improved security for the random value generation) and is adaptable to use any kind of charset the user wished. A next step would be to use regular expression strings to define the charset to be used.

What is the difference between % and %% in a cmd file?

In DOS you couldn't use environment variables on the command line, only in batch files, where they used the % sign as a delimiter. If you wanted a literal % sign in a batch file, e.g. in an echo statement, you needed to double it.

This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your % signs in a .cmd file.

How to clear the Entry widget after a button is pressed in Tkinter?

I'm unclear about your question. From http://effbot.org/tkinterbook/entry.htm#patterns, it seems you just need to do an assignment after you called the delete. To add entry text to the widget, use the insert method. To replace the current text, you can call delete before you insert the new text.

e = Entry(master)
e.pack()

e.delete(0, END)
e.insert(0, "")

Could you post a bit more code?

How can I search for a commit message on GitHub?

Update (2017/01/05):

GitHub has published an update that allows you now to search within commit messages from within their UI. See blog post for more information.


I had the same question and contacted someone GitHub yesterday:

Since they switched their search engine to Elasticsearch it's not possible to search for commit messages using the GitHub UI. But that feature is on the team's wishlist.

Unfortunately there's no release date for that function right now.

SQL 'like' vs '=' performance

A personal example using mysql 5.5: I had an inner join between 2 tables, one of 3 million rows and one of 10 thousand rows.

When using a like on an index as below(no wildcards), it took about 30 seconds:

where login like '12345678'

using 'explain' I get:

enter image description here

When using an '=' on the same query, it took about 0.1 seconds:

where login ='600009'

Using 'explain' I get:

enter image description here

As you can see, the like completely cancelled the index seek, so query took 300 times more time.

Get the current user, within an ApiController action, without passing the userID as a parameter

Hint lies in Webapi2 auto generated account controller

Have this property with getter defined as

public string UserIdentity
        {
            get
            {
                var user = UserManager.FindByName(User.Identity.Name);
                return user;//user.Email
            }
        }

and in order to get UserManager - In WebApi2 -do as Romans (read as AccountController) do

public ApplicationUserManager UserManager
        {
            get { return HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
        }

This should be compatible in IIS and self host mode

How to press back button in android programmatically?

You don't need to override onBackPressed() - it's already defined as the action that your activity will do by default when the user pressed the back button. So just call onBackPressed() whenever you want to "programatically press" the back button.

That would only result to finish() being called, though ;)

I think you're confused with what the back button does. By default, it's just a call to finish(), so it just exits the current activity. If you have something behind that activity, that screen will show.

What you can do is when launching your activity from the Login, add a CLEAR_TOP flag so the login activity won't be there when you exit yours.

How to indent HTML tags in Notepad++

Step 1: Open plugin manager in notepad++

Plugins -> Plugin Manager -> Show Plugin Manager.

Step 2:install XML Tool plugin

Search "XML TOOLS" from the "Available" option then click in install.

Now you can use shortcut key CTRL+ALT+SHIFT+B to indent the code.

C# DropDownList with a Dictionary as DataSource

Like that you can set DataTextField and DataValueField of DropDownList using "Key" and "Value" texts :

    Dictionary<string, string> list = new Dictionary<string, string>();
    list.Add("item 1", "Item 1");
    list.Add("item 2", "Item 2");
    list.Add("item 3", "Item 3");
    list.Add("item 4", "Item 4");

    ddl.DataSource = list;
    ddl.DataTextField = "Value";
    ddl.DataValueField = "Key";
    ddl.DataBind();

Screen width in React Native

React Native comes with "Dimensions" api which we need to import from 'react-native'

import { Dimensions } from 'react-native';

Then,

<Image source={pic} style={{width: Dimensions.get('window').width, height: Dimensions.get('window').height}}></Image>

log4j:WARN No appenders could be found for logger in web.xml

Add log4jExposeWebAppRoot -> false in your web.xml. It works with me :)

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>path/log4j.properties</param-value>
</context-param>
<context-param>
    <param-name>log4jExposeWebAppRoot</param-name>
    <param-value>false</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

Try this:

 >>> f = open('goodlines.txt')
 >>> mylist = f.readlines()

open() function returns a file object. And for file object, there is no method like splitlines() or split(). You could use dir(f) to see all the methods of file object.

Is "delete this" allowed in C++?

Yes, delete this; has defined results, as long as (as you've noted) you assure the object was allocated dynamically, and (of course) never attempt to use the object after it's destroyed. Over the years, many questions have been asked about what the standard says specifically about delete this;, as opposed to deleting some other pointer. The answer to that is fairly short and simple: it doesn't say much of anything. It just says that delete's operand must be an expression that designates a pointer to an object, or an array of objects. It goes into quite a bit of detail about things like how it figures out what (if any) deallocation function to call to release the memory, but the entire section on delete (§[expr.delete]) doesn't mention delete this; specifically at all. The section on destrucors does mention delete this in one place (§[class.dtor]/13):

At the point of definition of a virtual destructor (including an implicit definition (15.8)), the non-array deallocation function is determined as if for the expression delete this appearing in a non-virtual destructor of the destructor’s class (see 8.3.5).

That tends to support the idea that the standard considers delete this; to be valid--if it was invalid, its type wouldn't be meaningful. That's the only place the standard mentions delete this; at all, as far as I know.

Anyway, some consider delete this a nasty hack, and tell anybody who will listen that it should be avoided. One commonly cited problem is the difficulty of ensuring that objects of the class are only ever allocated dynamically. Others consider it a perfectly reasonable idiom, and use it all the time. Personally, I'm somewhere in the middle: I rarely use it, but don't hesitate to do so when it seems to be the right tool for the job.

The primary time you use this technique is with an object that has a life that's almost entirely its own. One example James Kanze has cited was a billing/tracking system he worked on for a phone company. When start to you make a phone call, something takes note of that and creates a phone_call object. From that point onward, the phone_call object handles the details of the phone call (making a connection when you dial, adding an entry to the database to say when the call started, possibly connect more people if you do a conference call, etc.) When the last people on the call hang up, the phone_call object does its final book-keeping (e.g., adds an entry to the database to say when you hung up, so they can compute how long your call was) and then destroys itself. The lifetime of the phone_call object is based on when the first person starts the call and when the last people leave the call--from the viewpoint of the rest of the system, it's basically entirely arbitrary, so you can't tie it to any lexical scope in the code, or anything on that order.

For anybody who might care about how dependable this kind of coding can be: if you make a phone call to, from, or through almost any part of Europe, there's a pretty good chance that it's being handled (at least in part) by code that does exactly this.

How to do associative array/hashing in JavaScript

If you require your keys to be any object rather than just strings, then you could use my jshashtable.

how to remove the first two columns in a file using shell (awk, sed, whatever)

Its pretty straight forward to do it with only shell

while read A B C; do
echo "$C"
done < oldfile >newfile

"Can't find Project or Library" for standard VBA functions

I have seen errors on standard functions if there was a reference to a totally different library missing.

In the VBA editor launch the Compile command from the menu and then check the References dialog to see if there is anything missing and if so try to add these libraries.

In general it seems to be good practice to compile the complete VBA code and then saving the document before distribution.