Programs & Examples On #Deployment project

Pandas dataframe fillna() only some columns in place

You can avoid making a copy of the object using Wen's solution and inplace=True:

df.fillna({'a':0, 'b':0}, inplace=True)
print(df)

Which yields:

     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0

How to time Java program execution speed

Using AOP/AspectJ and @Loggable annotation from jcabi-aspects you can do it easy and compact:

@Loggable(Loggable.DEBUG)
public String getSomeResult() {
  // return some value
}

Every call to this method will be sent to SLF4J logging facility with DEBUG logging level. And every log message will include execution time.

Inserting a PDF file in LaTeX

The \includegraphics function has a page option for inserting a specific page of a PDF file as graphs. The default is one, but you can change it.

\includegraphics[scale=0.75,page=2]{multipage.pdf}

You can find more here.

How to create a drop-down list?

Spinner xml:

<Spinner
      android:id="@+id/spinner"
      android:layout_width="wrap_content"
      android:layout_height="match_parent" />

java:

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{

    private Spinner spinner;
    private static final String[] paths = {"item 1", "item 2", "item 3"};

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        spinner = (Spinner)findViewById(R.id.spinner);
        ArrayAdapter<String>adapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_spinner_item,paths);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {

        switch (position) {
            case 0:
                // Whatever you want to happen when the first item gets selected
                break;
            case 1:
                // Whatever you want to happen when the second item gets selected
                break;
            case 2:
                // Whatever you want to happen when the thrid item gets selected
                break;

        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub
        }

}

How do you properly use WideCharToMultiByte

You use the lpMultiByteStr [out] parameter by creating a new char array. You then pass this char array in to get it filled. You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.

Here are a couple of useful helper functions for you, they show the usage of all parameters.

#include <string>

std::string wstrtostr(const std::wstring &wstr)
{
    // Convert a Unicode string to an ASCII string
    std::string strTo;
    char *szTo = new char[wstr.length() + 1];
    szTo[wstr.size()] = '\0';
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
    strTo = szTo;
    delete[] szTo;
    return strTo;
}

std::wstring strtowstr(const std::string &str)
{
    // Convert an ASCII string to a Unicode String
    std::wstring wstrTo;
    wchar_t *wszTo = new wchar_t[str.length() + 1];
    wszTo[str.size()] = L'\0';
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());
    wstrTo = wszTo;
    delete[] wszTo;
    return wstrTo;
}

--

Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it. The function will use that pointer to fill your variable.

So you can understand this better:

//pX is an out parameter, it fills your variable with 10.
void fillXWith10(int *pX)
{
  *pX = 10;
}

int main(int argc, char ** argv)
{
  int X;
  fillXWith10(&X);
  return 0;
}

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

When I read in various places that hibernate didn't like you to assign to a collection, I assumed that the safest thing to do would obviously be to make it final like this:

class User {
  private final Set<Role> roles = new HashSet<>();

public void setRoles(Set<Role> roles) {
  this.roles.retainAll(roles);
  this.roles.addAll(roles);
}
}

However, this doesn't work, and you get the dreaded "no longer referenced" error, which is actually quite misleading in this case.

It turns out that hibernate calls your setRoles method AND it wants its special collection class installed here, and won't accept your collection class. This had me stumped for a LONG time, despite reading all the warnings about not assigning to your collection in your set method.

So I changed to this:

public class User {
  private Set<Role> roles = null;

  public void setRoles(Set<Role> roles) {
  if (this.roles == null) {
    this.roles = roles;
  } else {
    this.roles.retainAll(roles);
   this.roles.addAll(roles);
  }
}
}

So that on the first call, hibernate installs its special class, and on subsequent calls you can use the method yourself without wrecking everything. If you want to use your class as a bean, you probably need a working setter, and this at least seems to work.

Getting the name of the currently executing method

To get the name of the method that called the current method you can use:

new Exception("is not thrown").getStackTrace()[1].getMethodName()

This works on my MacBook as well as on my Android phone

I also tried:

Thread.currentThread().getStackTrace()[1]

but Android will return "getStackTrace" I could fix this for Android with

Thread.currentThread().getStackTrace()[2]

but then I get the wrong answer on my MacBook

Jmeter - Run .jmx file through command line and get the summary report in a excel

To get the results in excel like file, you have one option to get it done with csv file. Use below commands with provided options.

jmeter -n -t /path-to-jmeter-test/file.jmx -l TestResults.csv
-n states Non GUI mode
-t states Test JMX File
-l state Log the results in provided file

Also you can pass any results related parameters dynamically in command line arguments using -Jprop.name=value which are already defined in jmeter.properties in bin folder.

ApiNotActivatedMapError for simple html page using google-places-api

Assuming you already have a application created under google developer console, Follow the below steps

  1. Go to the following link https://console.cloud.google.com/apis/dashboard? you will be getting the below page enter image description here
  2. Click on ENABLE APIS AND SERVICES you will be directed to following page enter image description here
  3. Select the desired option - in this case "Maps JavaScript API"
  4. Click ENABLE button as below, enter image description here

Note: Please use a server to load the html file

Check if an element is a child of a parent

.has() seems to be designed for this purpose. Since it returns a jQuery object, you have to test for .length as well:

if ($('div#hello').has(target).length) {
   alert('Target is a child of #hello');
}

Assign keyboard shortcut to run procedure

Write a vba proc like:

Sub E_1()
    Call sndPlaySound32(ThisWorkbook.Path & "\e1.wav", 0)
    Range("AG" & (ActiveCell.Row)).Select 'go to column AG in the same row
End Sub

then go to developer tab, macros, select the macro, click options, then add a shortcut letter or button.

C#: New line and tab characters in strings

    StringBuilder SqlScript = new StringBuilder();

    foreach (var file in lstScripts)
    {
        var input = File.ReadAllText(file.FilePath);
        SqlScript.AppendFormat(input, Environment.NewLine);
    }

http://afzal-gujrat.blogspot.com/

How to throw RuntimeException ("cannot find symbol")

As everyone else has said, instantiate the object before throwing it.

Just wanted to add one bit; it's incredibly uncommon to throw a RuntimeException. It would be normal for code in the API to throw a subclass of this, but normally, application code would throw Exception, or something that extends Exception but not RuntimeException.

And in retrospect, I missed adding the reason why you use Exception instead of RuntimeException; @Jay, in the comment below, added in the useful bit. RuntimeException isn't a checked exception;

  • The method signature doesn't have to declare that a RuntimeException may be thrown.
  • Callers of that method aren't required to catch the exception, or acknowlege it in any way.
  • Developers who try to later use your code won't anticipate this problem unless they look carefully, and it will increase the maintenance burden of the code.

What is the <leader> in a .vimrc file?

In my system its the \ key. it's used for commands so that you can combine it with other chars.

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

VLook-Up Match first 3 characters of one column with another column

Try using a wildcard like this

=VLOOKUP(LEFT(A1,3)&"*",B$2:B$22,1,FALSE)

so if A1 is "barry" that formula will return the first value in B2:B22 that starts with "bar"

Polling the keyboard (detect a keypress) in python

Ok, since my attempt to post my solution in a comment failed, here's what I was trying to say. I could do exactly what I wanted from native Python (on Windows, not anywhere else though) with the following code:

import msvcrt 

def kbfunc(): 
   x = msvcrt.kbhit()
   if x: 
      ret = ord(msvcrt.getch()) 
   else: 
      ret = 0 
   return ret

Laravel Eloquent groupBy() AND also return count of each group

Here is a more Laravel way to handle group by without the need to use raw statements.

$sources = $sources->where('age','>', 31)->groupBy('age');

$output = null;
foreach($sources as $key => $source) {
    foreach($source as $item) {
        //get each item in the group
    }
    $output[$key] = $source->count();
}

Spring application context external properties?

One way to do it is to add your external config folder to the classpath of the java process. That's how I've often done it in the past.

Selenium and xPath - locating a link by containing text

@FindBy(xpath = "//span[@class='y2' and contains(text(), 'Your Text')] ") 
private WebElementFacade emailLinkToVerifyAccount;

This approach will work for you, hopefully.

What does this thread join code mean?

This is a favorite Java interview question.

Thread t1 = new Thread(new EventThread("e1"));
t1.start();
Thread e2 = new Thread(new EventThread("e2"));
t2.start();

while (true) {
    try {
        t1.join(); // 1
        t2.join(); // 2  These lines (1,2) are in in public static void main
        break;
    }
}

t1.join() means, t1 says something like "I want to finish first". Same is the case with t2. No matter who started t1 or t2 thread (in this case the main method), main will wait until t1 and t2 finish their task.

However, an important point to note down, t1 and t2 themselves can run in parallel irrespective of the join call sequence on t1 and t2. It is the main/daemon thread that has to wait.

Angularjs if-then-else construction in expression

This can be done in one line.

{{corretor.isAdministrador && 'YES' || 'NÂO'}}

Usage in a td tag:

<td class="text-center">{{corretor.isAdministrador && 'Sim' || 'Não'}}</td>

Reading an image file in C/C++

If you decide to go for a minimal approach, without libpng/libjpeg dependencies, I suggest using stb_image and stb_image_write, found here.

It's as simple as it gets, you just need to place the header files stb_image.h and stb_image_write.h in your folder.

Here's the code that you need to read images:

#include <stdint.h>

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

int main() {
    int width, height, bpp;

    uint8_t* rgb_image = stbi_load("image.png", &width, &height, &bpp, 3);

    stbi_image_free(rgb_image);

    return 0;
}

And here's the code to write an image:

#include <stdint.h>

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

#define CHANNEL_NUM 3

int main() {
    int width = 800; 
    int height = 800;

    uint8_t* rgb_image;
    rgb_image = malloc(width*height*CHANNEL_NUM);

    // Write your code to populate rgb_image here

    stbi_write_png("image.png", width, height, CHANNEL_NUM, rgb_image, width*CHANNEL_NUM);

    return 0;
}

You can compile without flags or dependencies:

g++ main.cpp

Other lightweight alternatives include:

Unsigned values in C

Assign a int -1 to an unsigned: As -1 does not fit in the range [0...UINT_MAX], multiples of UINT_MAX+1 are added until the answer is in range. Evidently UINT_MAX is pow(2,32)-1 or 429496725 on OP's machine so a has the value of 4294967295.

    unsigned int a = -1;

The "%x", "%u" specifier expects a matching unsigned. Since these do not match, "If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined." C11 §7.21.6.1 9. The printf specifier does not change b.

    printf("%x\n", b);  // UB
    printf("%u\n", b);  // UB

The "%d" specifier expects a matching int. Since these do not match, more UB.

    printf("%d\n", a);  // UB

Given undefined behavior, the conclusions are not supported.


both cases, the bytes are the same (ffffffff).

Even with the same bit pattern, different types may have different values. ffffffff as an unsigned has the value of 4294967295. As an int, depending signed integer encoding, it has the value of -1, -2147483647 or TBD. As a float it may be a NAN.

what is unsigned word for?

unsigned stores a whole number in the range [0 ... UINT_MAX]. It never has a negative value. If code needs a non-negative number, use unsigned. If code needs a counting number that may be +, - or 0, use int.


Update: to avoid a compiler warning about assigning a signed int to unsigned, use the below. This is an unsigned 1u being negated - which is well defined as above. The effect is the same as a -1, but conveys to the compiler direct intentions.

unsigned int a = -1u;

TypeError: Can't convert 'int' object to str implicitly

You cannot concatenate a string with an int. You would need to convert your int to a string using the str function, or use formatting to format your output.

Change: -

print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")

to: -

print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))

or: -

print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")

or as per the comment, use , to pass different strings to your print function, rather than concatenating using +: -

print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")

How can I know when an EditText loses focus?

Using Java 8 lambda expression:

editText.setOnFocusChangeListener((v, hasFocus) -> {
    if(!hasFocus) {
        String value = String.valueOf( editText.getText() );
    }        
});

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

Can I write into the console in a unit test? If yes, why doesn't the console window open?

I have an easier solution (that I used myself recently, for a host of lazy reasons). Add this method to the class you are working in:

public static void DumbDebug(string message)
{
    File.WriteAllText(@"C:\AdHocConsole\" + message + ".txt", "this is really dumb. I wish Microsoft had more obvious solutions to its solutions problems.");
}

Then...open up the directory AdHocConsole, and order by created time. Make sure when you add your 'print statements'. They are distinct though, else there will be juggling.

Update a column value, replacing part of a string

Try using the REPLACE function:

mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
        -> 'WwWwWw.mysql.com'

Note that it is case sensitive.

Implementing two interfaces in a class with same method. Which interface method is overridden?

As in interface,we are just declaring methods,concrete class which implements these both interfaces understands is that there is only one method(as you described both have same name in return type). so there should not be an issue with it.You will be able to define that method in concrete class.

But when two interface have a method with the same name but different return type and you implement two methods in concrete class:

Please look at below code:

public interface InterfaceA {
  public void print();
}


public interface InterfaceB {
  public int print();
}

public class ClassAB implements InterfaceA, InterfaceB {
  public void print()
  {
    System.out.println("Inside InterfaceA");
  }
  public int print()
  {
    System.out.println("Inside InterfaceB");
    return 5;
  }
}

when compiler gets method "public void print()" it first looks in InterfaceA and it gets it.But still it gives compile time error that return type is not compatible with method of InterfaceB.

So it goes haywire for compiler.

In this way, you will not be able to implement two interface having a method of same name but different return type.

AngularJS How to dynamically add HTML and bind to controller

I needed to execute an directive AFTER loading several templates so I created this directive:

_x000D_
_x000D_
utilModule.directive('utPreload',_x000D_
    ['$templateRequest', '$templateCache', '$q', '$compile', '$rootScope',_x000D_
    function($templateRequest, $templateCache, $q, $compile, $rootScope) {_x000D_
    'use strict';_x000D_
    var link = function(scope, element) {_x000D_
        scope.$watch('done', function(done) {_x000D_
            if(done === true) {_x000D_
                var html = "";_x000D_
                if(scope.slvAppend === true) {_x000D_
                    scope.urls.forEach(function(url) {_x000D_
                        html += $templateCache.get(url);_x000D_
                    });_x000D_
                }_x000D_
                html += scope.slvHtml;_x000D_
                element.append($compile(html)($rootScope));_x000D_
            }_x000D_
        });_x000D_
    };_x000D_
_x000D_
    var controller = function($scope) {_x000D_
        $scope.done = false;_x000D_
        $scope.html = "";_x000D_
        $scope.urls = $scope.slvTemplate.split(',');_x000D_
        var promises = [];_x000D_
        $scope.urls.forEach(function(url) {_x000D_
            promises.add($templateRequest(url));_x000D_
        });_x000D_
        $q.all(promises).then(_x000D_
            function() { // SUCCESS_x000D_
                $scope.done = true;_x000D_
            }, function() { // FAIL_x000D_
                throw new Error('preload failed.');_x000D_
            }_x000D_
        );_x000D_
    };_x000D_
_x000D_
    return {_x000D_
        restrict: 'A',_x000D_
        scope: {_x000D_
            utTemplate: '=', // the templates to load (comma separated)_x000D_
            utAppend: '=', // boolean: append templates to DOM after load?_x000D_
            utHtml: '=' // the html to append and compile after templates have been loaded_x000D_
        },_x000D_
        link: link,_x000D_
        controller: controller_x000D_
    };_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>_x000D_
_x000D_
<div class="container-fluid"_x000D_
     ut-preload_x000D_
     ut-append="true"_x000D_
     ut-template="'html/one.html,html/two.html'"_x000D_
     ut-html="'<my-directive></my-directive>'">_x000D_
 _x000D_
</div>
_x000D_
_x000D_
_x000D_

100% width background image with an 'auto' height

Instead of using background-image you can use img directly and to get the image to spread all the width of the viewport try using max-width:100%; and please remember don't apply any padding or margin to your main container div as they will increase the total width of the container. Using this rule you can have a image width equal to the width of the browser and the height will also change according to the aspect ratio. Thanks.

Edit: Changing the image on different size of the window

_x000D_
_x000D_
$(window).resize(function(){_x000D_
  var windowWidth = $(window).width();_x000D_
  var imgSrc = $('#image');_x000D_
  if(windowWidth <= 400){   _x000D_
    imgSrc.attr('src','http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a');_x000D_
  }_x000D_
  else if(windowWidth > 400){_x000D_
    imgSrc.attr('src','http://i.stack.imgur.com/oURrw.png');_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="image-container">_x000D_
  <img id="image" src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a" alt=""/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In this way you change your image in different size of the browser.

How do I pipe or redirect the output of curl -v?

This simple example shows how to capture curl output, and use it in a bash script

test.sh

function main
{
  \curl -vs 'http://google.com'  2>&1
  # note: add -o /tmp/ignore.png if you want to ignore binary output, by saving it to a file. 
}

# capture output of curl to a variable
OUT=$(main)

# search output for something using grep.
echo
echo "$OUT" | grep 302 
echo
echo "$OUT" | grep title 

ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (DBD ERROR: OCIServerAttach)

The following worked for me (Windows 7):

oradim -shutdown -sid enter_sid_here
oradim -startup -sid enter_sid_here

(with enter_sid_here replaced by the SID)

In Python, is there an elegant way to print a list in a custom format without explicit looping?

l = [1, 2, 3]
print '\n'.join(['%i: %s' % (n, l[n]) for n in xrange(len(l))])

How do I write output in same place on the console?

You can also use the carriage return:

sys.stdout.write("Download progress: %d%%   \r" % (progress) )
sys.stdout.flush()

inverting image in Python with OpenCV

Alternatively, you could invert the image using the bitwise_not function of OpenCV:

imagem = cv2.bitwise_not(imagem)

I liked this example.

What Java FTP client library should I use?

You have also this 2006 article which lists different options for FTP clients.

commons-net is good, but FTP-GO can give you some of the more advanced features you are looking for.

kagi Ftp-Go

Can I change the Android startActivity() transition animation?

Most of the answers are pretty correct, but some of them are deprecated such as when using R.anim.hold and some of them are just elaboratig the process.

So, you can use:

startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

Create Local SQL Server database

For anyone still looking to do this in 2020. So long as you are purely using it for development purposes you can download a full featured version of SQL Server directly from Microsoft at https://www.microsoft.com/en-us/sql-server/sql-server-downloads.

Load local JSON file into variable

For ES6/ES2015 you can import directly like:

// example.json
{
    "name": "testing"
}


// ES6/ES2015
// app.js
import * as data from './example.json';
const {name} = data;
console.log(name); // output 'testing'

If you use Typescript, you may declare json module like:

// tying.d.ts
declare module "*.json" {
    const value: any;
    export default value;
}

Since Typescript 2.9+ you can add --resolveJsonModule compilerOptions in tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
     ...
    "resolveJsonModule": true,
     ...
  },
  ...
}

How can I make an svg scale with its parent container?

Adjusting the currentScale attribute works in IE ( I tested with IE 11), but not in Chrome.

Fill Combobox from database

void Fillcombobox()
{

    con.Open();
    cmd = new SqlCommand("select ID From Employees",con);
    Sdr = cmd.ExecuteReader();
    while (Sdr.Read())
    {
        for (int i = 0; i < Sdr.FieldCount; i++)
        {
           comboID.Items.Add( Sdr.GetString(i));

        }
    }
    Sdr.Close();
    con.Close();

}

how to get curl to output only http response body (json) and no other headers etc

You are specifying the -i option:

-i, --include

(HTTP) Include the HTTP-header in the output. The HTTP-header includes things like server-name, date of the document, HTTP-version and more...

Simply remove that option from your command line:

response=$(curl -sb -H "Accept: application/json" "http://host:8080/some/resource")

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.

My problem on the Browser Console:

Image Problem on Browser Console

PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)

In my case my code fix was:

//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ProductosService {

  productos:any[] = [];
  cargando:boolean = true;

  constructor( private http:Http) {
    this.cargar_productos();
  }

  public cargar_productos(){

    this.cargando = true;

    this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
      .subscribe( res => {
        console.log(res.json());
        this.cargando = false;
        this.productos = res.json().productos; // Before this.productos = res.json(); 
      });
  }

}

How to set ANDROID_HOME path in ubuntu?

This is what work for me, Assuming you have the sdk extracted at ~/Android/Sdk,

export ANDROID_HOME=$HOME/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/platform-tools

Add the above lines to the file ~/.bashrc (located at home/username/.bashrc) to make it permanent for the current user. Run source ~/.bashrc to apply the changes or restart your terminal. (or) Run the above lines on a terminal window to make it available for the session. To test if you have set it up correctly, Run the below commands on a terminal window

echo $ANDROID_HOME

user#host:~$ echo $ANDROID_HOME

You will get

/home/<user>/Android/Sdk

You can run this too

which android

user#host:~$ which android

/home/<user>/Android/Sdk/tools/android

Run android on a terminal, If it opens up Android SDK Manager, you are good to go.

What's the use of ob_start() in php?

Following things are not mentioned in the existing answers : Buffer size configuration HTTP Header and Nesting.

Buffer size configuration for ob_start :

ob_start(null, 4096); // Once the buffer size exceeds 4096 bytes, PHP automatically executes flush, ie. the buffer is emptied and sent out.

The above code improve server performance as PHP will send bigger chunks of data, for example, 4KB (wihout ob_start call, php will send each echo to the browser).

If you start buffering without the chunk size (ie. a simple ob_start()), then the page will be sent once at the end of the script.

Output buffering does not affect the HTTP headers, they are processed in different way. However, due to buffering you can send the headers even after the output was sent, because it is still in the buffer.

ob_start();  // turns on output buffering
$foo->bar();  // all output goes only to buffer
ob_clean();  // delete the contents of the buffer, but remains buffering active
$foo->render(); // output goes to buffer
ob_flush(); // send buffer output
$none = ob_get_contents();  // buffer content is now an empty string
ob_end_clean();  // turn off output buffering

Nicely explained here : https://phpfashion.com/everything-about-output-buffering-in-php

Python JSON dump / append to .txt with each variable on new line

To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:

with g as outfile:
  json.dump(hostDict, outfile,indent=2)

Using indent = 2 helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.

Are table names in MySQL case sensitive?

It depends upon lower_case_table_names system variable:

show variables where Variable_name='lower_case_table_names'

There are three possible values for this:

  • 0 - lettercase specified in the CREATE TABLE or CREATE DATABASE statement. Name comparisons are case sensitive.
  • 1 - Table names are stored in lowercase on disk and name comparisons are not case sensitive.
  • 2 - lettercase specified in the CREATE TABLE or CREATE DATABASE statement, but MySQL converts them to lowercase on lookup. Name comparisons are not case sensitive.

Documentation

location.host vs location.hostname and cross-browser compatibility?

host just includes the port number if there is one specified. If there is no port number specifically in the URL, then it returns the same as hostname. You pick whether you care to match the port number or not. See https://developer.mozilla.org/en/window.location for more info.

I would assume you want hostname to just get the site name.

Table is marked as crashed and should be repaired

Here is where the repair button is:

alt text

How can I append a query parameter to an existing URL?

Use the URI class.

Create a new URI with your existing String to "break it up" to parts, and instantiate another one to assemble the modified url:

URI u = new URI("http://[email protected]&name=John#fragment");

// Modify the query: append your new parameter
StringBuilder sb = new StringBuilder(u.getQuery() == null ? "" : u.getQuery());
if (sb.length() > 0)
    sb.append('&');
sb.append(URLEncoder.encode("paramName", "UTF-8"));
sb.append('=');
sb.append(URLEncoder.encode("paramValue", "UTF-8"));

// Build the new url with the modified query:
URI u2 = new URI(u.getScheme(), u.getAuthority(), u.getPath(),
    sb.toString(), u.getFragment());

How to run a C# console application with the console hidden

If you are using the ProcessStartInfo class you can set the window style to hidden - in the case of console (not GUI) applications, you have to set CreateNoWindow to true:

System.Diagnostics.ProcessStartInfo start =
      new System.Diagnostics.ProcessStartInfo();
start.FileName = dir + @"\Myprocesstostart.exe";
start.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; //Hides GUI
start.CreateNoWindow = true; //Hides console

Angular 4 - Observable catch error

catch needs to return an observable.

.catch(e => { console.log(e); return Observable.of(e); })

if you'd like to stop the pipeline after a caught error, then do this:

.catch(e => { console.log(e); return Observable.of(null); }).filter(e => !!e)

this catch transforms the error into a null val and then filter doesn't let falsey values through. This will however, stop the pipeline for ANY falsey value, so if you think those might come through and you want them to, you'll need to be more explicit / creative.

edit:

better way of stopping the pipeline is to do

.catch(e => Observable.empty())

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

Call the toISOString() method:

var dt = new Date("30 July 2010 15:05 UTC");
document.write(dt.toISOString());

// Output:
//  2010-07-30T15:05:00.000Z

Syntax for a for loop in ruby

I keep hitting this as a top link for google "ruby for loop", so I wanted to add a solution for loops where the step wasn't simply '1'. For these cases, you can use the 'step' method that exists on Numerics and Date objects. I think this is a close approximation for a 'for' loop.

start = Date.new(2013,06,30)
stop = Date.new(2011,06,30)
# step back in time over two years, one week at a time
start.step(stop, -7).each do |d| 
    puts d
end

Functions are not valid as a React child. This may happen if you return a Component instead of from render

In my case i forgot to add the () after the function name inside the render function of a react component

public render() {
       let ctrl = (
           <>
                <div className="aaa">
                    {this.renderView}
                </div>
            </>
       ); 

       return ctrl;
    };


    private renderView() : JSX.Element {
        // some html
    };

Changing the render method, as it states in the error message to

        <div className="aaa">
            {this.renderView()}
        </div>

fixed the problem

best way to get the key of a key/value javascript object

use for each loop for accessing keys in Object or Maps in javascript

for(key in foo){
   console.log(key);//for key name in your case it will be bar
   console.log(foo[key]);// for key value in your case it will be baz
}

Note: you can also use

Object.keys(foo);

it will give you like this output:

[bar];

No Spring WebApplicationInitializer types detected on classpath

WebApplicationInitializer is an interface you can implement in one of your classes. At startup Spring is scanning for this classes, as long as you are using servlet spec 3 and have a metadata-complete="false" attribute in your web.xml. But that doesn't seem to be the problem. The only error I can figure out is the missing slf4j-log4j12.jar.

Getting cursor position in Python

I found a way to do it that doesn't depend on non-standard libraries!

Found this in Tkinter

self.winfo_pointerxy()

jQuery get specific option tag text

Try this:

jQuery("#list option[value='2']").text()

C++ Compare char array with string

You're not working with strings. You're working with pointers. var1 is a char pointer (const char*). It is not a string. If it is null-terminated, then certain C functions will treat it as a string, but it is fundamentally just a pointer.

So when you compare it to a char array, the array decays to a pointer as well, and the compiler then tries to find an operator == (const char*, const char*).

Such an operator does exist. It takes two pointers and returns true if they point to the same address. So the compiler invokes that, and your code breaks.

IF you want to do string comparisons, you have to tell the compiler that you want to deal with strings, not pointers.

The C way of doing this is to use the strcmp function:

strcmp(var1, "dev");

This will return zero if the two strings are equal. (It will return a value greater than zero if the left-hand side is lexicographically greater than the right hand side, and a value less than zero otherwise.)

So to compare for equality you need to do one of these:

if (!strcmp(var1, "dev")){...}
if (strcmp(var1, "dev") == 0) {...}

However, C++ has a very useful string class. If we use that your code becomes a fair bit simpler. Of course we could create strings from both arguments, but we only need to do it with one of them:

std::string var1 = getenv("myEnvVar");

if(var1 == "dev")
{
   // do stuff
}

Now the compiler encounters a comparison between string and char pointer. It can handle that, because a char pointer can be implicitly converted to a string, yielding a string/string comparison. And those behave exactly as you'd expect.

How To: Best way to draw table in console app (C#)

Use String.Format with alignment values.

For example:

String.Format("|{0,5}|{1,5}|{2,5}|{3,5}|", arg0, arg1, arg2, arg3);

To create one formatted row.

Javascript can't find element by id?

The problem is that you are trying to access the element before it exists. You need to wait for the page to be fully loaded. A possible approach is to use the onload handler:

window.onload = function () {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
};

Most common JavaScript libraries provide a DOM-ready event, though. This is better, since window.onload waits for all images, too. You do not need that in most cases.

Another approach is to place the script tag right before your closing </body>-tag, since everything in front of it is loaded at the time of execution, then.

How to set commands output as a variable in a batch file

If you don't want to output to a temp file and then read into a variable, this code stores result of command direct into a variable:

FOR /F %i IN ('findstr testing') DO set VARIABLE=%i
echo %VARIABLE%

If you want to enclose search string in double quotes:

FOR /F %i IN ('findstr "testing"') DO set VARIABLE=%i

If you want to store this code in a batch file, add an extra % symbol:

FOR /F %%i IN ('findstr "testing"') DO set VARIABLE=%%i

A useful example to count the number of files in a directory & store in a variable: (illustrates piping)

FOR /F %i IN ('dir /b /a-d "%cd%" ^| find /v /c "?"') DO set /a count=%i

Note the use of single quotes instead of double quotes " or grave accent ` in the command brackets. This is cleaner alternative to delims, tokens or usebackq in for loop.

Tested on Win 10 CMD.

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

Convert data.frame columns from factors to characters

This works transforming all to character and then the numeric to numeric:

makenumcols<-function(df){
  df<-as.data.frame(df)
  df[] <- lapply(df, as.character)
  cond <- apply(df, 2, function(x) {
    x <- x[!is.na(x)]
    all(suppressWarnings(!is.na(as.numeric(x))))
  })
  numeric_cols <- names(df)[cond]
  df[,numeric_cols] <- sapply(df[,numeric_cols], as.numeric)
  return(df)
}

Adapted from: Get column types of excel sheet automatically

How do I protect Python code?

Another attempt to make your code harder to steal is to use jython and then use java obfuscator.

This should work pretty well as jythonc translate python code to java and then java is compiled to bytecode. So ounce you obfuscate the classes it will be really hard to understand what is going on after decompilation, not to mention recovering the actual code.

The only problem with jython is that you can't use python modules written in c.

Convert Pandas Column to DateTime

You can use the DataFrame method .apply() to operate on the values in Mycol:

>>> df = pd.DataFrame(['05SEP2014:00:00:00.000'],columns=['Mycol'])
>>> df
                    Mycol
0  05SEP2014:00:00:00.000
>>> import datetime as dt
>>> df['Mycol'] = df['Mycol'].apply(lambda x: 
                                    dt.datetime.strptime(x,'%d%b%Y:%H:%M:%S.%f'))
>>> df
       Mycol
0 2014-09-05

How to modify STYLE attribute of element with known ID using JQuery

Use the CSS function from jQuery to set styles to your items :

$('#buttonId').css({ "background-color": 'brown'});

Best way to overlay an ESRI shapefile on google maps?

I would not use KML. Instead, use GeoJSON which you can natively consume in Google Maps API now. It is a newer feature that didn't exist from the original responses.

In any case, simply open the SHP file in Quantum GIS, and then you can output it in any format you like (KML, GeoJSON).

If you are using Google Maps for Work, I found a premium extension that handles loading shapefiles directly where you can just connect direct to the shapefile that you generate from ESRI. I did a search on the CMaps site and found this snippet which loaded US by state shapefile: https://gmapsplugin.net/cmapsanalytics/assets/shapes/usstates.shp

var cMap = new centigon.locationIntelligence.MapView();
    cMap.key([your_api_key]);


    cMap.layerNames(["Basic Shapes"]);
    cMap.dbfKeys([['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','District of Columbia','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming']]);
    cMap.userShapeKeys([['Massachusetts','Minnesota','Montana','North Dakota','Hawaii','Idaho','Washington','Arizona','California','Colorado','Nevada','New Mexico','Oregon','Utah','Wyoming','Arkansas','Iowa','Kansas','Missouri','Nebraska','Oklahoma','South Dakota','Louisiana','Texas','Connecticut','New Hampshire','Rhode Island','Vermont','Alabama','Florida','Georgia','Mississippi','South Carolina','Illinois','Indiana','Kentucky','North Carolina','Ohio','Tennessee','Virginia','Wisconsin','West Virginia','Delaware','District of Columbia','Maryland','New Jersey','New York','Pennsylvania','Maine','Michigan','Alaska']]); 
    cMap.labels([['Massachusetts','Minnesota','Montana','North Dakota','Hawaii','Idaho','Washington','Arizona','California','Colorado','Nevada','New Mexico','Oregon','Utah','Wyoming','Arkansas','Iowa','Kansas','Missouri','Nebraska','Oklahoma','South Dakota','Louisiana','Texas','Connecticut','New Hampshire','Rhode Island','Vermont','Alabama','Florida','Georgia','Mississippi','South Carolina','Illinois','Indiana','Kentucky','North Carolina','Ohio','Tennessee','Virginia','Wisconsin','West Virginia','Delaware','District of Columbia','Maryland','New Jersey','New York','Pennsylvania','Maine','Michigan','Alaska']]); 

    cMap.polyDataSources([centigon.locationIntelligence.CMapAnalytics.DATA_PROVIDERS.SHAPE_DATAPROVIDER]);
    cMap.layerTypes([centigon.mapping.Layer.TYPE.POLY]);
    cMap.locations([["https://gmapsplugin.net/cmapsanalytics/assets/shapes/usstates.shp"]]);

    cMap.panTo("USA");
    cMap.zoomLevel(3);

resize2fs: Bad magic number in super-block while trying to open

I ran into the same exact problem around noon today and finally found a solution here --> Trying to resize2fs EB volume fails

I skipped mounting, since the partition was already mounted.

Apparently CentOS 7 uses XFS as the default file system and as a result resize2fs will fail.

I took a look in /etc/fstab, and guess what, XFS was staring me in the face... Hope this helps.

Difference between "move" and "li" in MIPS assembly language

The move instruction copies a value from one register to another. The li instruction loads a specific numeric value into that register.

For the specific case of zero, you can use either the constant zero or the zero register to get that:

move $s0, $zero
li   $s0, 0

There's no register that generates a value other than zero, though, so you'd have to use li if you wanted some other number, like:

li $s0, 12345678

Why can I not switch branches?

you can reset your branch with HEAD

git reset --hard branch_name

then fetch branches and delete branches which are not on remote from local,

git fetch -p 

Show a message box from a class in c#?

using System.Windows.Forms;

public class message
{
    static void Main()
    {  
        MessageBox.Show("Hello World!"); 
    }
}

How can I debug a HTTP POST in Chrome?

The other people made very nice answers, but I would like to complete their work with an extra development tool. It is called Live HTTP Headers and you can install it into your Firefox, and in Chrome we have the same plug in like this.

Working with it is queit easy.

  1. Using your Firefox, navigate to the website which you want to get your post request to it.

  2. In your Firefox menu Tools->Live Http Headers

  3. A new window pop ups for you, and all the http method details would be saved in this window for you. You don't need to do anything in this step.

  4. In the website, do an activity(log in, submit a form, etc.)

  5. Look at your plug in window. It is all recorded.

Just remember you need to check the Capture.

enter image description here

how can I Update top 100 records in sql server

for those like me still stuck with SQL Server 2000, SET ROWCOUNT {number}; can be used before the UPDATE query

SET ROWCOUNT 100;
UPDATE Table SET ..;
SET ROWCOUNT 0;

will limit the update to 100 rows

It has been deprecated at least since SQL 2005, but as of SQL 2017 it still works. https://docs.microsoft.com/en-us/sql/t-sql/statements/set-rowcount-transact-sql?view=sql-server-2017

Correct way to push into state array

You can use .concat method to create copy of your array with new data:

this.setState({ myArray: this.state.myArray.concat('new value') })

But beware of special behaviour of .concat method when passing arrays - [1, 2].concat(['foo', 3], 'bar') will result in [1, 2, 'foo', 3, 'bar'].

How to compare two vectors for equality element by element in C++?

According to the discussion here you can directly compare two vectors using

==

if (vector1 == vector2){
   //true
}
else{
   //false
}

AngularJS $watch window resize inside directive

// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag

---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';

@Directive({
       selector: '[resize]',
       host: { '(window:resize)': 'onResize()' } // Window resize listener
})

export class AutoResize {

element: ElementRef; // Element that associated to attribute.
$window: any;
       constructor(_element: ElementRef) {

         this.element = _element;
         // Get instance of DOM window.
         this.$window = angular.element(window);

         this.onResize();

    }

    // Adjust height of element.
    onResize() {
         $(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');
   }
}

Why is @font-face throwing a 404 error on woff files?

Actually the @Ian Robinson answer works well but Chrome will continue complain with that message : "Resource interpreted as Font but transferred with MIME type application/x-woff"

If you get that, you can change from

application/x-woff

to

application/x-font-woff

and you will not have any Chrome console errors anymore !

(tested on Chrome 17)

jQuery: Best practice to populate drop down?

Sure - make options an array of strings and use .join('') rather than += every time through the loop. Slight performance bump when dealing with large numbers of options...

var options = [];
$.getJSON("/Admin/GetFolderList/", function(result) {
    for (var i = 0; i < result.length; i++) {
        options.push('<option value="',
          result[i].ImageFolderID, '">',
          result[i].Name, '</option>');
    }
    $("#theSelect").html(options.join(''));
});

Yes. I'm still working with strings the whole time. Believe it or not, that's the fastest way to build a DOM fragment... Now, if you have only a few options, it won't really matter - use the technique Dreas demonstrates if you like the style. But bear in mind, you're invoking the browser's internal HTML parser i*2 times, rather than just once, and modifying the DOM each time through the loop... with a sufficient number of options. you'll end up paying for it, especially on older browsers.

Note: As Justice points out, this will fall apart if ImageFolderID and Name are not encoded properly...

Environment Variable with Maven

Following documentation from @Kevin's answer the below one worked for me for setting environment variable with maven sure-fire plugin

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
    <environmentVariables>
        <WSNSHELL_HOME>conf</WSNSHELL_HOME>
    </environmentVariables>
</configuration>

How to Populate a DataTable from a Stored Procedure

You don't need to add the columns manually. Just use a DataAdapter and it's simple as:

DataTable table = new DataTable();
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
using(var cmd = new SqlCommand("usp_GetABCD", con))
using(var da = new SqlDataAdapter(cmd))
{
   cmd.CommandType = CommandType.StoredProcedure;
   da.Fill(table);
}

Note that you even don't need to open/close the connection. That will be done implicitly by the DataAdapter.

The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

What is the difference between an annotated and unannotated tag?

Push annotated tags, keep lightweight local

man git-tag says:

Annotated tags are meant for release while lightweight tags are meant for private or temporary object labels.

And certain behaviors do differentiate between them in ways that this recommendation is useful e.g.:

  • annotated tags can contain a message, creator, and date different than the commit they point to. So you could use them to describe a release without making a release commit.

    Lightweight tags don't have that extra information, and don't need it, since you are only going to use it yourself to develop.

  • git push --follow-tags will only push annotated tags
  • git describe without command line options only sees annotated tags

Internals differences

  • both lightweight and annotated tags are a file under .git/refs/tags that contains a SHA-1

  • for lightweight tags, the SHA-1 points directly to a commit:

    git tag light
    cat .git/refs/tags/light
    

    prints the same as the HEAD's SHA-1.

    So no wonder they cannot contain any other metadata.

  • annotated tags point to a tag object in the object database.

    git tag -as -m msg annot
    cat .git/refs/tags/annot
    

    contains the SHA of the annotated tag object:

    c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
    

    and then we can get its content with:

    git cat-file -p c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
    

    sample output:

    object 4284c41353e51a07e4ed4192ad2e9eaada9c059f
    type commit
    tag annot
    tagger Ciro Santilli <[email protected]> 1411478848 +0200
    
    msg
    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.4.11 (GNU/Linux)
    
    <YOUR PGP SIGNATURE>
    -----END PGP SIGNAT
    

    And this is how it contains extra metadata. As we can see from the output, the metadata fields are:

    A more detailed analysis of the format is present at: What is the format of a git tag object and how to calculate its SHA?

Bonuses

  • Determine if a tag is annotated:

    git cat-file -t tag
    

    Outputs

    • commit for lightweight, since there is no tag object, it points directly to the commit
    • tag for annotated, since there is a tag object in that case
  • List only lightweight tags: How can I list all lightweight tags?

event Action<> vs event EventHandler<>

Based on some of the previous answers, I'm going to break my answer down into three areas.

First, physical limitations of using Action<T1, T2, T2... > vs using a derived class of EventArgs. There are three: First, if you change the number or types of parameters, every method that subscribes to will have to be changed to conform to the new pattern. If this is a public facing event that 3rd party assemblies will be using, and there is any possiblity that the event args would change, this would be a reason to use a custom class derived from event args for consistencies sake (remember, you COULD still use an Action<MyCustomClass>) Second, using Action<T1, T2, T2... > will prevent you from passing feedback BACK to the calling method unless you have a some kind of object (with a Handled property for instance) that is passed along with the Action. Third, you don't get named parameters, so if you're passing 3 bool's an int, two string's, and a DateTime, you have no idea what the meaning of those values are. As a side note, you can still have a "Fire this event safely method while still using Action<T1, T2, T2... >".

Secondly, consistency implications. If you have a large system you're already working with, it's nearly always better to follow the way the rest of the system is designed unless you have an very good reason not too. If you have publicly facing events that need to be maintained, the ability to substitute derived classes can be important. Keep that in mind.

Thirdly, real life practice, I personally find that I tend to create a lot of one off events for things like property changes that I need to interact with (Particularly when doing MVVM with view models that interact with each other) or where the event has a single parameter. Most of the time these events take on the form of public event Action<[classtype], bool> [PropertyName]Changed; or public event Action SomethingHappened;. In these cases, there are two benefits. First, I get a type for the issuing class. If MyClass declares and is the only class firing the event, I get an explicit instance of MyClass to work with in the event handler. Secondly, for simple events such as property change events, the meaning of the parameters is obvious and stated in the name of the event handler and I don't have to create a myriad of classes for these kinds of events.

Remove First and Last Character C++

My BASIC interpreter chops beginning and ending quotes with

str->pop_back();
str->erase(str->begin());

Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert if not:

assert(str->front() == '"' && str->back() == '"');

Just my two cents.

Call async/await functions in parallel

There is another way without Promise.all() to do it in parallel:

First, we have 2 functions to print numbers:

function printNumber1() {
   return new Promise((resolve,reject) => {
      setTimeout(() => {
      console.log("Number1 is done");
      resolve(10);
      },1000);
   });
}

function printNumber2() {
   return new Promise((resolve,reject) => {
      setTimeout(() => {
      console.log("Number2 is done");
      resolve(20);
      },500);
   });
}

This is sequential:

async function oneByOne() {
   const number1 = await printNumber1();
   const number2 = await printNumber2();
} 
//Output: Number1 is done, Number2 is done

This is parallel:

async function inParallel() {
   const promise1 = printNumber1();
   const promise2 = printNumber2();
   const number1 = await promise1;
   const number2 = await promise2;
}
//Output: Number2 is done, Number1 is done

Algorithm to compare two images

An idea:

  1. use keypoint detectors to find scale- and transform- invariant descriptors of some points in the image (e.g. SIFT, SURF, GLOH, or LESH).
  2. try to align keypoints with similar descriptors from both images (like in panorama stitching), allow for some image transforms if necessary (e.g. scale & rotate, or elastic stretching).
  3. if many keypoints align well (exists such a transform, that keypoint alignment error is low; or transformation "energy" is low, etc.), you likely have similar images.

Step 2 is not trivial. In particular, you may need to use a smart algorithm to find the most similar keypoint on the other image. Point descriptors are usually very high-dimensional (like a hundred parameters), and there are many points to look through. kd-trees may be useful here, hash lookups don't work well.

Variants:

  • Detect edges or other features instead of points.

How to use .htaccess in WAMP Server?

Click on Wamp icon and open Apache/httpd.conf and search "#LoadModule rewrite_module modules/mod_rewrite.so". Remove # as below and save it

LoadModule rewrite_module modules/mod_rewrite.so

and restart all service.

How to get html table td cell value by JavaScript?

Don't use in-line JavaScript, separate your behaviour from your data and it gets much easier to handle. I'd suggest the following:

var table = document.getElementById('tableID'),
    cells = table.getElementsByTagName('td');

for (var i=0,len=cells.length; i<len; i++){
    cells[i].onclick = function(){
        console.log(this.innerHTML);
        /* if you know it's going to be numeric:
        console.log(parseInt(this.innerHTML),10);
        */
    }
}

_x000D_
_x000D_
var table = document.getElementById('tableID'),_x000D_
  cells = table.getElementsByTagName('td');_x000D_
_x000D_
for (var i = 0, len = cells.length; i < len; i++) {_x000D_
  cells[i].onclick = function() {_x000D_
    console.log(this.innerHTML);_x000D_
  };_x000D_
}
_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  padding: 0.2em 0.3em 0.1em 0.3em;_x000D_
}
_x000D_
<table id="tableID">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column heading 1</th>_x000D_
      <th>Column heading 2</th>_x000D_
      <th>Column heading 3</th>_x000D_
      <th>Column heading 4</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>43</td>_x000D_
      <td>23</td>_x000D_
      <td>89</td>_x000D_
      <td>5</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>3</td>_x000D_
      <td>0</td>_x000D_
      <td>98</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>10</td>_x000D_
      <td>32</td>_x000D_
      <td>7</td>_x000D_
      <td>2</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JS Fiddle proof-of-concept.

A revised approach, in response to the comment (below):

You're missing a semicolon. Also, don't make functions within a loop.

This revision binds a (single) named function as the click event-handler of the multiple <td> elements, and avoids the unnecessary overhead of creating multiple anonymous functions within a loop (which is poor practice due to repetition and the impact on performance, due to memory usage):

function logText() {
  // 'this' is automatically passed to the named
  // function via the use of addEventListener()
  // (later):
  console.log(this.textContent);
}

// using a CSS Selector, with document.querySelectorAll()
// to get a NodeList of <td> elements within the #tableID element:
var cells = document.querySelectorAll('#tableID td');

// iterating over the array-like NodeList, using
// Array.prototype.forEach() and Function.prototype.call():
Array.prototype.forEach.call(cells, function(td) {
  // the first argument of the anonymous function (here: 'td')
  // is the element of the array over which we're iterating.

  // adding an event-handler (the function logText) to handle
  // the click events on the <td> elements:
  td.addEventListener('click', logText);
});

_x000D_
_x000D_
function logText() {_x000D_
  console.log(this.textContent);_x000D_
}_x000D_
_x000D_
var cells = document.querySelectorAll('#tableID td');_x000D_
_x000D_
Array.prototype.forEach.call(cells, function(td) {_x000D_
  td.addEventListener('click', logText);_x000D_
});
_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  padding: 0.2em 0.3em 0.1em 0.3em;_x000D_
}
_x000D_
<table id="tableID">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column heading 1</th>_x000D_
      <th>Column heading 2</th>_x000D_
      <th>Column heading 3</th>_x000D_
      <th>Column heading 4</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>43</td>_x000D_
      <td>23</td>_x000D_
      <td>89</td>_x000D_
      <td>5</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>3</td>_x000D_
      <td>0</td>_x000D_
      <td>98</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>10</td>_x000D_
      <td>32</td>_x000D_
      <td>7</td>_x000D_
      <td>2</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JS Fiddle proof-of-concept.

References:

Strip HTML from strings in Python

The Beautiful Soup package does this immediately for you.

from bs4 import BeautifulSoup

soup = BeautifulSoup(html)
text = soup.get_text()
print(text)

Basic Authentication Using JavaScript

After Spending quite a bit of time looking into this, i came up with the solution for this; In this solution i am not using the Basic authentication but instead went with the oAuth authentication protocol. But to use Basic authentication you should be able to specify this in the "setHeaderRequest" with minimal changes to the rest of the code example. I hope this will be able to help someone else in the future:

var token_ // variable will store the token
var userName = "clientID"; // app clientID
var passWord = "secretKey"; // app clientSecret
var caspioTokenUrl = "https://xxx123.caspio.com/oauth/token"; // Your application token endpoint  
var request = new XMLHttpRequest(); 

function getToken(url, clientID, clientSecret) {
    var key;           
    request.open("POST", url, true); 
    request.setRequestHeader("Content-type", "application/json");
    request.send("grant_type=client_credentials&client_id="+clientID+"&"+"client_secret="+clientSecret); // specify the credentials to receive the token on request
    request.onreadystatechange = function () {
        if (request.readyState == request.DONE) {
            var response = request.responseText;
            var obj = JSON.parse(response); 
            key = obj.access_token; //store the value of the accesstoken
            token_ = key; // store token in your global variable "token_" or you could simply return the value of the access token from the function
        }
    }
}
// Get the token
getToken(caspioTokenUrl, userName, passWord);

If you are using the Caspio REST API on some request it may be imperative that you to encode the paramaters for certain request to your endpoint; see the Caspio documentation on this issue;

NOTE: encodedParams is NOT used in this example but was used in my solution.

Now that you have the token stored from the token endpoint you should be able to successfully authenticate for subsequent request from the caspio resource endpoint for your application

function CallWebAPI() {
    var request_ = new XMLHttpRequest();        
    var encodedParams = encodeURIComponent(params);
    request_.open("GET", "https://xxx123.caspio.com/rest/v1/tables/", true);
    request_.setRequestHeader("Authorization", "Bearer "+ token_);
    request_.send();
    request_.onreadystatechange = function () {
        if (request_.readyState == 4 && request_.status == 200) {
            var response = request_.responseText;
            var obj = JSON.parse(response); 
            // handle data as needed... 

        }
    }
} 

This solution does only considers how to successfully make the authenticated request using the Caspio API in pure javascript. There are still many flaws i am sure...

Search for executable files using find command

So as to have another possibility1 to find the files that are executable by the current user:

find . -type f -exec test -x {} \; -print

(the test command here is the one found in PATH, very likely /usr/bin/test, not the builtin).


1 Only use this if the -executable flag of find is not available! this is subtly different from the -perm +111 solution.

Selecting non-blank cells in Excel with VBA

I know I'm am very late on this, but here some usefull samples:

'select the used cells in column 3 of worksheet wks
wks.columns(3).SpecialCells(xlCellTypeConstants).Select

or

'change all formulas in col 3 to values
with sheet1.columns(3).SpecialCells(xlCellTypeFormulas)
    .value = .value
end with

To find the last used row in column, never rely on LastCell, which is unreliable (it is not reset after deleting data). Instead, I use someting like

 lngLast = cells(rows.count,3).end(xlUp).row

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

Please verify your .project and .classpath files. Verify the java version and other reuqired details. If those and missing or mis matched

How to set focus on input field?

For those who use Angular with the Bootstrap plugin:

http://angular-ui.github.io/bootstrap/#/modal

You can hook into the opened promise of the modal instance:

modalInstance.opened.then(function() {
        $timeout(function() {
            angular.element('#title_input').trigger('focus');
        });
    });

modalInstance.result.then(function ( etc...

On delete cascade with doctrine2

There are two kinds of cascades in Doctrine:

1) ORM level - uses cascade={"remove"} in the association - this is a calculation that is done in the UnitOfWork and does not affect the database structure. When you remove an object, the UnitOfWork will iterate over all objects in the association and remove them.

2) Database level - uses onDelete="CASCADE" on the association's joinColumn - this will add On Delete Cascade to the foreign key column in the database:

@ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")

I also want to point out that the way you have your cascade={"remove"} right now, if you delete a Child object, this cascade will remove the Parent object. Clearly not what you want.

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

In my case I had to put textbox into a stack panel in order to stretch textbox on left side. Thanks to previous post. Just for an example I did set a background color to see what’s happens when window size is changing.

<StackPanel Name="JustContainer" VerticalAlignment="Center" HorizontalAlignment="Stretch" Background="BlueViolet" >
    <TextBox 
       Name="Input" Text="Hello World" 
       MaxWidth="300"
       HorizontalAlignment="Right"
       Width="{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type FrameworkElement}}}">
    </TextBox>
</StackPanel>

Creating a JSON dynamically with each input value using jquery

same from above example - if you are just looking for json (not an array of object) just use

function getJsonDetails() {
      item = {}
      item ["token1"] = token1val;
      item ["token2"] = token1val;
      return item;
}
console.log(JSON.stringify(getJsonDetails()))

this output ll print as (a valid json)

{ 
   "token1":"samplevalue1",
   "token2":"samplevalue2"
}

How to check type of files without extensions in python?

also you can use this code (pure python by 3 byte of header file):

full_path = os.path.join(MEDIA_ROOT, pathfile)

try:
    image_data = open(full_path, "rb").read()
except IOError:
    return "Incorrect Request :( !!!"

header_byte = image_data[0:3].encode("hex").lower()

if header_byte == '474946':
    return "image/gif"
elif header_byte == '89504e':
    return "image/png"
elif header_byte == 'ffd8ff':
    return "image/jpeg"
else:
    return "binary file"

without any package install [and update version]

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

Update: I should have probably started with this as your projects are SNAPSHOTs. It is part of the SNAPSHOT semantics that Maven will check for updates on each build. Being a SNAPSHOT means that it is volatile and subject to change so updates should be checked for. However it's worth pointing out that the Maven super POM configures central to have snapshots disabled, so Maven shouldn't ever check for updates for SNAPSHOTs on central unless you've overridden that in your own pom/settings.


You can configure Maven to use a mirror for the central repository, this will redirect all requests that would normally go to central to your internal repository.

In your settings.xml you would add something like this to set your internal repository as as mirror for central:

<mirrors>
  <mirror>
    <id>ibiblio.org</id>
    <name>ibiblio Mirror of http://repo1.maven.org/maven2/</name>
    <url>http://path/to/my/repository</url>
    <mirrorOf>central</mirrorOf>
  </mirror>
</mirrors>

If you are using a repository manager like Nexus for your internal repository. You can set up a proxy repository for proxy central, so any requests that would normally go to Central are instead sent to your proxy repository (or a repository group containing the proxy), and subsequent requests are cached in the internal repository manager. You can even set the proxy cache timeout to -1, so it will never request for contents from central that are already on the proxy repository.


A more basic solution if you are only working with local repositories is to set the updatePolicy for the central repository to "never", this means Maven will only ever check for artifacts that aren't already in the local repository. This can then be overridden at the command line when needed by using the -U switch to force Maven to check for updates.

You would configure the repository (in your pom or a profile in the settings.xml) as follows:

<repository>
  <id>central</id>
  <url>http://repo1.maven.org/maven2</url>
  <updatePolicy>never</updatePolicy>
</repository>

How to connect PHP with Microsoft Access database

If you are struggling with the connection in the XAMPP environment I suggest uncommenting the following entry in the php.ini file.

extension = odbc

I received an error without it: Uncaught pdoexception: could not find driver

In Flask, What is request.args and how is it used?

It has some interesting behaviour in some cases that is good to be aware of:

from werkzeug.datastructures import MultiDict

d = MultiDict([("ex1", ""), ("ex2", None)])

d.get("ex1", "alternive")
# returns: ''

d.get("ex2", "alternative")
# returns no visible output of any kind
# It is returning literally None, so if you do:
d.get("ex2", "alternative") is None
# it returns: True

d.get("ex3", "alternative")
# returns: 'alternative'

How to convert a string to lower case in Bash?

In bash 4 you can use typeset

Example:

A="HELLO WORLD"
typeset -l A=$A

Reverse HashMap keys and values in Java

private <A, B> Map<B, A> invertMap(Map<A, B> map) {
    Map<B, A> reverseMap = new HashMap<>();
    for (Map.Entry<A, B> entry : map.entrySet()) {
        reverseMap.put(entry.getValue(), entry.getKey());
    }
    return reverseMap;
}

It's important to remember that put replaces the value when called with the same key. So if you map has two keys with the same value only one of them will exist in the inverted map.

Webpack how to build production code and how to use it

Use these plugins to optimize your production build:

  new webpack.optimize.CommonsChunkPlugin('common'),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.UglifyJsPlugin(),
  new webpack.optimize.AggressiveMergingPlugin()

I recently came to know about compression-webpack-plugin which gzips your output bundle to reduce its size. Add this as well in the above listed plugins list to further optimize your production code.

new CompressionPlugin({
      asset: "[path].gz[query]",
      algorithm: "gzip",
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      minRatio: 0.8
})

Server side dynamic gzip compression is not recommended for serving static client-side files because of heavy CPU usage.

Convert Datetime column from UTC to local time in select statement

Ron's answer contains an error. It uses 2:00 AM local time where the UTC equivalent is required. I don't have enough reputation points to comment on Ron's answer so a corrected version appears below:

-- =============================================
-- Author:      Ron Smith
-- Create date: 2013-10-23
-- Description: Converts UTC to DST
--              based on passed Standard offset
-- =============================================
CREATE FUNCTION [dbo].[fn_UTC_to_DST]
(
    @UTC datetime,
    @StandardOffset int
)
RETURNS datetime
AS
BEGIN

declare 
    @DST datetime,
    @SSM datetime, -- Second Sunday in March
    @FSN datetime  -- First Sunday in November
-- get DST Range
set @SSM = datename(year,@UTC) + '0314' 
set @SSM = dateadd(hour,2 - @StandardOffset,dateadd(day,datepart(dw,@SSM)*-1+1,@SSM))
set @FSN = datename(year,@UTC) + '1107'
set @FSN = dateadd(second,-1,dateadd(hour,2 - (@StandardOffset + 1),dateadd(day,datepart(dw,@FSN)*-1+1,@FSN)))

-- add an hour to @StandardOffset if @UTC is in DST range
if @UTC between @SSM and @FSN
    set @StandardOffset = @StandardOffset + 1

-- convert to DST
set @DST = dateadd(hour,@StandardOffset,@UTC)

-- return converted datetime
return @DST

END

std::string formatting like sprintf

inline void format(string& a_string, const char* fmt, ...)
{
    va_list vl;
    va_start(vl, fmt);
    int size = _vscprintf( fmt, vl );
    a_string.resize( ++size );
    vsnprintf_s((char*)a_string.data(), size, _TRUNCATE, fmt, vl);
    va_end(vl);
}

Function to Calculate a CRC16 Checksum

for (pos = 0; pos < len; pos++) {
    crc ^= (uint16_t)buf[pos];     // XOR byte into least sig. byte of crc

    for (i = 8; i != 0; i--) {     // Loop over each bit
        if ((crc & 0x0001) != 0) { // If the LSB is set
            crc >>= 1;             // Shift right and XOR 0xA001
            crc ^= CRC16;
        } else {                   // Else LSB is not set
            crc >>= 1;             // Just shift right
        }
     }
}

return crc;

Oracle - What TNS Names file am I using?

The easiest way is probably to check the PATH environment variable of the process that is connecting to the database. Most likely the tnsnames.ora file is in first Oracle bin directory in path..\network\admin. TNS_ADMIN environment variable or value in registry (for the current Oracle home) may override this.

Using filemon like suggested by others will also do the trick.

How do I display a wordpress page content?

You can achieve this by adding this simple php code block

<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
      the_content();
      endwhile; else: ?>
      <p>!Sorry no posts here</p>
<?php endif; ?>

retrieve data from db and display it in table in php .. see this code whats wrong with it?

Here is the solution total html with php and database connections

   <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>database connections</title>
    </head>
    <body>
      <?php
      $username = "database-username";
      $password = "database-password";
      $host = "localhost";

      $connector = mysql_connect($host,$username,$password)
          or die("Unable to connect");
        echo "Connections are made successfully::";
      $selected = mysql_select_db("test_db", $connector)
        or die("Unable to connect");

      //execute the SQL query and return records
      $result = mysql_query("SELECT * FROM table_one ");
      ?>
      <table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
      <thead>
        <tr>
          <th>Employee_id</th>
          <th>Employee_Name</th>
          <th>Employee_dob</th>
          <th>Employee_Adress</th>
          <th>Employee_dept</th>
          <td>Employee_salary</td>
        </tr>
      </thead>
      <tbody>
        <?php
          while( $row = mysql_fetch_assoc( $result ) ){
            echo
            "<tr>
              <td>{$row\['employee_id'\]}</td>
              <td>{$row\['employee_name'\]}</td>
              <td>{$row\['employee_dob'\]}</td>
              <td>{$row\['employee_addr'\]}</td>
              <td>{$row\['employee_dept'\]}</td>
              <td>{$row\['employee_sal'\]}</td> 
            </tr>\n";
          }
        ?>
      </tbody>
    </table>
     <?php mysql_close($connector); ?>
    </body>
    </html>

How to check if an int is a null

You can use

if (person == null || String.valueOf(person.getId() == null)) 

in addition to regular approach

person.getId() == 0

How to create an empty matrix in R?

The default for matrix is to have 1 column. To explicitly have 0 columns, you need to write

matrix(, nrow = 15, ncol = 0)

A better way would be to preallocate the entire matrix and then fill it in

mat <- matrix(, nrow = 15, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- vector
}

Base table or view not found: 1146 Table Laravel 5

Check your migration file, maybe you are using Schema::table, like this:

Schema::table('table_name', function ($table)  {
    // ...
});

If you want to create a new table you must use Schema::create:

Schema::create('table_name', function ($table)  {
    // ...
});

default select option as blank

_x000D_
_x000D_
<td><b>Field Label:</b><br>
    <select style='align:left; width:100%;' id='some_id' name='some_name'>
    <option hidden selected>Select one...</option>
    <option value='Value1'>OptLabel1</option>
    <option value='Value2'>OptLabel2</option>
    <option value='Value3'>OptLabel3</option></select>
</td>
_x000D_
_x000D_
_x000D_

Just put "hidden" on option you want to hide on dropdown list.

How to generate a random string of 20 characters

Here you go. Just specify the chars you want to allow on the first line.

char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
    char c = chars[random.nextInt(chars.length)];
    sb.append(c);
}
String output = sb.toString();
System.out.println(output);

If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use java.security.SecureRandom instead. Values produced by java.util.Random and java.util.concurrent.ThreadLocalRandom are mathematically predictable.

Android - Pulling SQlite database android device

On Mac (NO root required)

1. Go to platform-tools folder.
2) Run following command in terminal.

./adb -d shell "run-as your.package.name cat databases/database.sqlite" > database.sqlite

It will copy the sqlite file in platform-tools folder.

How do I concatenate strings?

When you concatenate strings, you need to allocate memory to store the result. The easiest to start with is String and &str:

fn main() {
    let mut owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    owned_string.push_str(borrowed_string);
    println!("{}", owned_string);
}

Here, we have an owned string that we can mutate. This is efficient as it potentially allows us to reuse the memory allocation. There's a similar case for String and String, as &String can be dereferenced as &str.

fn main() {
    let mut owned_string: String = "hello ".to_owned();
    let another_owned_string: String = "world".to_owned();
    
    owned_string.push_str(&another_owned_string);
    println!("{}", owned_string);
}

After this, another_owned_string is untouched (note no mut qualifier). There's another variant that consumes the String but doesn't require it to be mutable. This is an implementation of the Add trait that takes a String as the left-hand side and a &str as the right-hand side:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    let new_owned_string = owned_string + borrowed_string;
    println!("{}", new_owned_string);
}

Note that owned_string is no longer accessible after the call to +.

What if we wanted to produce a new string, leaving both untouched? The simplest way is to use format!:

fn main() {
    let borrowed_string: &str = "hello ";
    let another_borrowed_string: &str = "world";
    
    let together = format!("{}{}", borrowed_string, another_borrowed_string);

    // After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
    // let together = format!("{borrowed_string}{another_borrowed_string}");

    println!("{}", together);
}

Note that both input variables are immutable, so we know that they aren't touched. If we wanted to do the same thing for any combination of String, we can use the fact that String also can be formatted:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let another_owned_string: String = "world".to_owned();
    
    let together = format!("{}{}", owned_string, another_owned_string);

    // After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
    // let together = format!("{owned_string}{another_owned_string}");
    println!("{}", together);
}

You don't have to use format! though. You can clone one string and append the other string to the new string:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    let together = owned_string.clone() + borrowed_string;
    println!("{}", together);
}

Note - all of the type specification I did is redundant - the compiler can infer all the types in play here. I added them simply to be clear to people new to Rust, as I expect this question to be popular with that group!

How to only get file name with Linux 'find'?

-exec and -execdir are slow, xargs is king.

$ alias f='time find /Applications -name "*.app" -type d -maxdepth 5'; \
f -exec basename {} \; | wc -l; \
f -execdir echo {} \; | wc -l; \
f -print0 | xargs -0 -n1 basename | wc -l; \
f -print0 | xargs -0 -n1 -P 8 basename | wc -l; \
f -print0 | xargs -0 basename | wc -l

     139
    0m01.17s real     0m00.20s user     0m00.93s system
     139
    0m01.16s real     0m00.20s user     0m00.92s system
     139
    0m01.05s real     0m00.17s user     0m00.85s system
     139
    0m00.93s real     0m00.17s user     0m00.85s system
     139
    0m00.88s real     0m00.12s user     0m00.75s system

xargs's parallelism also helps.

Funnily enough i cannot explain the last case of xargs without -n1. It gives the correct result and it's the fastest ¯\_(?)_/¯

(basename takes only 1 path argument but xargs will send them all (actually 5000) without -n1. does not work on linux and openbsd, only macOS...)

Some bigger numbers from a linux system to see how -execdir helps, but still much slower than a parallel xargs:

$ alias f='time find /usr/ -maxdepth 5 -type d'
$ f -exec basename {} \; | wc -l; \
f -execdir echo {} \; | wc -l; \
f -print0 | xargs -0 -n1 basename | wc -l; \
f -print0 | xargs -0 -n1 -P 8 basename | wc -l

2358
    3.63s real     0.10s user     0.41s system
2358
    1.53s real     0.05s user     0.31s system
2358
    1.30s real     0.03s user     0.21s system
2358
    0.41s real     0.03s user     0.25s system

Blur or dim background when Android PopupWindow active

You can use android:theme="@android:style/Theme.Dialog" to do that. Create an activity and in your AndroidManifest.xml define the activity as:

    <activity android:name=".activities.YourActivity"
              android:label="@string/your_activity_label"
              android:theme="@android:style/Theme.Dialog">

Can not change UILabel text color

May be the better way is

UIColor *color = [UIColor greenColor];
[self.myLabel setTextColor:color];

Thus we have colored text

Undoing accidental git stash pop

If your merge was not too complicated another option would be to:

  1. Move all the changes including the merge changes back to stash using "git stash"
  2. Run the merge again and commit your changes (without the changes from the dropped stash)
  3. Run a "git stash pop" which should ignore all the changes from your previous merge since the files are identical now.

After that you are left with only the changes from the stash you dropped too early.

Why do we use arrays instead of other data structures?

Not all programs do the same thing or run on the same hardware.

This is usually the answer why various language features exist. Arrays are a core computer science concept. Replacing arrays with lists/matrices/vectors/whatever advanced data structure would severely impact performance, and be downright impracticable in a number of systems. There are any number of cases where using one of these "advanced" data collection objects should be used because of the program in question.

In business programming (which most of us do), we can target hardware that is relatively powerful. Using a List in C# or Vector in Java is the right choice to make in these situations because these structures allow the developer to accomplish the goals faster, which in turn allows this type of software to be more featured.

When writing embedded software or an operating system an array may often be the better choice. While an array offers less functionality, it takes up less RAM, and the compiler can optimize code more efficiently for look-ups into arrays.

I am sure I am leaving out a number of the benefits for these cases, but I hope you get the point.

JavaScript data grid for millions of rows

I would highly recommend Open rico. It is difficult to implement in the the beginning, but once you grab it you will never look back.

Disable color change of anchor tag when visited

If you use some pre-processor like SASS, you can use @extend feature:

a:visited {
  @extend a;
}

As a result you will see automatically-added a:visited selector for every style with a selector, so be carefully with it, because your style-table may be increase in size very much.

As a compromise you can add @extend only in those block wich you really need.

How to insert values in table with foreign key using MySQL?

http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

For case1:

INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
SELECT 'Joe The Student', id_teacher
  FROM TAB_TEACHER
 WHERE name_teacher = 'Professor Jack'
 LIMIT 1

For case2 you just have to do 2 separate insert statements

How do I make a branch point at a specific commit?

git reset --hard 1258f0d0aae

But be careful, if the descendant commits between 1258f0d0aae and HEAD are not referenced in other branches it'll be tedious (but not impossible) to recover them, so you'd better to create a "backup" branch at current HEAD, checkout master, and reset to the commit you want.

Also, be sure that you don't have uncommitted changes before a reset --hard, they will be truly lost (no way to recover).

How to add one column into existing SQL Table

The syntax you need is

ALTER TABLE Products ADD LastUpdate  varchar(200) NULL

This is a metadata only operation

How do I extract a substring from a string until the second space is encountered?

A straightforward approach would be the following:

string[] tokens = str.Split(' ');
string retVal = tokens[0] + " " + tokens[1];

Slide a layout up from bottom of screen

Ok, there are two possible approaches. The simplest - is to use a sliding menu library. It allows creating a bottom sliding menu, it can animate the top container to make bottom visible, it suports both dragging it with your finger, or animating it programmatically via button (StaticDrawer).

Harder way - if you want to use Animations, as was already suggested. With animations you must FIRST change your layouts. So try first to make your layout change to the final state without any animations whatsoever. Because it is very likely that you are not laying out your views properly in RelativeLayout, so even though you show your bottom view, it remains obscured by the top one. Once you achieved proper layout change - all you need to do is to is to remember translations before layout and apply translate animation AFTER layout.

Get IPv4 addresses from Dns.GetHostEntry()

IPv6

lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0).ToString()


IPv4

lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(1).ToString()

how to delete all commit history in github?

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

  1. Checkout

    git checkout --orphan latest_branch

  2. Add all the files

    git add -A

  3. Commit the changes

    git commit -am "commit message"

  4. Delete the branch

    git branch -D main

  5. Rename the current branch to main

    git branch -m main

  6. Finally, force update your repository

    git push -f origin main

PS: this will not keep your old commit history around

How to use a typescript enum value in an Angular2 ngSwitch statement

You can create a custom decorator to add to your component to make it aware of enums.

myenum.enum.ts:

export enum MyEnum {
    FirstValue,
    SecondValue
}

myenumaware.decorator.ts

import { MyEnum } from './myenum.enum';

export function MyEnumAware(constructor: Function) {
    constructor.prototype.MyEnum = MyEnum;
}

enum-aware.component.ts

import { Component } from '@angular2/core';
import { MyEnum } from './myenum.enum';
import { MyEnumAware } from './myenumaware.decorator';

@Component({
  selector: 'enum-aware',
  template: `
    <div [ngSwitch]="myEnumValue">
      <div *ngSwitchCase="MyEnum.FirstValue">
        First Value
      </div>
      <div *ngSwitchCase="MyEnum.SecondValue">
        Second Value
      </div>
    </div>
    <button (click)="toggleValue()">Toggle Value</button>
  `,
})
@MyEnumAware // <---------------!!!
export default class EnumAwareComponent {
  myEnumValue: MyEnum = MyEnum.FirstValue;

  toggleValue() {
    this.myEnumValue = this.myEnumValue === MyEnum.FirstValue
        ? MyEnum.SecondValue : MyEnum.FirstValue;
  }
}

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

It's in this package (Ubuntu 19.04):

  sudo apt install g++-6

How do I declare a global variable in VBA?

You need to declare the variables outside the function:

Public iRaw As Integer
Public iColumn As Integer

Function find_results_idle()
    iRaw = 1
    iColumn = 1

How can I check if a string contains a character in C#?

You can create your own extention method if you plan to use this a lot.

public static class StringExt
{
    public static bool ContainsInvariant(this string sourceString, string filter)
    {
        return sourceString.ToLowerInvariant().Contains(filter);
    }
}

example usage:

public class test
{
    public bool Foo()
    {
        const string def = "aB";
        return def.ContainsInvariant("s");
    }
}

angular.element vs document.getElementById or jQuery selector with spin (busy) control

This worked for me well.

angular.forEach(element.find('div'), function(node)
{
  if(node.id == 'someid'){
    //do something
  }
  if(node.className == 'someclass'){
    //do something
  }
});

how to replace characters in hive?

select translate(description,'\\t','') from myTable;

Translates the input string by replacing the characters present in the from string with the corresponding characters in the to string. This is similar to the translate function in PostgreSQL. If any of the parameters to this UDF are NULL, the result is NULL as well. (Available as of Hive 0.10.0, for string types)

Char/varchar support added as of Hive 0.14.0

How to obtain Certificate Signing Request

Since you installed a new OS you probably don't have any more of your private and public keys that you used to sign your app in to XCode before. You need to regenerate those keys on your machine by revoking your previous certificate and asking for a new one on the iOS development portal. As part of the process you will be asked to generate a Certificate Signing Request which is where you seem to have a problem.

You will find all you need there which consists of (from the official doc):

1.Open Keychain Access on your Mac (located in Applications/Utilities).

2.Open Preferences and click Certificates. Make sure both Online Certificate Status Protocol and Certificate Revocation List are set to Off.

3.Choose Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority.

Note: If you have a private key selected when you do this, the CSR won’t be accepted. Make sure no private key is selected. Enter your user email address and common name. Use the same address and name as you used to register in the iOS Developer Program. No CA Email Address is required.

4.Select the options “Saved to disk” and “Let me specify key pair information” and click Continue.

5.Specify a filename and click Save. (make sure to replace .certSigningRequest with .csr)

For the Key Size choose 2048 bits and for Algorithm choose RSA. Click Continue and the Certificate Assistant creates a CSR and saves the file to your specified location.

Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?

Not really. This is normally done using javascript.

there is a good discussion of ways of doing this here...

Autosizing textarea using Prototype

Get an array of list element contents in jQuery

var arr = new Array();

$('li').each(function() { 
  arr.push(this.innerHTML); 
})

Moving from one activity to another Activity in Android

@Override
public void onClick(View v)
{
    // TODO Auto-generated method stub
    Intent intent = new Intent(Activity1.this,Activity2.class);
    startActivity(intent);

}

javascript regular expression to not match a word

This can be done in 2 ways:

if (str.match(/abc|def/)) {
                       ...
                    }


if (/abc|def/.test(str)) {
                        ....
                    } 

Git log out user from command line

Try this on Windows:

cmdkey /delete:LegacyGeneric:target=git:https://github.com

Measuring function execution time in R

As Andrie said, system.time() works fine. For short function I prefer to put replicate() in it:

system.time( replicate(10000, myfunction(with,arguments) ) )

Why is the jquery script not working?

if you have some other scripts that conflicts with jQuery wrap your code with this

(function($) {
    //here is your code
})(jQuery);

How can I set multiple CSS styles in JavaScript?

Using Object.assign:

Object.assign(yourelement.style,{fontsize:"12px",left:"200px",top:"100px"});

This also gives you ability to merge styles, instead of rewriting the CSS style.

You can also make a shortcut function:

const setStylesOnElement = function(styles, element){
    Object.assign(element.style, styles);
}

Writing a pandas DataFrame to CSV file

Example of export in file with full path on Windows and in case your file has headers:

df.to_csv (r'C:\Users\John\Desktop\export_dataframe.csv', index = None, header=True) 

For example, if you want to store the file in same directory where your script is, with utf-8 encoding and tab as separator:

df.to_csv(r'./export/dftocsv.csv', sep='\t', encoding='utf-8', header='true')

'names' attribute must be the same length as the vector

I want to explain the error with an example below:

> names(lenses)
[1] "X1..1..1..1..1..3"

names(lenses)=c("ID","Age","Sight","Astigmatism","Tear","Class") Error in names(lenses) = c("ID", "Age", "Sight", "Astigmatism", "Tear", : 'names' attribute [6] must be the same length as the vector [1]

The error happened because of mismatch in a number of attributes. I only have one but trying to add 6 names. In this case, the error happens. See below the correct one:::::>>>>

> names(lenses)=c("ID")
> names(lenses)

[1] "ID"

Now there was no error.

I hope this will help!

How to make URL/Phone-clickable UILabel?

If you want this to be handled by UILabel and not UITextView, you can make UILabel subclass, like this one:

class LinkedLabel: UILabel {

fileprivate let layoutManager = NSLayoutManager()
fileprivate let textContainer = NSTextContainer(size: CGSize.zero)
fileprivate var textStorage: NSTextStorage?


override init(frame aRect:CGRect){
    super.init(frame: aRect)
    self.initialize()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.initialize()
}

func initialize(){

    let tap = UITapGestureRecognizer(target: self, action: #selector(LinkedLabel.handleTapOnLabel))
    self.isUserInteractionEnabled = true
    self.addGestureRecognizer(tap)
}

override var attributedText: NSAttributedString?{
    didSet{
        if let _attributedText = attributedText{
            self.textStorage = NSTextStorage(attributedString: _attributedText)

            self.layoutManager.addTextContainer(self.textContainer)
            self.textStorage?.addLayoutManager(self.layoutManager)

            self.textContainer.lineFragmentPadding = 0.0;
            self.textContainer.lineBreakMode = self.lineBreakMode;
            self.textContainer.maximumNumberOfLines = self.numberOfLines;
        }

    }
}

func handleTapOnLabel(tapGesture:UITapGestureRecognizer){

    let locationOfTouchInLabel = tapGesture.location(in: tapGesture.view)
    let labelSize = tapGesture.view?.bounds.size
    let textBoundingBox = self.layoutManager.usedRect(for: self.textContainer)
    let textContainerOffset = CGPoint(x: ((labelSize?.width)! - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: ((labelSize?.height)! - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)

    let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)
    let indexOfCharacter = self.layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)


    self.attributedText?.enumerateAttribute(NSLinkAttributeName, in: NSMakeRange(0, (self.attributedText?.length)!), options: NSAttributedString.EnumerationOptions(rawValue: UInt(0)), using:{
        (attrs: Any?, range: NSRange, stop: UnsafeMutablePointer<ObjCBool>) in

        if NSLocationInRange(indexOfCharacter, range){
            if let _attrs = attrs{

                UIApplication.shared.openURL(URL(string: _attrs as! String)!)
            }
        }
    })

}}

This class was made by reusing code from this answer. In order to make attributed strings check out this answer. And here you can find how to make phone urls.

How to run certain task every day at a particular time using ScheduledExecutorService?

In Java 8:

scheduler = Executors.newScheduledThreadPool(1);

//Change here for the hour you want ----------------------------------.at()       
Long midnight=LocalDateTime.now().until(LocalDate.now().plusDays(1).atStartOfDay(), ChronoUnit.MINUTES);
scheduler.scheduleAtFixedRate(this, midnight, 1440, TimeUnit.MINUTES);

How to embed a YouTube channel into a webpage

In order to embed your channel, all you need to do is copy then paste the following code in another web-page.

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=YourChannelName&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

Make sure to replace the YourChannelName with your actual channel name.

For example: if your channel name were CaliChick94066 your channel embed code would be:

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=CaliChick94066&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

Please look at the following links:

YouTube on your site

Embed YouTube Channel

You just have to name the URL to your channel name. Also you can play with the height and the border color and size. Hope it helps

How to get the html of a div on another page with jQuery ajax?

Unfortunately an ajax request gets the entire file, but you can filter the content once it's retrieved:

$.ajax({
   url:href,
   type:'GET',
   success: function(data) {
       var content = $('<div>').append(data).find('#content');
       $('#content').html( content );
   }
});

Note the use of a dummy element as find() only works with descendants, and won't find root elements.

or let jQuery filter it for you:

$('#content').load(href + ' #IDofDivToFind');

I'm assuming this isn't a cross domain request, as that won't work, only pages on the same domain.

Deleting a SQL row ignoring all foreign keys and constraints

On all tables with foreign keys pointing to this one, use:

ALTER TABLE MyOtherTable NOCHECK CONSTRAINT fk_name

convert an enum to another type of enum

In case when the enum members have different values, you can apply something like this:

public static MyGender? MapToMyGender(this Gender gender)
{
    return gender switch
    {
        Gender.Male => MyGender.Male,
        Gender.Female => MyGender.Female,
        Gender.Unknown => null,
        _ => throw new InvalidEnumArgumentException($"Invalid gender: {gender}")
    };
}

Then you can call: var myGender = gender.MapToMyGender();

Update: This previous code works only with C# 8. For older versions of C#, you can use the switch statement instead of the switch expression:

public static MyGender? MapToMyGender(this Gender gender)
{
    switch (gender)
    {
        case Gender.Male: 
            return MyGender.Male;
        case Gender.Female:
            return MyGender.Female;
        case Gender.Unknown:
            return null;
        default:
            throw new InvalidEnumArgumentException($"Invalid gender: {gender}")
    };
}

Usage of __slots__?

You have — essentially — no use for __slots__.

For the time when you think you might need __slots__, you actually want to use Lightweight or Flyweight design patterns. These are cases when you no longer want to use purely Python objects. Instead, you want a Python object-like wrapper around an array, struct, or numpy array.

class Flyweight(object):

    def get(self, theData, index):
        return theData[index]

    def set(self, theData, index, value):
        theData[index]= value

The class-like wrapper has no attributes — it just provides methods that act on the underlying data. The methods can be reduced to class methods. Indeed, it could be reduced to just functions operating on the underlying array of data.

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

webRTC or websockets? Why not use both.

When building a video/audio/text chat, webRTC is definitely a good choice since it uses peer to peer technology and once the connection is up and running, you do not need to pass the communication via a server (unless using TURN).

When setting up the webRTC communication you have to involve some sort of signaling mechanism. Websockets could be a good choice here, but webRTC is the way to go for the video/audio/text info. Chat rooms is accomplished in the signaling.

But, as you mention, not every browser supports webRTC, so websockets can sometimes be a good fallback for those browsers.

Drop primary key using script in SQL Server database

The answer I got is that variables and subqueries will not work and we have to user dynamic SQL script. The following works:

DECLARE @SQL VARCHAR(4000)
SET @SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '

SET @SQL = REPLACE(@SQL, '|ConstraintName|', ( SELECT   name
                                               FROM     sysobjects
                                               WHERE    xtype = 'PK'
                                                        AND parent_obj =        OBJECT_ID('Student')))

EXEC (@SQL)

Why does instanceof return false for some literals?

Or you can just make your own function like so:

function isInstanceOf(obj, clazz){
  return (obj instanceof eval("("+clazz+")")) || (typeof obj == clazz.toLowerCase());
};

usage:

isInstanceOf('','String');
isInstanceOf(new String(), 'String');

These should both return true.

Webpack not excluding node_modules

Try use absolute path:

exclude:path.resolve(__dirname, "node_modules")

Docker official registry (Docker Hub) URL

For those wanting to explicitly declare they are pulling from dockerhub when using fabric8 maven plugin, add a new property: <docker.pull.registry>registry.hub.docker.com/library</docker.pull.registry>

I arrived on this page trying to solve problem of pulling from my AWS ECR registry when building Docker images using fabric8.

View more than one project/solution in Visual Studio

If you have two separate solutions, then you cannot view them simultaneously in the same VS instance. However, you can open multiple instances of VS and tab between them.

An alternative would be to import the projects from one solution into the other, thus putting all of your projects into one solution. You can do this by following these steps:

  1. In the Solution Explorer, select the Solution into which you want to import a project. Right-click, and select Add->Existing Project from the context menu.

  2. In the file chooser, find the project file that you want to import (it will end in .XXproj where XX is the language you're using).

  3. Click Open and voila! Your project is imported.

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I have a similar problem and as I'm newbie, here are some facts for somebody to comment:

I'm sending form data to Google sheet this way (scriptURL is https://script.google.com/macros/s/AKfy..., showSuccess() is showing a simple image):

fetch(scriptURL, {method: 'POST', body: new FormData(form)})
.then(response => showSuccess())
.catch(error => alert('Error! ' + error.message))

Executed in Edge my HTML doesn't show error and Network tab reports this 3 requests: Edge execution Executed in Chrome my HTML (index.htm) shows Failed to fetch error and Network tab reports this 2 requests: Chrome execution The value in the second column is blocked:other and there is also an error in Console tab:

GET https://script.googleusercontent.com/macros/echo?user_content_key=D-ABF... net::ERR_BLOCKED_BY_CLIENT

In order to suspend installed Chrome extensions, I executed my code in an Incognito window and there is no error message and Network tab reports this 2 requests: Incognito execution

My guess is that something (extension?) prevents Chrome to read the request's answer (the GET request is blocked).

How to remove an element slowly with jQuery?

I'm little late to the party, but for anyone like me that came from a Google search and didn't find the right answer. Don't get me wrong there are good answers here, but not exactly what I was looking for, without further ado, here is what I did:

_x000D_
_x000D_
$(document).ready(function() {
    
    var $deleteButton = $('.deleteItem');

    $deleteButton.on('click', function(event) {
      event.preventDefault();

      var $button = $(this);

      if(confirm('Are you sure about this ?')) {

        var $item = $button.closest('tr.item');

        $item.addClass('removed-item')
        
            .one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
          
                $(this).remove();
        });
      }
      
    });
    
});
_x000D_
/**
 * Credit to Sara Soueidan
 * @link https://github.com/SaraSoueidan/creative-list-effects/blob/master/css/styles-4.css
 */

.removed-item {
    -webkit-animation: removed-item-animation .6s cubic-bezier(.55,-0.04,.91,.94) forwards;
    -o-animation: removed-item-animation .6s cubic-bezier(.55,-0.04,.91,.94) forwards;
    animation: removed-item-animation .6s cubic-bezier(.55,-0.04,.91,.94) forwards
}

@keyframes removed-item-animation {
    from {
        opacity: 1;
        -webkit-transform: scale(1);
        -ms-transform: scale(1);
        -o-transform: scale(1);
        transform: scale(1)
    }

    to {
        -webkit-transform: scale(0);
        -ms-transform: scale(0);
        -o-transform: scale(0);
        transform: scale(0);
        opacity: 0
    }
}

@-webkit-keyframes removed-item-animation {
    from {
        opacity: 1;
        -webkit-transform: scale(1);
        transform: scale(1)
    }

    to {
        -webkit-transform: scale(0);
        transform: scale(0);
        opacity: 0
    }
}

@-o-keyframes removed-item-animation {
    from {
        opacity: 1;
        -o-transform: scale(1);
        transform: scale(1)
    }

    to {
        -o-transform: scale(0);
        transform: scale(0);
        opacity: 0
    }
}
_x000D_
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
  
  <table class="table table-striped table-bordered table-hover">
    <thead>
      <tr>
        <th>id</th>
        <th>firstname</th>
        <th>lastname</th>
        <th>@twitter</th>
        <th>action</th>
      </tr>
    </thead>
    <tbody>
      
      <tr class="item">
        <td>1</td>
        <td>Nour-Eddine</td>
        <td>ECH-CHEBABY</td>
        <th>@__chebaby</th>
        <td><button class="btn btn-danger deleteItem">Delete</button></td>
      </tr>
      
      <tr class="item">
        <td>2</td>
        <td>John</td>
        <td>Doe</td>
        <th>@johndoe</th>
        <td><button class="btn btn-danger deleteItem">Delete</button></td>
      </tr>
      
      <tr class="item">
        <td>3</td>
        <td>Jane</td>
        <td>Doe</td>
        <th>@janedoe</th>
        <td><button class="btn btn-danger deleteItem">Delete</button></td>
      </tr>
    </tbody>
  </table>
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


</body>
</html>
_x000D_
_x000D_
_x000D_

nginx: [emerg] "server" directive is not allowed here

Example valid nginx.conf for reverse proxy; In case someone is stuck like me. where 10.x.x.x is the server where you are running the nginx proxy server and to which you are connecting to with the browser, and 10.y.y.y is where your real web server is running

events {
  worker_connections  4096;  ## Default: 1024
}
http {
 server {
   listen 80;
   listen [::]:80;

   server_name 10.x.x.x;
 
   location / {
       proxy_pass http://10.y.y.y:80/;
       proxy_set_header Host $host;
   }
 }
}

Here is the snippet if you want to do SSL pass through. That is if 10.y.y.y is running a HTTPS webserver. Here 10.x.x.x, or where the nignx runs is listening to port 443, and all traffic to 443 is directed to your target web server

events {
  worker_connections  4096;  ## Default: 1024
}

stream {
  server {
    listen     443;
    proxy_pass 10.y.y.y:443;
  }
}

and you can serve it up in docker too

 docker run --name nginx-container --rm --net=host   -v /home/core/nginx/nginx.conf:/etc/nginx/nginx.conf nginx

Count the number of occurrences of a character in a string in Javascript

My solution:

function countOcurrences(str, value){
   var regExp = new RegExp(value, "gi");
   return str.match(regExp) ? str.match(regExp).length : 0;  
}

Reading Excel file using node.js

You can also use this node module called js-xlsx

1) Install module
npm install xlsx

2) Import module + code snippet

var XLSX = require('xlsx')
var workbook = XLSX.readFile('Master.xlsx');
var sheet_name_list = workbook.SheetNames;
var xlData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
console.log(xlData);

Making authenticated POST requests with Spring RestTemplate for Android

Slightly different approach:

MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("HeaderName", "value");
headers.add("Content-Type", "application/json");

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

HttpEntity<ObjectToPass> request = new HttpEntity<ObjectToPass>(objectToPass, headers);

restTemplate.postForObject(url, request, ClassWhateverYourControllerReturns.class);

How to connect a Windows Mobile PDA to Windows 10

  1. Install

    • Windows Mobile 6 Professional SDK Refresh
    • Windows Mobile 6 Standard SDK Refresh
    • Windows Mobile 6.5 Professional Developer Tool Kit (USA)
    • Windows Mobile 6.5 Standard Developer Tool Kit (USA)
  2. Control Panel > Programs and Features > Add or remove a Windows component

    • NET Framework 3.5
    • Check HTTP and non HTTP
  3. Reinstall WMDC observing your platform x64/x86

  4. Services.msc > Windows Mobile 2003-based device connectivity

    • Logon > Local System
    • Allow service to interact with desktop
  5. Restart your PC

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

Did you read https://software.intel.com/en-us/blogs/2014/03/14/troubleshooting-intel-haxm?

It says "Make sure "Hyper-V", a Windows feature, is not installed/enabled on your system. Hyper-V captures the VT virtualization capability of the CPU, and HAXM and Hyper-V cannot run at the same time. Read this blog: Creating a "no hypervisor" boot entry." https://blogs.msdn.microsoft.com/virtual_pc_guy/2008/04/14/creating-a-no-hypervisor-boot-entry/

I've created the boot entry that disables HyperV and it's working

Simulating Key Press C#

Simple one, add before Main

[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

Code inside Main/Method:

string className = "IEFrame";
string windowName = "New Tab - Windows Internet Explorer";
IntPtr IE = FindWindow(className, windowName);
if (IE == IntPtr.Zero)
{
   return;
}
SetForegroundWindow(IE);
InputSimulator.SimulateKeyPress(VirtualKeyCode.F5);

Note:

  1. Add InputSimulator as reference. To download Click here

  2. To find Class & Window name, use WinSpy++. To download Click here

jQuery DataTable overflow and text-wrapping issues

I settled for the limitation (to some people a benefit) of having my rows only one line of text high. The CSS to contain long strings then becomes:

.datatable td {
  overflow: hidden; /* this is what fixes the expansion */
  text-overflow: ellipsis; /* not supported in all browsers, but I accepted the tradeoff */
  white-space: nowrap;
}

[edit to add:] After using my own code and initially failing, I recognized a second requirement that might help people. The table itself needs to have a fixed layout or the cells will just keep trying to expand to accomodate contents no matter what. If DataTables styles or your own styles don't already do so, you need to set it:

table.someTableClass {
  table-layout: fixed
}

Now that text is truncated with ellipses, to actually "see" the text that is potentially hidden you can implement a tooltip plugin or a details button or something. But a quick and dirty solution is to use JavaScript to set each cell's title to be identical to its contents. I used jQuery, but you don't have to:

  $('.datatable tbody td').each(function(index){
    $this = $(this);
    var titleVal = $this.text();
    if (typeof titleVal === "string" && titleVal !== '') {
      $this.attr('title', titleVal);
    }
  });

DataTables also provides callbacks at the row and cell rendering levels, so you could provide logic to set the titles at that point instead of with a jQuery.each iterator. But if you have other listeners that modify cell text, you might just be better off hitting them with the jQuery.each at the end.

This entire truncation method will ALSO have a limitation you've indicated you're not a fan of: by default columns will have the same width. I identify columns that are going to be consistently wide or consistently narrow, and explicitly set a percentage-based width on them (you could do it in your markup or with sWidth). Any columns without an explicit width get even distribution of the remaining space.

That might seem like a lot of compromises, but the end result was worth it for me.

Closing a Userform with Unload Me doesn't work

As specified by the top answer, I used the following in the code behind the button control.

Private Sub btnClose_Click()
    Unload Me
End Sub

In doing so, it will not attempt to unload a control, but rather will unload the user form where the button control resides. The "Me" keyword refers to the user form object even when called from a control on the user form. If you are getting errors with this technique, there are a couple of possible reasons.

  1. You could be entering the code in the wrong place (such as a separate module)

  2. You might be using an older version of Office. I'm using Office 2013. I've noticed that VBA changes over time.

From my experience, the use of the the DoCmd.... method is more specific to the macro features in MS Access, but not commonly used in Excel VBA.

Under normal (out of the box) conditions, the code above should work just fine.

How to compare two dates in php

You will have to make sure that your dates are valid date objects.

Try this:

$date1=date('d/m/y');
$tempArr=explode('_', '31_12_11');
$date2 = date("d/m/y", mktime(0, 0, 0, $tempArr[1], $tempArr[0], $tempArr[2]));

You can then perform the strtotime() method to get the difference.

How can I put CSS and HTML code in the same file?

<html>
<head>
    <style type="text/css">
    .title {
        color: blue;
        text-decoration: bold;
        text-size: 1em;
    }

    .author {
        color: gray;
    }
    </style>
</head>
<body>
    <p>
    <span class="title">La super bonne</span>
    <span class="author">proposée par Jérém</span>
    </p>
</body>
</html>

On a side note, it would have been much easier to just do this.

How do I check if a directory exists? "is_dir", "file_exists" or both?

$dirname = $_POST["search"];
$filename = "/folder/" . $dirname . "/";

if (!file_exists($filename)) {
    mkdir("folder/" . $dirname, 0777);
    echo "The directory $dirname was successfully created.";
    exit;
} else {
    echo "The directory $dirname exists.";
}

using "if" and "else" Stored Procedures MySQL

The problem is you either haven't closed your if or you need an elseif:

create procedure checando(
    in nombrecillo varchar(30),
    in contrilla varchar(30), 
    out resultado int)
begin 

    if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
        set resultado = 0;
    elseif exists (select * from compas where nombre = nombrecillo) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
end;

Install Application programmatically on Android

Do not forget to request permissions:

android.Manifest.permission.WRITE_EXTERNAL_STORAGE 
android.Manifest.permission.READ_EXTERNAL_STORAGE

Add in AndroidManifest.xml the provider and permission:

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
...
<application>
    ...
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

Create XML file provider res/xml/provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external"
        path="." />
    <external-files-path
        name="external_files"
        path="." />
    <cache-path
        name="cache"
        path="." />
    <external-cache-path
        name="external_cache"
        path="." />
    <files-path
        name="files"
        path="." />
</paths>

Use below example code:

   public class InstallManagerApk extends AppCompatActivity {

    static final String NAME_APK_FILE = "some.apk";
    public static final int REQUEST_INSTALL = 0;

     @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // required permission:
        // android.Manifest.permission.WRITE_EXTERNAL_STORAGE 
        // android.Manifest.permission.READ_EXTERNAL_STORAGE

        installApk();

    }

    ...

    /**
     * Install APK File
     */
    private void installApk() {

        try {

            File filePath = Environment.getExternalStorageDirectory();// path to file apk
            File file = new File(filePath, LoadManagerApkFile.NAME_APK_FILE);

            Uri uri = getApkUri( file.getPath() ); // get Uri for  each SDK Android

            Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
            intent.setData( uri );
            intent.setFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK );
            intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
            intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
            intent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, getApplicationInfo().packageName);

            if ( getPackageManager().queryIntentActivities(intent, 0 ) != null ) {// checked on start Activity

                startActivityForResult(intent, REQUEST_INSTALL);

            } else {
                throw new Exception("don`t start Activity.");
            }

        } catch ( Exception e ) {

            Log.i(TAG + ":InstallApk", "Failed installl APK file", e);
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG)
                .show();

        }

    }

    /**
     * Returns a Uri pointing to the APK to install.
     */
    private Uri getApkUri(String path) {

        // Before N, a MODE_WORLD_READABLE file could be passed via the ACTION_INSTALL_PACKAGE
        // Intent. Since N, MODE_WORLD_READABLE files are forbidden, and a FileProvider is
        // recommended.
        boolean useFileProvider = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;

        String tempFilename = "tmp.apk";
        byte[] buffer = new byte[16384];
        int fileMode = useFileProvider ? Context.MODE_PRIVATE : Context.MODE_WORLD_READABLE;
        try (InputStream is = new FileInputStream(new File(path));
             FileOutputStream fout = openFileOutput(tempFilename, fileMode)) {

            int n;
            while ((n = is.read(buffer)) >= 0) {
                fout.write(buffer, 0, n);
            }

        } catch (IOException e) {
            Log.i(TAG + ":getApkUri", "Failed to write temporary APK file", e);
        }

        if (useFileProvider) {

            File toInstall = new File(this.getFilesDir(), tempFilename);
            return FileProvider.getUriForFile(this,  BuildConfig.APPLICATION_ID, toInstall);

        } else {

            return Uri.fromFile(getFileStreamPath(tempFilename));

        }

    }

    /**
     * Listener event on installation APK file
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == REQUEST_INSTALL) {

            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(this,"Install succeeded!", Toast.LENGTH_SHORT).show();
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(this,"Install canceled!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this,"Install Failed!", Toast.LENGTH_SHORT).show();
            }

        }

    }

    ...

}

Insert array into MySQL database with PHP

Here is my full solution to this based on the accepted answer.

Usage example:

include("./assets/php/db.php");
$data = array('field1' => 'data1', 'field2'=> 'data2');
insertArr("databaseName.tableName", $data);

db.php

<?PHP
/**
 * Class to initiate a new MySQL connection based on $dbInfo settings found in dbSettings.php
 *
 * @example
 *    $db = new database(); // Initiate a new database connection
 *    mysql_close($db->get_link());
 */
class database{
    protected $databaseLink;
    function __construct(){
        include "dbSettings.php";
        $this->database = $dbInfo['host'];
        $this->mysql_user = $dbInfo['user'];
        $this->mysql_pass = $dbInfo['pass'];
        $this->openConnection();
        return $this->get_link();
    }
    function openConnection(){
    $this->databaseLink = mysql_connect($this->database, $this->mysql_user, $this->mysql_pass);
    }

    function get_link(){
    return $this->databaseLink;
    }
}

/**
 * Insert an associative array into a MySQL database
 *
 * @example
 *    $data = array('field1' => 'data1', 'field2'=> 'data2');
 *    insertArr("databaseName.tableName", $data);
 */
function insertArr($tableName, $insData){
    $db = new database();
    $columns = implode(", ",array_keys($insData));
    $escaped_values = array_map('mysql_real_escape_string', array_values($insData));
    foreach ($escaped_values as $idx=>$data) $escaped_values[$idx] = "'".$data."'";
    $values  = implode(", ", $escaped_values);
    $query = "INSERT INTO $tableName ($columns) VALUES ($values)";
    mysql_query($query) or die(mysql_error());
    mysql_close($db->get_link());
}
?>

dbSettings.php

<?PHP
$dbInfo = array(
    'host'      => "localhost",
    'user'      => "root",
    'pass'      => "password"
);
?>

How to load my app from Eclipse to my Android phone instead of AVD

I had the same problem, and have not been able to get Eclipse in Windows 7 to recognise the device. The device is correctly configured, Windows 7 recognises it on the USB port, and I edited the Run settings in Eclipse to prompt for a device, and it is just not there.

I ran it with the following steps:

  • Connect the device to the computer with USB.
  • Ensure the device is not locked (ie. timed out in the UI). I have to keep unlocking it while I'm working.
  • Wait for Windows to recognise the USB device, and when the autoplay menu comes up select Open device to view files. It should open up the file system in the device, in Explorer.
  • In Explorer go to the Eclipse workspace and find the apk file from the build (eg. MyFirstApp.apk)
  • Copy the apk file to the Downloads directory on the device
  • On the device, use the My Files app (or similar) to open the Downloads directory.
  • Click the downloaded file (My First App.apk) and Android offers to install it
  • Select install
  • The app is now in the installed Apps. Run it.

A second method is to mail the apk file to the device and then download and install it. (Credits to a post on SO which I can't find now).

A third method is to use DropBox. This requires installation of DropBox on the PC and on the device (from the play store) but once both are set up it runs very smoothly. Just share a DropBox folder between the two devices, and then drop the APK into that folder on the PC, and open it on the device. With this method you don't need a USB connection, and can also install the APK on multiple devices. It also assists the management of multiple development versions (by making a separate sub-folder for each version).

Encode String to UTF-8

This solved my problem

    String inputText = "some text with escaped chars"
    InputStream is = new ByteArrayInputStream(inputText.getBytes("UTF-8"));

What is the difference between varchar and nvarchar?

I always use nvarchar as it allows whatever I'm building to withstand pretty much any data I throw at it. My CMS system does Chinese by accident, because I used nvarchar. These days, any new applications shouldn't really be concerned with the amount of space required.

How to align checkboxes and their labels consistently cross-browsers

Working off of One Crayon's solution, I have something that works for me and is simpler:

_x000D_
_x000D_
.font2 {font-family:Arial; font-size:32px} /* Sample font */_x000D_
_x000D_
input[type=checkbox], input[type=radio] {_x000D_
  vertical-align: middle;_x000D_
  position: relative;_x000D_
  bottom: 1px;_x000D_
}_x000D_
_x000D_
input[type=radio] { _x000D_
  bottom: 2px; _x000D_
} 
_x000D_
<label><input type="checkbox" /> Label text</label>_x000D_
<p class="font2">_x000D_
  <label><input type="checkbox"/> Label text</label>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Renders pixel-for-pixel the same in Safari (whose baseline I trust) and both Firefox and IE7 check out as good. It also works for various label font sizes, big and small. Now, for fixing IE's baseline on selects and inputs...


Update: (Third-Party Edit)

The proper bottom position depends on font-family and font-size! I found using bottom: .08em; for checkbox & radio elements is a good general value. I tested it in Chrome/Firefox/IE11 in windows with Arial & Calibri fonts using several small/mid/large font-sizes.

_x000D_
_x000D_
.font2, .font2 input {font-family:Arial; font-size:32px} /* Sample font */_x000D_
_x000D_
input[type=checkbox], input[type=radio] {_x000D_
  vertical-align: middle; _x000D_
  position: relative;_x000D_
  bottom: .08em; /* this is a better value for different fonts! */_x000D_
}
_x000D_
<label><input type="checkbox" /> Label text</label> _x000D_
_x000D_
<p class="font2">_x000D_
  <label><input type="checkbox"/> Label text</label>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Call to getLayoutInflater() in places not in activity

or

View.inflate(context, layout, parent)

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

_x000D_
_x000D_
angular.module('testApp',[]).controller('testCTRL',function($scope)_x000D_
                               _x000D_
{_x000D_
  _x000D_
$scope.testingModel = "This is ModelData.If you change textbox data it will reflected here..because model is two way binding reflected in both.";_x000D_
$scope.testingBind = "This is BindData.You can't change this beacause it is binded with html..In above textBox i tried to use bind, but it is not working because it is one way binding.";            _x000D_
});
_x000D_
div input{_x000D_
width:600px;  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<head>Diff b/w model and bind</head>_x000D_
<body data-ng-app="testApp">_x000D_
    <div data-ng-controller="testCTRL">_x000D_
        Model-Data : <input type="text" data-ng-model="testingModel">_x000D_
        <p>{{testingModel}}</p>_x000D_
          <input type="text" data-ng-bind="testingBind">_x000D_
          <p ng-bind="testingBind"></p>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to check the presence of php and apache on ubuntu server through ssh

Try this.

dpkg -s apache2 | grep Status 

dpkg -s php5 | grep Status

Python: Importing urllib.quote

Use six:

from six.moves.urllib.parse import quote

six will simplify compatibility problems between Python 2 and Python 3, such as different import paths.

php hide ALL errors

The best way is to build your script in a way it cannot create any errors! When there is something that can create a Notice or an Error there is something wrong with your script and the checking of variables and environment!

If you want to hide them anyway: error_reporting(0);

psql - save results of command to a file

I assume that there exist some internal psql command for this, but you could also run the script command from util-linux-ng package:

DESCRIPTION Script makes a typescript of everything printed on your terminal.

Add new item in existing array in c#.net

I would use a List if you need a dynamically sized array:

List<string> ls = new List<string>();
ls.Add("Hello");

What's the console.log() of java?

Use the Android logging utility.

http://developer.android.com/reference/android/util/Log.html

Log has a bunch of static methods for accessing the different log levels. The common thread is that they always accept at least a tag and a log message.

Tags are a way of filtering output in your log messages. You can use them to wade through the thousands of log messages you'll see and find the ones you're specifically looking for.

You use the Log functions in Android by accessing the Log.x objects (where the x method is the log level). For example:

Log.d("MyTagGoesHere", "This is my log message at the debug level here");
Log.e("MyTagGoesHere", "This is my log message at the error level here");

I usually make it a point to make the tag my class name so I know where the log message was generated too. Saves a lot of time later on in the game.

You can see your log messages using the logcat tool for android:

adb logcat

Or by opening the eclipse Logcat view by going to the menu bar

Window->Show View->Other then select the Android menu and the LogCat view

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

AngularJS does not send hidden field value

update @tymeJV 's answer eg:

 <div style="display: none">
    <input type="text" name='price' ng-model="price" ng-init="price = <%= @product.price.to_s %>" >
 </div>

How can I make the browser wait to display the page until it's fully loaded?

There is certainly a valid use for this. One is to prevent people from clicking on links/causing JavaScript events to occur until all the page elements and JavaScript have loaded.

In IE, you could use page transitions which mean the page doesn't display until it's fully loaded:

<meta http-equiv="Page-Enter" content="blendTrans(Duration=.01)" />
<meta http-equiv="Page-Exit" content="blendTrans(Duration=.01)" />

Notice the short duration. It's just enough to make sure the page doesn't display until it's fully loaded.

In FireFox and other browsers, the solution I've used is to create a DIV that is the size of the page and white, then at the very end of the page put in JavaScript that hides it. Another way would be to use jQuery and hide it as well. Not as painless as the IE solution but both work well.

How do I read image data from a URL in Python?

Use StringIO to turn the read string into a file-like object:

from StringIO import StringIO
import urllib

Image.open(StringIO(urllib.requests.urlopen(url).read()))