Programs & Examples On #Destruction

undefined reference to 'std::cout'

Compile the program with:

g++ -Wall -Wextra -Werror -c main.cpp -o main.o
     ^^^^^^^^^^^^^^^^^^^^ <- For listing all warnings when your code is compiled.

as cout is present in the C++ standard library, which would need explicit linking with -lstdc++ when using gcc; g++ links the standard library by default.

With gcc, (g++ should be preferred over gcc)

gcc main.cpp -lstdc++ -o main.o

C++ Boost: undefined reference to boost::system::generic_category()

Il the library is not installed you should give boost libraries folder:

example:

g++ -L/usr/lib/x86_64-linux-gnu -lboost_system -lboost_filesystem prog.cpp -o prog

undefined reference to `std::ios_base::Init::Init()'

Most of these linker errors occur because of missing libraries.

I added the libstdc++.6.dylib in my Project->Targets->Build Phases-> Link Binary With Libraries.

That solved it for me on Xcode 6.3.2 for iOS 8.3

Cheers!

Requested bean is currently in creation: Is there an unresolvable circular reference?

@Resource annotation on field level also could be used to declare look up at runtime

How to compile a c++ program in Linux?

Try this:

g++ -o hi hi.cpp

gcc is only for C

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

If it is going to be a web based application, you can also use the ServletContextListener interface.

public class SLF4JBridgeListener implements ServletContextListener {

   @Autowired 
   ThreadPoolTaskExecutor executor;

   @Autowired 
   ThreadPoolTaskScheduler scheduler;

    @Override
    public void contextInitialized(ServletContextEvent sce) {

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
         scheduler.shutdown();
         executor.shutdown();     

    }

}

How to turn off the Eclipse code formatter for certain sections of Java code?

This hack works:

String x = "s" + //Formatter Hack
    "a" + //
    "c" + //
    "d";

I would suggest not to use the formatter. Bad code should look bad not artificially good. Good code takes time. You cannot cheat on quality. Formatting is part of source code quality.

How to compile C++ under Ubuntu Linux?

even you can compile your c++ code by gcc Sounds funny ?? Yes it is. try it

$  gcc avishay.cpp -lstdc++

enjoy

How many threads is too many?

ryeguy, I am currently developing a similar application and my threads number is set to 15. Unfortunately if I increase it at 20, it crashes. So, yes, I think the best way to handle this is to measure whether or not your current configuration allows more or less than a number X of threads.

throwing exceptions out of a destructor

As an addition to the main answers, which are good, comprehensive and accurate, I would like to comment about the article you reference - the one that says "throwing exceptions in destructors is not so bad".

The article takes the line "what are the alternatives to throwing exceptions", and lists some problems with each of the alternatives. Having done so it concludes that because we can't find a problem-free alternative we should keep throwing exceptions.

The trouble is is that none of the problems it lists with the alternatives are anywhere near as bad as the exception behaviour, which, let's remember, is "undefined behaviour of your program". Some of the author's objections include "aesthetically ugly" and "encourage bad style". Now which would you rather have? A program with bad style, or one which exhibited undefined behaviour?

how to dynamically add options to an existing select in vanilla javascript

This tutorial shows exactly what you need to do: Add options to an HTML select box with javascript

Basically:

 daySelect = document.getElementById('daySelect');
 daySelect.options[daySelect.options.length] = new Option('Text 1', 'Value1');

Are there any standard exit status codes in Linux?

There are no standard exit codes, aside from 0 meaning success. Non-zero doesn't necessarily mean failure either.

stdlib.h does define EXIT_FAILURE as 1 and EXIT_SUCCESS as 0, but that's about it.

The 11 on segfault is interesting, as 11 is the signal number that the kernel uses to kill the process in the event of a segfault. There is likely some mechanism, either in the kernel or in the shell, that translates that into the exit code.

How do I run two commands in one line in Windows CMD?

With windows 10 you can also use scriptrunner:

ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror

it allows you to start few commands on one line you want you can run them consecutive or without waiting each other, you can put timeouts and rollback on error.

curl: (6) Could not resolve host: application

I was getting this error too. I resolved it by installing: https://git-scm.com/

and running the command from the Git Bash window.

How to remove/delete a large file from commit history in Git repository?

Use the BFG Repo-Cleaner, a simpler, faster alternative to git-filter-branch specifically designed for removing unwanted files from Git history.

Carefully follow the usage instructions, the core part is just this:

$ java -jar bfg.jar --strip-blobs-bigger-than 100M my-repo.git

Any files over 100MB in size (that aren't in your latest commit) will be removed from your Git repository's history. You can then use git gc to clean away the dead data:

$ git gc --prune=now --aggressive

The BFG is typically at least 10-50x faster than running git-filter-branch, and generally easier to use.

Full disclosure: I'm the author of the BFG Repo-Cleaner.

Django - iterate number in for loop of a template

[Django HTML template doesn't support index as of now], but you can achieve the goal:

If you use Dictionary inside Dictionary in views.py then iteration is possible using key as index. example:

{% for key, value in DictionartResult.items %} <!-- dictionartResult is a dictionary having key value pair-->
<tr align="center">
    <td  bgcolor="Blue"><a href={{value.ProjectName}}><b>{{value.ProjectName}}</b></a></td>
    <td> {{ value.atIndex0 }} </td>         <!-- atIndex0 is a key which will have its value , you can treat this key as index to resolve-->
    <td> {{ value.atIndex4 }} </td>
    <td> {{ value.atIndex2 }} </td>
</tr>
{% endfor %}

Elseif you use List inside dictionary then not only first and last iteration can be controlled, but all index can be controlled. example:

{% for key, value in DictionaryResult.items %}
    <tr align="center">
    {% for project_data in value %}
        {% if  forloop.counter <= 13 %}  <!-- Here you can control the iteration-->
            {% if forloop.first %}
                <td bgcolor="Blue"><a href={{project_data}}><b> {{ project_data }} </b></a></td> <!-- it will always refer to project_data[0]-->
            {% else %}
                <td> {{ project_data }} </td> <!-- it will refer to all items in project_data[] except at index [0]-->
            {% endif %}
            {% endif %}
    {% endfor %}
    </tr>
{% endfor %}

End If ;)

// Hope have covered the solution with Dictionary, List, HTML template, For Loop, Inner loop, If Else. Django HTML Documentaion for more methods: https://docs.djangoproject.com/en/2.2/ref/templates/builtins/

select a value where it doesn't exist in another table

You could use NOT IN:

SELECT A.* FROM A WHERE ID NOT IN(SELECT ID FROM B)

However, meanwhile i prefer NOT EXISTS:

SELECT A.* FROM A WHERE NOT EXISTS(SELECT 1 FROM B WHERE B.ID=A.ID)

There are other options as well, this article explains all advantages and disadvantages very well:

Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?

Can I convert a boolean to Yes/No in a ASP.NET GridView

Add a method to your page class like this:

public string YesNo(bool active) 
{
  return active ? "Yes" : "No";
}

And then in your TemplateField you Bind using this method:

<%# YesNo(Active) %>

Command line: search and replace in all filenames matched by grep

Do you mean search and replace a string in all files matched by grep?

perl -p -i -e 's/oldstring/newstring/g' `grep -ril searchpattern *`

Edit

Since this seems to be a fairly popular question thought I'd update.

Nowadays I mostly use ack-grep as it's more user-friendly. So the above command would be:

perl -p -i -e 's/old/new/g' `ack -l searchpattern`

To handle whitespace in file names you can run:

ack --print0 -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'

you can do more with ack-grep. Say you want to restrict the search to HTML files only:

ack --print0 --html -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'

And if white space is not an issue it's even shorter:

perl -p -i -e 's/old/new/g' `ack -l --html searchpattern`
perl -p -i -e 's/old/new/g' `ack -f --html` # will match all html files

Best Python IDE on Linux

I haven't played around with it much but eclipse/pydev feels nice.

CodeIgniter Active Record not equal

According to the manual this should work:

Custom key/value method:

You can include an operator in the first parameter in order to control the comparison:

$this->db->where('name !=', $name);
$this->db->where('id <', $id);
Produces: WHERE name != 'Joe' AND id < 45

Search for $this->db->where(); and look at item #2.

String "true" and "false" to boolean

You could consider only appending internal to your url if it is true, then if the checkbox isn't checked and you don't append it params[:internal] would be nil, which evaluates to false in Ruby.

I'm not that familiar with the specific jQuery you're using, but is there a cleaner way to call what you want than manually building a URL string? Have you had a look at $get and $ajax?

How do implement a breadth first traversal?

public static boolean BFS(ListNode n, int x){
        if(n==null){
           return false;
       }
Queue<ListNode<Integer>> q = new Queue<ListNode<Integer>>();
ListNode<Integer> tmp = new ListNode<Integer>(); 
q.enqueue(n);
tmp = q.dequeue();
if(tmp.val == x){
    return true;
}
while(tmp != null){
    for(ListNode<Integer> child: n.getChildren()){
        if(child.val == x){
            return true;
        }
        q.enqueue(child);
    }

    tmp = q.dequeue();
}
return false;
}

How can we generate getters and setters in Visual Studio?

Enter image description here

On behalf of the Visual Studio tool, we can easily generate C# properties using an online tool called C# property generator.

HTTP requests and JSON parsing in Python

I recommend using the awesome requests library:

import requests

url = 'http://maps.googleapis.com/maps/api/directions/json'

params = dict(
    origin='Chicago,IL',
    destination='Los+Angeles,CA',
    waypoints='Joplin,MO|Oklahoma+City,OK',
    sensor='false'
)

resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below

JSON Response Content: https://requests.readthedocs.io/en/master/user/quickstart/#json-response-content

how to set mongod --dbpath

Scenario: MongoDB(version v4.0.9).

  1. Set custom folder(with name: myCustomDatabases), where to store databases.
  2. In custom folder(with name: myCustomDatabases), have to create database (with name: newDb).

Resolve:

  1. Create custom folder(with name: myCustomDatabases):

    D:>md myCustomDatabases
    
  2. Run 'mongod --dbpath' with path to custom folder(with name: myCustomDatabases):

    mongod --dbpath "D:\myCustomDatabases"
    
  3. From another 'cmd' run 'mongo':

    D:>mongo
    

    3.1. Show all databases, stored in custom folder(with name: myCustomDatabases):

    >show dbs
    admin   0.000GB
    config  0.000GB
    local   0.000GB
    

    3.2. Use database with name newDb:

    > use newDb
    switched to db newDb
    

    3.3. Show all databases, stored in custom folder(with name: myCustomDatabases):

    >show dbs
    admin   0.000GB
    config  0.000GB
    local   0.000GB
    

    !!! Noticed, that newDb is NOT in the list !!!

    3.4. Have to create a collection with a document, which will create the database newDb.

    > db.Cats.insert({name: 'Leo'})
    WriteResult({ "nInserted" : 1 })
    

    The insert({name: 'Leo'}) operation creates: the database newDB and the collection Cats, because they do not exist.

    3.5. Now the new created database newDb will be displayed in the list.

    > show dbs
    admin   0.000GB
    config  0.000GB
    local   0.000GB
    newDb   0.000GB
    

    3.6. Now in custom folder D:\myCustomDatabases, have database newDb.

In Angular, how to pass JSON object/array into directive?

What you need is properly a service:

.factory('DataLayer', ['$http',

    function($http) {

        var factory = {};
        var locations;

        factory.getLocations = function(success) {
            if(locations){
                success(locations);
                return;
            }
            $http.get('locations/locations.json').success(function(data) {
                locations = data;
                success(locations);
            });
        };

        return factory;
    }
]);

The locations would be cached in the service which worked as singleton model. This is the right way to fetch data.

Use this service DataLayer in your controller and directive is ok as following:

appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
    DataLayer.getLocations(function(data){
        $scope.locations = data;
    });
});

.directive('map', function(DataLayer) {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function(scope, element, attrs) {

            DataLayer.getLocations(function(data) {
                angular.forEach(data, function(location, key){
                    //do something
                });
            });
        }
    };
});

How to get "wc -l" to print just the number of lines without file name?

Obviously, there are a lot of solutions to this. Here is another one though:

wc -l somefile | tr -d "[:alpha:][:blank:][:punct:]"

This only outputs the number of lines, but the trailing newline character (\n) is present, if you don't want that either, replace [:blank:] with [:space:].

jQuery animate backgroundColor

I like using delay() to get this done, here's an example:

jQuery(element).animate({ backgroundColor: "#FCFCD8" },1).delay(1000).animate({ backgroundColor: "#EFEAEA" }, 1500);

This can be called by a function, with "element" being the element class/name/etc. The element will instantly appear with the #FCFCD8 background, hold for a second, then fade into #EFEAEA.

onclick on a image to navigate to another page using Javascript

maybe this is what u want?

<a href="#" id="bottle" onclick="document.location=this.id+'.html';return false;" >
    <img src="../images/bottle.jpg" alt="bottle" class="thumbnails" />
</a>

edit: keep in mind that anyone who does not have javascript enabled will not be able to navaigate to the image page....

What is the difference between 'typedef' and 'using' in C++11?

The using syntax has an advantage when used within templates. If you need the type abstraction, but also need to keep template parameter to be possible to be specified in future. You should write something like this.

template <typename T> struct whatever {};

template <typename T> struct rebind
{
  typedef whatever<T> type; // to make it possible to substitue the whatever in future.
};

rebind<int>::type variable;

template <typename U> struct bar { typename rebind<U>::type _var_member; }

But using syntax simplifies this use case.

template <typename T> using my_type = whatever<T>;

my_type<int> variable;
template <typename U> struct baz { my_type<U> _var_member; }

Angular: How to download a file from HttpClient?

After spending much time searching for a response to this answer: how to download a simple image from my API restful server written in Node.js into an Angular component app, I finally found a beautiful answer in this web Angular HttpClient Blob. Essentially it consist on:

API Node.js restful:

   /* After routing the path you want ..*/
  public getImage( req: Request, res: Response) {

    // Check if file exist...
    if (!req.params.file) {
      return res.status(httpStatus.badRequest).json({
        ok: false,
        msg: 'File param not found.'
      })
    }
    const absfile = path.join(STORE_ROOT_DIR,IMAGES_DIR, req.params.file);

    if (!fs.existsSync(absfile)) {
      return res.status(httpStatus.badRequest).json({
        ok: false,
        msg: 'File name not found on server.'
      })
    }
    res.sendFile(path.resolve(absfile));
  }

Angular 6 tested component service (EmployeeService on my case):

  downloadPhoto( name: string) : Observable<Blob> {
    const url = environment.api_url + '/storer/employee/image/' + name;

    return this.http.get(url, { responseType: 'blob' })
      .pipe(
        takeWhile( () => this.alive),
        filter ( image => !!image));
  }

Template

 <img [src]="" class="custom-photo" #photo>

Component subscriber and use:

@ViewChild('photo') image: ElementRef;

public LoadPhoto( name: string) {
    this._employeeService.downloadPhoto(name)
          .subscribe( image => {
            const url= window.URL.createObjectURL(image);
            this.image.nativeElement.src= url;
          }, error => {
            console.log('error downloading: ', error);
          })    
}

How to escape a JSON string containing newline characters using JavaScript?

EDIT: Check if the api you’re interacting with is set to Content-Type: application/json, &/or if your client http library is both stringify-ing and parsing the http request body behind the scenes. My client library was generated by swagger, and was the reason I needed to apply these hacks, as the client library was stringifying my pre-stringified body (body: “jsonString”, instead of body: { ...normal payload }). All I had to do was change the api to Content-Type: text/plain, which removed the JSON stringify/parsing on that route, and then none of these hacks were needed. You can also change only the "consumes" or "produces" portion of the api, see here.

ORIGINAL: If your Googles keep landing you here and your api throws errors unless your JSON double quotes are escaped ("{\"foo\": true}"), all you need to do is stringify twice e.g. JSON.stringify(JSON.stringify(bar))

How to set java_home on Windows 7?

In cmd (temporarily for that cmd window):

set JAVA_HOME="C:\\....\java\jdk1.x.y_zz"

echo %JAVA_HOME%

set PATH=%PATH%;%JAVA_HOME%\bin

echo %PATH%

Adding a column to a dataframe in R

That is a pretty standard use case for apply():

R> vec <- 1:10
R> DF <- data.frame(start=c(1,3,5,7), end=c(2,6,7,9))
R> DF$newcol <- apply(DF,1,function(row) mean(vec[ row[1] : row[2] ] ))
R> DF
  start end newcol
1     1   2    1.5
2     3   6    4.5
3     5   7    6.0
4     7   9    8.0
R> 

You can also use plyr if you prefer but here is no real need to go beyond functions from base R.

How to run SQL script in MySQL?

You have quite a lot of options:

  • use the MySQL command line client: mysql -h hostname -u user database < path/to/test.sql
  • Install the MySQL GUI tools and open your SQL file, then execute it
  • Use phpmysql if the database is available via your webserver

phpinfo() is not working on my CentOS server

Be sure that the tag "php" is stick in the code like this:

?php phpinfo(); ?>

Not like this:

? php phpinfo(); ?>

OR the server will treat it as a (normal word), so the server will not understand the language you are writing to deal with it so it will be blank.

I know it's a silly error ...but it happened ^_^

AngularJS: How to run additional code after AngularJS has rendered a template?

I have found the simplest (cheap and cheerful) solution is simply add an empty span with ng-show = "someFunctionThatAlwaysReturnsZeroOrNothing()" to the end of the last element rendered. This function will be run when to check if the span element should be displayed. Execute any other code in this function.

I realize this is not the most elegant way to do things, however, it works for me...

I had a similar situation, though slightly reversed where I needed to remove a loading indicator when an animation began, on mobile devices angular was initializing much faster than the animation to be displayed, and using an ng-cloak was insufficient as the loading indicator was removed well before any real data was displayed. In this case I just added the my return 0 function to the first rendered element, and in that function flipped the var that hides the loading indicator. (of course I added an ng-hide to the loading indicator triggered by this function.

error: RPC failed; curl transfer closed with outstanding read data remaining

When I tried cloning from the remote, got the same issue repeatedly:

remote: Counting objects: 182, done.
remote: Compressing objects: 100% (149/149), done.
error: RPC failed; curl 18 transfer closed with outstanding read data remaining
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed

Finally this worked for me:

git clone https://[email protected]/repositoryName.git --depth 1

How to edit the size of the submit button on a form?

Using CSS.

Either inside your <head> tag (the #search means "the element with an ID of search")

<style type="text/css">
    input#search
    {
        width: 20px;
        height: 20px;
    }
</style>

Or inline, in your <input> tag

<input type="submit" id="search" value="Search"  style="width: 20px; height: 20px;" />

How to set ANDROID_HOME path in ubuntu?

Download the Android SDK to the machine. (Suppose that the location is /home/zelong/Android/Sdk) (home/username/Android/Sdk)

Add these lines to the file ~/.bashrc (located at home/username/.bashrc)

export ANDROID_HOME="/home/zelong/Android/Sdk"
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/platform-tools

This will make it permanent for the current user because every time the machine boots, it will run this script and set the enviroment path.

After making this change, remember to save it.

Then run source ~/.bashrc to apply the changes or restart your terminal.

Test if it works:

zelong@zelong-ThinkPad-T430:~$ echo $ANDROID_HOME
/home/zelong/Android/Sdk
zelong@zelong-ThinkPad-T430:~$ which android
/home/zelong/Android/Sdk/tools/android
zelong@zelong-ThinkPad-T430:~$ which adb
/home/zelong/Android/Sdk/platform-tools/adb

As we can see,

android command line locates under tools

adb command line locates under platform-tools

Efficiently sorting a numpy array in descending order?

i suggest using this ...

np.arange(start_index, end_index, intervals)[::-1]

for example:

np.arange(10, 20, 0.5)
np.arange(10, 20, 0.5)[::-1]

Then your resault:

[ 19.5,  19. ,  18.5,  18. ,  17.5,  17. ,  16.5,  16. ,  15.5,
    15. ,  14.5,  14. ,  13.5,  13. ,  12.5,  12. ,  11.5,  11. ,
    10.5,  10. ]

Angular 4 default radio button checked by default

getting following error

_x000D_
_x000D_
It happens:  Error: 
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.  Example:
_x000D_
_x000D_
_x000D_

How can I keep Bootstrap popovers alive while being hovered?

I found the mouseleave will not fire when weird things happen, like the window focus changes suddenly, then the user comes back to the browser. In cases like that, mouseleave will never fire until the cursor goes over and leaves the element again.

This solution I came up with relies on mouseenter on the window object, so it disappears when the mouse is moved anywhere else on the page.

This was designed to work with having multiple elements on the page that will trigger it (like in a table).

var allMenus = $(".menus");
allMenus.popover({
    html: true,
    trigger: "manual",
    placement: "bottom",
    content: $("#menuContent")[0].outerHTML
}).on("mouseenter", (e) => {
    allMenus.not(e.target).popover("hide");
    $(e.target).popover("show");
    e.stopPropagation();
}).on("shown.bs.popover", () => {
    $(window).on("mouseenter.hidepopover", (e) => {
        if ($(e.target).parents(".popover").length === 0) {
            allMenus.popover("hide");
            $(window).off("mouseenter.hidepopover");
        }
    });
});

When do you use Java's @Override annotation and why?

It does allow you (well, the compiler) to catch when you've used the wrong spelling on a method name you are overriding.

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

Is there a way to get the source code from an APK file?

I've been driving myself crazy for days trying to get dex2jar to work on a fedora 31 laptop against an apk that just wasn't going to work. This python 3 script did the trick in minutes and installing jd-gui made class files human readable.

http://java-decompiler.github.io/

https://github.com/Storyyeller/enjarify

specifically, here's what I ran:

# i installed apktool before the rest of the stuff, may not need it but here it is
$> cd /opt
$> sudo mkdir apktool
$> cd apktool/
$> sudo wget https://raw.githubusercontent.com/iBotPeaches/Apktool/master/scripts/linux/apktool
$> sudo wget https://bitbucket.org/iBotPeaches/apktool/downloads/apktool_2.4.1.jar
$> sudo mv apktool_2.4.1.jar apktool.jar
$> sudo mv apktool* /usr/bin/
$> sudo chmod a+x /usr/bin/apktool*

# and enjarify
$> cd /opt
$> sudo git clone https://github.com/Storyyeller/enjarify.git
$> cd enjarify/
$> sudo ln -s /opt/enjarify/enjarify.sh /usr/bin/enjarify

# and finally jd-gui
$> cd /opt
$> sudo git clone https://github.com/java-decompiler/jd-gui.git
$> cd jd-gui/
$> sudo ./gradlew build

# I made an alias to kick of the jd-gui with short commandline rather than long java -jar blahblahblah :)
$> echo "jd-gui='java -jar /opt/jd-gui/build/launch4j/lib/jd-gui-1.6.6.jar'" >> ~/.bashrc

Now one should be able to rum the following to get class files:

$> enjarify yourapkfile.apk

And to start jd-gui:

$> jd-gui

Then just open your class files!

How to write a file with C in Linux?

You need to write() the read() data into the new file:

ssize_t nrd;
int fd;
int fd1;

fd = open(aa[1], O_RDONLY);
fd1 = open(aa[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
while (nrd = read(fd,buffer,50)) {
    write(fd1,buffer,nrd);
}

close(fd);
close(fd1);

Update: added the proper opens...

Btw, the O_CREAT can be OR'd (O_CREAT | O_WRONLY). You are actually opening too many file handles. Just do the open once.

Fully custom validation error message with Rails

Rails3 Code with fully localized messages:

In the model user.rb define the validation

validates :email, :presence => true

In config/locales/en.yml

en:  
  activerecord:
    models: 
      user: "Customer"
    attributes:
      user:
        email: "Email address"
    errors:
      models:
        user:
          attributes:
            email:
              blank: "cannot be empty"

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

Split Spark Dataframe string column into multiple columns

Here's another approach, in case you want split a string with a delimiter.

import pyspark.sql.functions as f

df = spark.createDataFrame([("1:a:2001",),("2:b:2002",),("3:c:2003",)],["value"])
df.show()
+--------+
|   value|
+--------+
|1:a:2001|
|2:b:2002|
|3:c:2003|
+--------+

df_split = df.select(f.split(df.value,":")).rdd.flatMap(
              lambda x: x).toDF(schema=["col1","col2","col3"])

df_split.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   a|2001|
|   2|   b|2002|
|   3|   c|2003|
+----+----+----+

I don't think this transition back and forth to RDDs is going to slow you down... Also don't worry about last schema specification: it's optional, you can avoid it generalizing the solution to data with unknown column size.

How to open remote files in sublime text 3

On server

Install rsub:

wget -O /usr/local/bin/rsub \https://raw.github.com/aurora/rmate/master/rmate
chmod a+x /usr/local/bin/rsub

On local

  1. Install rsub Sublime3 package:

On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub and install it

  1. Open command line and connect to remote server:

ssh -R 52698:localhost:52698 server_user@server_address

  1. after connect to server run this command on server:

rsub path_to_file/file.txt

  1. File opening auto in Sublime 3

As of today (2018/09/05) you should use : https://github.com/randy3k/RemoteSubl because you can find it in packagecontrol.io while "rsub" is not present.

How to align linearlayout to vertical center?

Change orientation and gravity in

<LinearLayout
    android:id="@+id/groupNumbers"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:layout_weight="0.7"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

to

android:orientation="vertical"
android:layout_gravity="center_vertical"

You are adding orientation: horizontal, so the layout will contain all elements in single horizontal line. Which won't allow you to get the element in center.

Hope this helps.

Annotation @Transactional. How to rollback?

You can throw an unchecked exception from the method which you wish to roll back. This will be detected by spring and your transaction will be marked as rollback only.

I'm assuming you're using Spring here. And I assume the annotations you refer to in your tests are the spring test based annotations.

The recommended way to indicate to the Spring Framework's transaction infrastructure that a transaction's work is to be rolled back is to throw an Exception from code that is currently executing in the context of a transaction.

and note that:

please note that the Spring Framework's transaction infrastructure code will, by default, only mark a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException.

How to handle ListView click in Android

This solution is really minimalistic and doesn't mess up your code.

In your list_item.xml (NOT listView!) assign the attribute android:onClick like this:

<RelativeLayout android:onClick="onClickDoSomething">

and then in your activity call this method:

public void onClickDoSomething(View view) {
   // the view is the line you have clicked on
}

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

How to start rails server?

For rails 4.1.4 you can start server:

$ bin/rails server

How to use Comparator in Java to sort

You want to implement Comparable, not Comparator. You need to implement the compareTo method. You're close though. Comparator is a "3rd party" comparison routine. Comparable is that this object can be compared with another.

public int compareTo(Object obj1) {
  People that = (People)obj1;
  Integer p1 = this.getId();
  Integer p2 = that.getid();

  if (p1 > p2 ){
   return 1;
  }
  else if (p1 < p2){
   return -1;
  }
  else
   return 0;
 }

Note, you may want to check for nulls in here for getId..just in case.

How to remove a character at the end of each line in unix

Try doing this :

awk '{print substr($0, 1, length($0)-1)}' file.txt

This is more generic than just removing the final comma but any last character

If you'd want to only remove the last comma with awk :

awk '{gsub(/,$/,""); print}' file.txt

How to correctly display .csv files within Excel 2013?

Taken from https://superuser.com/questions/238944/how-to-force-excel-to-open-csv-files-with-data-arranged-in-columns

The behavior of Excel when opening CSV files heavily depends on your local settings and the selected list separator under Region and language » Formats » Advanced. By default Excel will assume every CSV was saved with that separator. Which is true as long as the CSV doesn't come from another country!

If your customers are in other countries, they may see other results then you think.

For example, here you see that a German Excel will use semicolon instead of comma like in the U.S.

Regional Settings

How to close <img> tag properly?

It's helpful to have the closing tag if you will ever try to read it with an XHTML parser. Might be an edge case but I do it all the time. It does no harm having it, and means I know we can use an array of XML readers which won't keel over when they hit an unclosed tag.

If you are never going to try to parse the content, then ignore the closing.

Background color in input and text fields

The best solution is the attribute selector in CSS (input[type="text"]) as the others suggested.

But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.

In this case your only option seems to be to define classes on input elements.

<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...

and target them with a class selector:

input.input-box, textarea { background: cyan; }

How do I right align div elements?

Do you mean like this? http://jsfiddle.net/6PyrK/1

You can add the attributes of float:right and clear:both; to the form and button

Convert String to System.IO.Stream

string str = "asasdkopaksdpoadks";
byte[] data = Encoding.ASCII.GetBytes(str);
MemoryStream stm = new MemoryStream(data, 0, data.Length);

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Sending JSON data with NodeJS on AJAX call :

$.ajax({
    url: '/listClientsNames',
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify({foo:'bar'})
}).done(function(response){
    console.log("response :: "+response[0].nom);
});

Be aware of removing white spaces.

app.post("/listClientsNames", function(req,res){

        var querySQL = "SELECT id, nom FROM clients";   
        var data = new Array();

        var execQuery = connection.query(querySQL, function(err, rows, fields){

            if(!err){
                for(var i=0; i<25; i++){
                    data.push({"nom":rows[i].nom});         
                }
                res.contentType('application/json');
                res.json(data); 
            }else{  
                console.log("[SQL005] - Une erreur est survenue");
            }

        });

});

Does MS Access support "CASE WHEN" clause if connect with ODBC?

I have had to use a multiple IIF statement to create a similar result in ACCESS SQL.

IIf([refi type] Like "FHA ST*","F",IIf([refi type]="VA IRRL","V"))

All remaining will stay Null.

How to list the contents of a package using YUM?

I don't think you can list the contents of a package using yum, but if you have the .rpm file on your local system (as will most likely be the case for all installed packages), you can use the rpm command to list the contents of that package like so:

rpm -qlp /path/to/fileToList.rpm

If you don't have the package file (.rpm), but you have the package installed, try this:

rpm -ql packageName

When do I need to use AtomicBoolean in Java?

When multiple threads need to check and change the boolean. For example:

if (!initialized) {
   initialize();
   initialized = true;
}

This is not thread-safe. You can fix it by using AtomicBoolean:

if (atomicInitialized.compareAndSet(false, true)) {
    initialize();
}

Delete statement in SQL is very slow

  1. Disable CONSTRAINT

    ALTER TABLE [TableName] NOCHECK CONSTRAINT ALL;

  2. Disable Index

    ALTER INDEX ALL ON [TableName] DISABLE;

  3. Rebuild Index

    ALTER INDEX ALL ON [TableName] REBUILD;

  4. Enable CONSTRAINT

    ALTER TABLE [TableName] CHECK CONSTRAINT ALL;

  5. Delete again

Correct way to integrate jQuery plugins in AngularJS

i have alreay 2 situations where directives and services/factories didnt play well.

the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).

in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.

i even tried to make a directive with a controller and an isolated-scope

only when i moved everything to a controller and it worked like magic.

example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS

How to execute 16-bit installer on 64-bit Win7?

Bottom line at the top: Get newer programs or get an older computer.

The solution is simple. It sucks but it's simple. For old programs keep an old computer up and running. Some times you just can't find the same game experience in the new games as the old ones. Sometimes there are programs that have no new counterparts that do the same thing. You basically have 2 choices at that point. On the bright side. Old computers can run $20 -$100 and that can buy you the whole system; monitor, tower, keyboard, mouse and speakers. If you have the patience to run old programs you should have the patience to find what you are looking for in want ads. I have 4 old computers running; 2 windows 98, 2 windows xp. The my wife and I each have win7 computers.

Sort a Custom Class List<T>

One way to do this is with a delegate

List<cTag> week = new List<cTag>();
// add some stuff to the list
// now sort
week.Sort(delegate(cTag c1, cTag c2) { return c1.date.CompareTo(c2.date); });

Displaying splash screen for longer than default seconds

This works...

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Load Splash View Controller first
    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"Splash"];
    self.window.rootViewController = viewController;
    [self.window makeKeyAndVisible];

    // Load other stuff that requires time

    // Now load the main View Controller that you want
}

How to resize an image to fit in the browser window?

Here is a simple CSS only solution (JSFiddle), works everywhere, mobile and IE included:

CSS 2.0:

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

img {
    padding: 0;
    display: block;
    margin: 0 auto;
    max-height: 100%;
    max-width: 100%;
}

HTML:

<body>
  <img src="images/your-image.png" />
</body>

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

Based on DaveRandom's answer, I was also playing around and found a slightly simpler Apache solution that produces the same result (Access-Control-Allow-Origin is set to the current specific protocol + domain + port dynamically) without using any rewrite rules:

SetEnvIf Origin ^(https?://.+\.mywebsite\.com(?::\d{1,5})?)$   CORS_ALLOW_ORIGIN=$1
Header append Access-Control-Allow-Origin  %{CORS_ALLOW_ORIGIN}e   env=CORS_ALLOW_ORIGIN
Header merge  Vary "Origin"

And that's it.

Those who want to enable CORS on the parent domain (e.g. mywebsite.com) in addition to all its subdomains can simply replace the regular expression in the first line with this one:

^(https?://(?:.+\.)?mywebsite\.com(?::\d{1,5})?)$.

Note: For spec compliance and correct caching behavior, ALWAYS add the Vary: Origin response header for CORS-enabled resources, even for non-CORS requests and those from a disallowed origin (see example why).

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

You can use the .tostring() method with datetime format specifiers to format to whatever you need:

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

(Get-Date).AddDays(-1).ToString('MM-dd-yyyy')
11-01-2013

Comparing chars in Java

You can just write your chars as Strings and use the equals method.

For Example:

String firstChar = "A";
String secondChar = "B";
String thirdChar = "C";

if (firstChar.equalsIgnoreCase(secondChar) ||
        (firstChar.equalsIgnoreCase(thirdChar))) // As many equals as you want
{
    System.out.println(firstChar + " is the same as " + secondChar);
} else {
    System.out.println(firstChar + " is different than " + secondChar);
}

Use jQuery to change a second select list based on the first select list option

On the selected answer I see that when initially the page is loaded the selection of first option is prior fixed and therefore gives the option of all the categories in selection 2. You can avoid that by adding the first option as the following in both the select tag:- <option value="none" selected disabled hidden>Select an Option</option>

<select name="select1" id="select1">
<option value="none" selected disabled hidden>Select an Option</option>
<option value="1">Fruit</option>
  <option value="2">Animal</option>
  <option value="3">Bird</option>
  <option value="4">Car</option>
</select>


<select name="select2" id="select2">
<option value="none" selected disabled hidden>Select an Option</option>
  <option value="1">Banana</option>
  <option value="1">Apple</option>
  <option value="1">Orange</option>
  <option value="2">Wolf</option>
  <option value="2">Fox</option>
  <option value="2">Bear</option>
  <option value="3">Eagle</option>
  <option value="3">Hawk</option>
  <option value="4">BWM<option>
</select>

Is there a way to get rid of accents and convert a whole string to regular letters?

I suggest Junidecode . It will handle not only 'L' and 'Ø', but it also works well for transcribing from other alphabets, such as Chinese, into Latin alphabet.

How can I get key's value from dictionary in Swift?

From Apple Docs

You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:

https://developer.apple.com/documentation/swift/dictionary

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."

How to Update Date and Time of Raspberry Pi With out Internet

Remember that Raspberry Pi does not have real time clock. So even you are connected to internet have to set the time every time you power on or restart.

This is how it works:

  1. Type sudo raspi-config in the Raspberry Pi command line
  2. Internationalization options
  3. Change Time Zone
  4. Select geographical area
  5. Select city or region
  6. Reboot your pi

Next thing you can set time using this command

sudo date -s "Mon Aug  12 20:14:11 UTC 2014"

More about data and time

man date

When Pi is connected to computer should have to manually set data and time

jQuery: Uncheck other checkbox on one checked

I think the prop method is more convenient when it comes to boolean attribute. http://api.jquery.com/prop/

a page can have only one server-side form tag

please remove " runat="server" " from "form" tag then it will definetly works.

Static class initializer in PHP

NOTE: This is exactly what OP said they did. (But didn't show code for.) I show the details here, so that you can compare it to the accepted answer. My point is that OP's original instinct was, IMHO, better than the answer he accepted.


Given how highly upvoted the accepted answer is, I'd like to point out the "naive" answer to one-time initialization of static methods, is hardly more code than that implementation of Singleton -- and has an essential advantage.

final class MyClass  {
    public static function someMethod1() {
        MyClass::init();
        // whatever
    }

    public static function someMethod2() {
        MyClass::init();
        // whatever
    }


    private static $didInit = false;

    private static function init() {
        if (!self::$didInit) {
            self::$didInit = true;
            // one-time init code.
        }
    }

    // private, so can't create an instance.
    private function __construct() {
        // Nothing to do - there are no instances.
    }
}

The advantage of this approach, is that you get to call with the straightforward static function syntax:

MyClass::someMethod1();

Contrast it to the calls required by the accepted answer:

MyClass::getInstance->someMethod1();

As a general principle, it is best to pay the coding price once, when you code a class, to keep callers simpler.


If you are NOT using PHP 7.4's opcode.cache, then use Victor Nicollet's answer. Simple. No extra coding required. No "advanced" coding to understand. (I recommend including FrancescoMM's comment, to make sure "init" will never execute twice.) See Szczepan's explanation of why Victor's technique won't work with opcode.cache.

If you ARE using opcode.cache, then AFAIK my answer is as clean as you can get. The cost is simply adding the line MyClass::init(); at start of every public method. NOTE: If you want public properties, code them as a get / set pair of methods, so that you have a place to add that init call.

(Private members do NOT need that init call, as they are not reachable from the outside - so some public method has already been called, by the time execution reaches the private member.)

Enter key pressed event handler

Either KeyDown or KeyUp.

TextBox tb = new TextBox();
tb.KeyDown += new KeyEventHandler(tb_KeyDown);

static void tb_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        //enter key is down
    }
}

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.


Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"

or

start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.

Examples:

Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

Source: http://ss64.com/nt/cmd.html

Installing Git on Eclipse

egit was included in Indigo (2011) and should be there in all future Eclipse versions after that.

Just go to ![(Help->Install New Software)]

Then Work with: --All Available Sites--

Then type egit underneath and wait (may take a while) ! Then click the checkbox and install.

How to activate a specific worksheet in Excel?

I would recommend you to use worksheet's index instead of using worksheet's name, in this way you can also loop through sheets "dynamically"

for i=1 to thisworkbook.sheets.count
 sheets(i).activate
'You can add more code 
with activesheet
 'Code...
end with
next i

It will also, improve performance.

How to generate a random int in C?

On modern x86_64 CPUs you can use the hardware random number generator via _rdrand64_step()

Example code:

#include <immintrin.h>

uint64_t randVal;
if(!_rdrand64_step(&randVal)) {
  // Report an error here: random number generation has failed!
}
// If no error occured, randVal contains a random 64-bit number

What are the differences between if, else, and else if?

Those are the basic decision orders that you have in most of the programming language; it helps you to decide the flow of actions that your program is gonna do. The if is telling the compiler that you have a question, and the question is the condition between parenthesis

if (condition) {
    thingsToDo()..
}

the else part is an addition to this structure to tell the compiler what to do if the condition is false

if (condition) {
    thingsToDo()..
} else {
    thingsToDoInOtherCase()..
}

you can combine those to form a else if which is when the first condition is false but you want to do another question before to decide what to do.

if (condition) {
    thingsToDo()..
} else if (condition2) {
    thingsToDoInTheSecondCase()..
}else {
    thingsToDoInOtherCase()..
}

How to execute a shell script from C in Linux?

If you're ok with POSIX, you can also use popen()/pclose()

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

int main(void) {
/* ls -al | grep '^d' */
  FILE *pp;
  pp = popen("ls -al", "r");
  if (pp != NULL) {
    while (1) {
      char *line;
      char buf[1000];
      line = fgets(buf, sizeof buf, pp);
      if (line == NULL) break;
      if (line[0] == 'd') printf("%s", line); /* line includes '\n' */
    }
    pclose(pp);
  }
  return 0;
}

How Long Does it Take to Learn Java for a Complete Newbie?

The best advice for learning to program is basically: write a lot of programs.

Project Euler contains lots of problems well suited for this purpose, as the resulting programs are manageable in size while actually allowing you to solve an explicit problem.

http://projecteuler.net/index.php

What is the advantage of using heredoc in PHP?

Heredoc's are a great alternative to quoted strings because of increased readability and maintainability. You don't have to escape quotes and (good) IDEs or text editors will use the proper syntax highlighting.

A very common example: echoing out HTML from within PHP:

$html = <<<HTML
  <div class='something'>
    <ul class='mylist'>
      <li>$something</li>
      <li>$whatever</li>
      <li>$testing123</li>
    </ul>
  </div>
HTML;

// Sometime later
echo $html;

It is easy to read and easy to maintain.

The alternative is echoing quoted strings, which end up containing escaped quotes and IDEs aren't going to highlight the syntax for that language, which leads to poor readability and more difficulty in maintenance.

Updated answer for Your Common Sense

Of course you wouldn't want to see an SQL query highlighted as HTML. To use other languages, simply change the language in the syntax:

$sql = <<<SQL
       SELECT * FROM table
SQL;

SQL time difference between two dates result in hh:mm:ss

Take a look at these. I didn't use more parenthesis to keep it readable, so remember that multiplication is done before addition or subtraction.

Both below return:

hr  mins  sec   timediff
73   12    30   73:12:30

This is written to not use a sub-query and be the most readable and understandable:

declare @StartDate datetime,
@EndDate datetime

set @StartDate = '10/01/2012 08:40:18.000'
set @EndDate =   '10/04/2012 09:52:48.000' 

select datediff(hour, @StartDate, @EndDate) hr,
   datediff(minute, @StartDate, @EndDate) 
   - datediff(hour, @StartDate, @EndDate) * 60 mins,
   datediff(second, @StartDate, @EndDate) 
   - (datediff(minute, @StartDate, @EndDate) * 60) sec,
   cast(datediff(hour, @StartDate, @EndDate) as varchar)+':'+ 
   cast(datediff(minute, @StartDate, @EndDate) 
   - datediff(hour, @StartDate, @EndDate) * 60 as varchar)+':'+ 
   cast(datediff(second, @StartDate, @EndDate) 
   - (datediff(minute, @StartDate, @EndDate) * 60) as varchar) timediff

This is a version that would perform better if you have a lot of data. It requires a sub-query.

declare @StartDate datetime,
@EndDate datetime

set @StartDate = '10/01/2012 08:40:18.000'
set @EndDate =   '10/04/2012 09:52:48.000' 

select s.seconds / 3600  hrs,
s.seconds / 60 - (seconds / 3600 ) * 60 mins,
s.seconds - (s.seconds / 60) * 60   seconds,
cast(s.seconds / 3600 as varchar) + ':' +
cast((s.seconds / 60 - (seconds / 3600 ) * 60) as varchar) + ':' +
cast((s.seconds - (s.seconds / 60) * 60) as varchar) timediff
from (select datediff(second, @StartDate, @EndDate) as seconds) s

Define an <img>'s src attribute in CSS

#divID {
    background-image: url("http://imageurlhere.com");
    background-repeat: no-repeat;
    width: auto; /*or your image's width*/
    height: auto; /*or your image's height*/
    margin: 0;
    padding: 0;
}

Display loading image while post with ajax

This is very simple and easily manage.

jQuery(document).ready(function(){
jQuery("#search").click(function(){
    jQuery("#loader").show("slow");
    jQuery("#response_result").hide("slow");
    jQuery.post(siteurl+"/ajax.php?q="passyourdata, function(response){
        setTimeout("finishAjax('response_result', '"+escape(response)+"')", 850);
            });
});

})
function finishAjax(id,response){ 
      jQuery("#loader").hide("slow");   
      jQuery('#response_result').html(unescape(response));
      jQuery("#"+id).show("slow");      
      return true;
}

How do I compile a Visual Studio project from the command-line?

DEVENV works well in many cases, but on a WIXPROJ to build my WIX installer, all I got is "CATASTROPHIC" error in the Out log.

This works: MSBUILD /Path/PROJECT.WIXPROJ /t:Build /p:Configuration=Release

Extract a single (unsigned) integer from a string

An alternative solution with sscanf:

$str = "In My Cart : 11 items";
list($count) = sscanf($str, 'In My Cart : %s items');

How do I detect if I am in release or debug mode?

Yes, you will have no problems using:

if (BuildConfig.DEBUG) {
   //It's not a release version.
}

Unless you are importing the wrong BuildConfig class. Make sure you are referencing your project's BuildConfig class, not from any of your dependency libraries.

enter image description here

How to install pip in CentOS 7?

yum install python34-pip

pip3.4 install foo

You will likely need the EPEL repositories installed:

yum install -y epel-release

How to install sklearn?

You didn't provide us which operating system are you on? If it is a Linux, make sure you have scipy installed as well, after that just do

pip install -U scikit-learn

If you are on windows you might want to check out these pages.

Using UPDATE in stored procedure with optional parameters

One Idea:

UPDATE tbl_ClientNotes
SET ordering=ISNULL(@ordering, ordering), 
    title=ISNULL(@title, title),  
    content=ISNULL(@content, content)
WHERE id=@id

Leap year calculation

The length of a year is (more or less) 365.242196 days. So we have to subtract, more or less, a quarter of a day to make it fit :

365.242196 - 0.25 = 364.992196 (by adding 1 day in 4 years) : but oops, now it's too small!! lets add a hundreth of a day (by not adding that day once in a hundred year :-))

364.992196 + 0,01 = 365.002196 (oops, a bit too big, let's add that day anyway one time in about 400 years)

365.002196 - 1/400 = 364.999696

Almost there now, just play with leapseconds now and then, and you're set.

(Note : the reason no more corrections are applied after this step is because a year also CHANGES IN LENGTH!!, that's why leapseconds are the most flexible solution, see for examlple here)

That's why i guess

Why are only a few video games written in Java?

Misconceptions about performance and poor JVM optimizations would be my guess. I say misconceptions about performance because there are some Java ports of C++ games that perform faster than their C++ counterparts (see Jake 2). The real problem, IMHO, is that many Java programmers aren't focused so much on bleeding edge performance as they are with ease of use and understandability/maintainability of code. On the C/C++ side of things you're essentially coding in a slightly higher level assembly language and its about as close to the hardware as you can get without writing in assembly or straight machine code.

MS SQL 2008 - get all table names and their row counts in a DB

Try this it's simple and fast

SELECT T.name AS [TABLE NAME], I.rows AS [ROWCOUNT] 
FROM   sys.tables AS T 
   INNER JOIN sys.sysindexes AS I ON T.object_id = I.id 
   AND I.indid < 2 ORDER  BY I.rows DESC

View RDD contents in Python Spark?

Try this:

data = f.flatMap(lambda x: x.split(' '))
map = data.map(lambda x: (x, 1))
mapreduce = map.reduceByKey(lambda x,y: x+y)
result = mapreduce.collect()

Please note that when you run collect(), the RDD - which is a distributed data set is aggregated at the driver node and is essentially converted to a list. So obviously, it won't be a good idea to collect() a 2T data set. If all you need is a couple of samples from your RDD, use take(10).

Setting the MySQL root user password on OS X

I solved this by:

  1. Shutting down my MySQL server: mysql.server stop
  2. Running MySQL in safe mode: mysqld_safe --skip-grant-tables
  3. In another terminal, login with mysql -u root
  4. In the same terminal, run UPDATE mysql.user SET authentication_string=null WHERE User='root';, then FLUSH PRIVILEGES; and then exit with exit;
  5. Stop the safe mode server with mysql.server stop and then start the normal one; mysql.server start

Now you can set your new password with

ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'yourpasswd';

Interface type check with Typescript

export interface ConfSteps {
    group: string;
    key: string;
    steps: string[];
}
private verify(): void {
    const obj = `{
      "group": "group",
      "key": "key",
      "steps": [],
      "stepsPlus": []
    } `;
    if (this.implementsObject<ConfSteps>(obj, ['group', 'key', 'steps'])) {
      console.log(`Implements ConfSteps: ${obj}`);
    }
  }
private objProperties: Array<string> = [];

private implementsObject<T>(obj: any, keys: (keyof T)[]): boolean {
    JSON.parse(JSON.stringify(obj), (key, value) => {
      this.objProperties.push(key);
    });
    for (const key of keys) {
      if (!this.objProperties.includes(key.toString())) {
        return false;
      }
    }
    this.objProperties = null;
    return true;
  }

Mapping composite keys using EF code first

Through Configuration, you can do this:

Model1
{
    int fk_one,
    int fk_two
}

Model2
{
    int pk_one,
    int pk_two,
}

then in the context config

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Model1>()
            .HasRequired(e => e.Model2)
            .WithMany(e => e.Model1s)
            .HasForeignKey(e => new { e.fk_one, e.fk_two })
            .WillCascadeOnDelete(false);
    }
}

What is a provisioning profile used for when developing iPhone applications?

You need it to install development iPhone applications on development devices.

Here's how to create one, and the reference for this answer:
http://www.wikihow.com/Create-a-Provisioning-Profile-for-iPhone

Another link: http://iphone.timefold.com/provisioning.html

How to "inverse match" with regex?

In perl you can do

process($line) if ($line =~ !/Andrea/);

How to create and use resources in .NET

The above method works good.

Another method (I am assuming web here) is to create your page. Add controls to the page. Then while in design mode go to: Tools > Generate Local Resource. A resource file will automatically appear in the solution with all the controls in the page mapped in the resource file.

To create resources for other languages, append the 4 character language to the end of the file name, before the extension (Account.aspx.en-US.resx, Account.aspx.es-ES.resx...etc).

To retrieve specific entries in the code-behind, simply call this method: GetLocalResourceObject([resource entry key/name]).

How to add a "open git-bash here..." context menu to the windows explorer?

Add the gitpath to the Environment-path variable (e.g. C:\Program Files\Git\cmd) by which you can access git from any folder using command line.

Hot deploy on JBoss - how do I make JBoss "see" the change?

I am using JBoss AS 7.1.1.Final. Adding following code snippet in my web.xml helped me to change jsp files on the fly :

<servlet>
    <servlet-name>jsp</servlet-name>
    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <init-param>
        <param-name>development</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
</servlet>

Hope this helps.!!

How do I deal with installing peer dependencies in Angular CLI?

I found that running the npm install command in the same directory where your Angular project is, eliminates these warnings. I do not know the reason why.

Specifically, I was trying to use ng2-completer

$ npm install ng2-completer --save
npm WARN saveError ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm WARN [email protected] requires a peer of @angular/common@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@>= 6.0.0 but noneis installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/forms@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN foo No description
npm WARN foo No repository field.
npm WARN foo No README data
npm WARN foo No license field.

I was unable to compile. When I tried again, this time in my Angular project directory which was in foo/foo_app, it worked fine.

cd foo/foo_app
$ npm install ng2-completer --save

Could not connect to React Native development server on Android

None of the above solutions worked for me.

I just opened Dev menu by clicking Ctrl+M and then clicked on change bundle location and added my machine IP followed by port.

Use Expect in a Bash script to provide a password to an SSH command

Also make sure to use

send -- "$PWD\r"

instead, as passwords starting with a dash (-) will fail otherwise.

The above won't interpret a string starting with a dash as an option to the send command.

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Google Apps KitKat for Genymotion.

Download the Google Apps ZIP file from the link which contain the essential Google Apps such as Play Store, Gmail, YouTube, etc.

https://www.mediafire.com/?qbbt4lhyu9q10ix

After finishing booting, drag and drop the ZIP file we downloaded named update-gapps-4-4-2-signed.zip to the Genymotion Window. It starts installing the Google Apps, and it asks for your confirmation. Confirm it.

Changing Node.js listening port

There is no config file unless you create one yourself. However, the port is a parameter of the listen() function. For example, to listen on port 8124:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

If you're having problems finding a port that's open, you can go to the command line and type:

netstat -ano

To see a list of all ports in use per adapter.

MVC pattern on Android

When we apply MVC, MVVM, or Presentation Model to an Android app, what we really want is to have a clear structured project and more importantly easier for unit tests.

At the moment, without a third-party framework, you usually have lots of code (like addXXListener(), findViewById(), etc.), which does not add any business value.

What's more, you have to run Android unit tests instead of normal JUnit tests, which take ages to run and make unit tests somewhat impractical. For these reasons, some years ago we started an open source project, RoboBinding - A data-binding Presentation Model framework for the Android platform.

RoboBinding helps you write UI code that is easier to read, test and maintain. RoboBinding removes the need of unnecessary code like addXXListener or so, and shifts UI logic to Presentation Model, which is a POJO and can be tested via normal JUnit tests. RoboBinding itself comes with more than 300 JUnit tests to ensure its quality.

Getting a better understanding of callback functions in JavaScript

Here is a basic example that explains the callback() function in JavaScript:

_x000D_
_x000D_
var x = 0;_x000D_
_x000D_
function testCallBack(param1, param2, callback) {_x000D_
  alert('param1= ' + param1 + ', param2= ' + param2 + ' X=' + x);_x000D_
  if (callback && typeof(callback) === "function") {_x000D_
    x += 1;_x000D_
    alert("Calla Back x= " + x);_x000D_
    x += 1;_x000D_
    callback();_x000D_
  }_x000D_
}_x000D_
_x000D_
testCallBack('ham', 'cheese', function() {_x000D_
  alert("Function X= " + x);_x000D_
});
_x000D_
_x000D_
_x000D_

JSFiddle

How to run console application from Windows Service?

Starting from Windows Vista, a service cannot interact with the desktop. You will not be able to see any windows or console windows that are started from a service. See this MSDN forum thread.

On other OS, there is an option that is available in the service option called "Allow Service to interact with desktop". Technically, you should program for the future and should follow the Vista guideline even if you don't use it on Vista.

If you still want to run an application that never interact with the desktop, try specifying the process to not use the shell.

ProcessStartInfo info = new ProcessStartInfo(@"c:\myprogram.exe");
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.CreateNoWindow = true;
info.ErrorDialog = false;
info.WindowStyle = ProcessWindowStyle.Hidden;

Process process = Process.Start(info);

See if this does the trick.

First you inform Windows that the program won't use the shell (which is inaccessible in Vista to service).

Secondly, you redirect all consoles interaction to internal stream (see process.StandardInput and process.StandardOutput.

How to change context root of a dynamic web project in Eclipse?

If using maven java ee 7/8 enterprise application, need to edit the pom.xml of the EAR project

<build>
    <plugins>
        ...
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-ear-plugin</artifactId>
            <version>2.8</version>
            <configuration>
                <version>6</version>
                <defaultLibBundleDir>lib</defaultLibBundleDir>
                <modules>
                    <webModule>
                        <groupId>com.sample</groupId>
                        <artifactId>ProjectName-web</artifactId>
                        <contextRoot>/myproject</contextRoot>
                    </webModule>
                </modules>
            </configuration>
        </plugin>
        ...
    </plugins>
</build>

I can't install python-ldap

On OSX, you need the xcode CLI tools. Just open a terminal and run:

xcode-select --install

javascript multiple OR conditions in IF statement

When it checks id!=2 it returns true and stops further checking

Create instance of generic type whose constructor requires a parameter?

It is still possible, with high performance, by doing the following:

    //
    public List<R> GetAllItems<R>() where R : IBaseRO, new() {
        var list = new List<R>();
        using ( var wl = new ReaderLock<T>( this ) ) {
            foreach ( var bo in this.items ) {
                T t = bo.Value.Data as T;
                R r = new R();
                r.Initialize( t );
                list.Add( r );
            }
        }
        return list;
    }

and

    //
///<summary>Base class for read-only objects</summary>
public partial interface IBaseRO  {
    void Initialize( IDTO dto );
    void Initialize( object value );
}

The relevant classes then have to derive from this interface and initialize accordingly. Please note, that in my case, this code is part of a surrounding class, which already has <T> as generic parameter. R, in my case, also is a read-only class. IMO, the public availability of Initialize() functions has no negative effect on the immutability. The user of this class could put another object in, but this would not modify the underlying collection.

How to include a sub-view in Blade templates?

When you use laravel modules, you may add the name's module:

@include('cimple::shared.posts_list')

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

How to download videos from youtube on java?

Regarding the format (mp4 or flv) decide which URL you want to use. Then use this tutorial to download the video and save it into a local directory.

Random date in C#

private Random gen = new Random();
DateTime RandomDay()
{
    DateTime start = new DateTime(1995, 1, 1);
    int range = (DateTime.Today - start).Days;           
    return start.AddDays(gen.Next(range));
}

For better performance if this will be called repeatedly, create the start and gen (and maybe even range) variables outside of the function.

How to run a PowerShell script from a batch file

If you want to run from the current directory without a fully qualified path, you can use:

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& './ps.ps1'"

Iterating through all the cells in Excel VBA or VSTO 2005

You can use a For Each to iterate through all the cells in a defined range.

Public Sub IterateThroughRange()

Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim cell As Range

Set wb = Application.Workbooks(1)
Set ws = wb.Sheets(1)
Set rng = ws.Range("A1", "C3")

For Each cell In rng.Cells
    cell.Value = cell.Address
Next cell

End Sub

How to retrieve data from sqlite database in android and display it in TextView

You are using getData() method as void.

You can not return values from void.

What is your most productive shortcut with Vim?

I just discovered Vim's omnicompletion the other day, and while I'll admit I'm a bit hazy on what does which, I've had surprisingly good results just mashing either Ctrl + x Ctrl + u or Ctrl + n/Ctrl +p in insert mode. It's not quite IntelliSense, but I'm still learning it.

Try it out! :help ins-completion

C++ printing boolean, what is displayed?

The standard streams have a boolalpha flag that determines what gets displayed -- when it's false, they'll display as 0 and 1. When it's true, they'll display as false and true.

There's also an std::boolalpha manipulator to set the flag, so this:

#include <iostream>
#include <iomanip>

int main() {
    std::cout<<false<<"\n";
    std::cout << std::boolalpha;   
    std::cout<<false<<"\n";
    return 0;
}

...produces output like:

0
false

For what it's worth, the actual word produced when boolalpha is set to true is localized--that is, <locale> has a num_put category that handles numeric conversions, so if you imbue a stream with the right locale, it can/will print out true and false as they're represented in that locale. For example,

#include <iostream>
#include <iomanip>
#include <locale>

int main() {
    std::cout.imbue(std::locale("fr"));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

...and at least in theory (assuming your compiler/standard library accept "fr" as an identifier for "French") it might print out faux instead of false. I should add, however, that real support for this is uneven at best--even the Dinkumware/Microsoft library (usually quite good in this respect) prints false for every language I've checked.

The names that get used are defined in a numpunct facet though, so if you really want them to print out correctly for particular language, you can create a numpunct facet to do that. For example, one that (I believe) is at least reasonably accurate for French would look like this:

#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>

class my_fr : public std::numpunct< char > {
protected:
    char do_decimal_point() const { return ','; }
    char do_thousands_sep() const { return '.'; }
    std::string do_grouping() const { return "\3"; }
    std::string do_truename() const { return "vrai";  }
    std::string do_falsename() const { return "faux"; }
};

int main() {
    std::cout.imbue(std::locale(std::locale(), new my_fr));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

And the result is (as you'd probably expect):

0
faux

An efficient way to Base64 encode a byte array?

Based on your edit and comments.. would this be what you're after?

byte[] newByteArray = UTF8Encoding.UTF8.GetBytes(Convert.ToBase64String(currentByteArray));

TypeError: Missing 1 required positional argument: 'self'

You need to instantiate a class instance here.

Use

p = Pump()
p.getPumps()

Small example -

>>> class TestClass:
        def __init__(self):
            print("in init")
        def testFunc(self):
            print("in Test Func")


>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func

How to change the text of a label?

I just went through this myself and found the solution. See an ASP.NET label server control actually gets redered as a span (not an input), so using the .val() property to get/set will not work. Instead you must use the 'text' property on the span in conjuntion with using the controls .ClientID property. The following code will work:

$("#<%=lblVessel.ClientID %>").text('NewText');

How to get first and last day of week in Oracle?

You could try this approach:

  1. Get the current date.

  2. Add the the number of years which is equal to the difference between the current date's year and the specified year.

  3. Subtract the number of days that is the last obtained date's week day's number (and it will give us the last day of some week).

  4. Add the number of weeks which is the difference between the last obtained date's week number and the specified week number, and that will yield the last day of the desired week.

  5. Subtract 6 days to obtain the first day.

Find TODO tags in Eclipse

  1. Push Ctrl+H
  2. Got to File Search tab
  3. Enter "// TODO Auto-generated method stub" in Containing Text field
  4. Enter "*.java" in Filename patterns field
  5. Select proper scope

Java SSLHandshakeException "no cipher suites in common"

It looks like you are trying to connect using TLSv1.2, which isn't widely implemented on servers. Does your destination support tls1.2?

Extract time from moment js object

This is the good way using formats:

const now = moment()
now.format("hh:mm:ss K") // 1:00:00 PM
now.format("HH:mm:ss") // 13:00:00

Red more about moment sring format

How to launch a Google Chrome Tab with specific URL using C#

UPDATE: Please see Dylan's or d.c's anwer for a little easier (and more stable) solution, which does not rely on Chrome beeing installed in LocalAppData!


Even if I agree with Daniel Hilgarth to open a new tab in chrome you just need to execute chrome.exe with your URL as the argument:

Process.Start(@"%AppData%\..\Local\Google\Chrome\Application\chrome.exe", 
              "http:\\www.YourUrl.com");

Propagate all arguments in a bash shell script

I realize this has been well answered but here's a comparison between "$@" $@ "$*" and $*

Contents of test script:

# cat ./test.sh
#!/usr/bin/env bash
echo "================================="

echo "Quoted DOLLAR-AT"
for ARG in "$@"; do
    echo $ARG
done

echo "================================="

echo "NOT Quoted DOLLAR-AT"
for ARG in $@; do
    echo $ARG
done

echo "================================="

echo "Quoted DOLLAR-STAR"
for ARG in "$*"; do
    echo $ARG
done

echo "================================="

echo "NOT Quoted DOLLAR-STAR"
for ARG in $*; do
    echo $ARG
done

echo "================================="

Now, run the test script with various arguments:

# ./test.sh  "arg with space one" "arg2" arg3
=================================
Quoted DOLLAR-AT
arg with space one
arg2
arg3
=================================
NOT Quoted DOLLAR-AT
arg
with
space
one
arg2
arg3
=================================
Quoted DOLLAR-STAR
arg with space one arg2 arg3
=================================
NOT Quoted DOLLAR-STAR
arg
with
space
one
arg2
arg3
=================================

Programmatically go back to the previous fragment in the backstack

Add those line to your onBackPressed() Method. popBackStackImmediate() method will get you back to the previous fragment if you have any fragment on back stack `

if(getFragmentManager().getBackStackEntryCount() > 0){
     getFragmentManager().popBackStackImmediate();
}
else{
    super.onBackPressed();
}

`

"Multiple definition", "first defined here" errors

I am adding this A because I got caught with a bizarre version of this which really had me scratching my head for about a hour until I spotted the root cause. My load was failing because of multiple repeats of this format

<path>/linit.o:(.rodata1.libs+0x50): multiple definition of `lua_lib_BASE'
<path>/linit.o:(.rodata1.libs+0x50): first defined here

I turned out to be a bug in my Makefile magic where I had a list of C files and using vpath etc., so the compiles would pick them up from the correct directory in hierarchy. However one C file was repeated in the list, at the end of one line and the start of the next so the gcc load generated by the make had the .o file twice on the command line. Durrrrh. The multiple definitions were from multiple occurances of the same file. The linker ignored duplicates apart from static initialisers!

Change marker size in Google maps V3

This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.

The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(42, 68)
);  

As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.

Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:

what happens when you leave anchor null on an enlarged shadow

The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null. In other words, leaving the anchor null ensures the tip points where it is supposed to point.

However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.

By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.

var pinShadow = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
    null,
    null,
    /* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
    new google.maps.Point(40, 110), 
    new google.maps.Size(120, 110)); 

to give this:

offset the enlarged shadow anchor explicitly

Convert Java Object to JsonNode in Jackson

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);

or

JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

Insert current date into a date column using T-SQL?

If you're looking to store the information in a table, you need to use an INSERT or an UPDATE statement. It sounds like you need an UPDATE statement:

UPDATE  SomeTable
SET     SomeDateField = GETDATE()
WHERE   SomeID = @SomeID

How to start Activity in adapter?

Just pass in the current Context to the Adapter constructor and store it as a field. Then inside the onClick you can use that context to call startActivity().

pseudo-code

public class MyAdapter extends Adapter {
     private Context context;

     public MyAdapter(Context context) {
          this.context = context;     
     }

     public View getView(...){
         View v;
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                 context.startActivity(...);
             }
         });
     }
}

How to fix Subversion lock error

I solved this problem by doing these:

  1. Right click on your project.

  2. Click on Team

  3. Click Refresh/Cleaup

ArrayList insertion and retrieval order

Yes, it will always be the same. From the documentation

Appends the specified element to the end of this list. Parameters: e element to be appended to this list Returns: true (as specified by Collection.add(java.lang.Object))

ArrayList add() implementation

public boolean More ...add(E e) {
    ensureCapacity(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

How to count frequency of characters in a string?

This is more Effective way to count frequency of characters in a string

public class demo {
    public static void main(String[] args) {
        String s = "babdcwertyuiuygf";
        Map<Character, Integer> map = new TreeMap<>();
        s.chars().forEach(e->map.put((char)e, map.getOrDefault((char)e, 0) + 1));
        StringBuffer myValue = new StringBuffer();
        String myMapKeyValue = "";
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            myMapKeyValue = Character.toString(entry.getKey()).concat(
                Integer.toString(entry.getValue()));
            myValue.append(myMapKeyValue);
        }
        System.out.println(myValue);
    }
}

Java Does Not Equal (!=) Not Working?

Please use !statusCheck.equals("success") instead of !=.

Here are more details.

Show MySQL host via SQL Command

show variables where Variable_name='hostname'; 

That could help you !!

How to write log base(2) in c/c++

If you're looking for an integral result, you can just determine the highest bit set in the value and return its position.

How do I prevent DIV tag starting a new line?

div is a block element, which always takes up its own line.

use the span tag instead

Custom style to jquery ui dialogs

See http://jsfiddle.net/qP8DY/24/

You can add a class (such as "success-dialog" in my example) to div#success, either directly in your HTML, or in your JavaScript by adding to the dialogClass option, as I've done.

$('#success').dialog({
    height: 50,
    width: 350,
    modal: true,
    resizable: true,
    dialogClass: 'no-close success-dialog'
});

Then just add the success-dialog class to your CSS rules as appropriate. To indicate an element with two (or more) classes applied to it, just write them all together, with no spaces in between. For example:

.ui-dialog.success-dialog {
    font-family: Verdana,Arial,sans-serif;
    font-size: .8em;
}

Twitter API - Display all tweets with a certain hashtag?

The answer here worked better for me as it isolates the search on the hashtag, not just returning results that contain the search string. In the answer above you would still need to parse the JSON response to see if the entities.hashtags array is not empty.

Position Absolute + Scrolling

I ran into this situation and creating an extra div was impractical. I ended up just setting the full-height div to height: 10000%; overflow: hidden;

Clearly not the cleanest solution, but it works really fast.

Adding default parameter value with type hint in Python

Your second way is correct.

def foo(opts: dict = {}):
    pass

print(foo.__annotations__)

this outputs

{'opts': <class 'dict'>}

It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.

I strongly advise against using mutable keyword arguments. More information here.

Bootstrap change div order with pull-right, pull-left on 3 columns

Try this...

<div class="row">
    <div class="col-xs-3">
        Menu
    </div>
    <div class="col-xs-9">
        <div class="row">
          <div class="col-sm-4 col-sm-push-8">
          Right content
          </div>
          <div class="col-sm-8 col-sm-pull-4">
          Content
          </div>
       </div>
    </div>
</div>

Bootply

Understanding the Linux oom-killer's logs

Sum of total_vm is 847170 and sum of rss is 214726, these two values are counted in 4kB pages, which means when oom-killer was running, you had used 214726*4kB=858904kB physical memory and swap space.

Since your physical memory is 1GB and ~200MB was used for memory mapping, it's reasonable for invoking oom-killer when 858904kB was used.

rss for process 2603 is 181503, which means 181503*4KB=726012 rss, was equal to sum of anon-rss and file-rss.

[11686.043647] Killed process 2603 (flasherav) total-vm:1498536kB, anon-rss:721784kB, file-rss:4228kB

how to compare two string dates in javascript?

You can simply compare 2 strings

function isLater(dateString1, dateString2) {
  return dateString1 > dateString2
}

Then

isLater("2012-12-01", "2012-11-01")

returns true while

isLater("2012-12-01", "2013-11-01")

returns false

How ViewBag in ASP.NET MVC works

The ViewBag is an System.Dynamic.ExpandoObject as suggested. The properties in the ViewBag are essentially KeyValue pairs, where you access the value by the key. In this sense these are equivalent:

ViewBag.Foo = "Bar";
ViewBag["Foo"] = "Bar";

How to use FormData in react-native?

If you want to set custom content-type for formData item:

var img = {
    uri : 'file://opa.jpeg',
    name: 'opa.jpeg',
    type: 'image/jpeg'
};
var personInfo = {
    name : 'David',
    age: 16
};

var fdata = new FormData();
fdata.append('personInfo', {
    "string": JSON.stringify(personInfo), //This is how it works :)
    type: 'application/json'
});

fdata.append('image', {
    uri: img.uri,
    name: img.name,
    type: img.type
});

docker run <IMAGE> <MULTIPLE COMMANDS>

You can do this a couple of ways:

  1. Use the -w option to change the working directory:

    -w, --workdir="" Working directory inside the container

    https://docs.docker.com/engine/reference/commandline/run/#set-working-directory--w

  2. Pass the entire argument to /bin/bash:

    docker run image /bin/bash -c "cd /path/to/somewhere; python a.py"
    

How to remove all white spaces from a given text file

Try this:

tr -d " \t" <filename

See the manpage for tr(1) for more details.

Pass a local file in to URL in Java

have a look here for the full syntax: http://en.wikipedia.org/wiki/File_URI_scheme for unix-like systems it will be as @Alex said file:///your/file/here whereas for Windows systems would be file:///c|/path/to/file

How do I get the height of a div's full content with jQuery?

You can get it with .outerHeight().

Sometimes, it will return 0. For the best results, you can call it in your div's ready event.

To be safe, you should not set the height of the div to x. You can keep its height auto to get content populated properly with the correct height.

$('#x').ready( function(){
// alerts the height in pixels
alert($('#x').outerHeight());
})

You can find a detailed post here.

filename.whl is not supported wheel on this platform

During Tensorflow configuration I specified python3.6. But default python on my system is python2.7. Thus pip in my case means pip for 2.7. For me

pip3 install /tmp/tensorflow_pkg/NAME.whl

did the trick.

How can I get a Bootstrap column to span multiple rows?

The example below seemed to work. Just setting a height on the first element

<ul class="row">
    <li class="span4" style="height: 100px"><h1>1</h1></li>
    <li class="span4"><h1>2</h1></li>
    <li class="span4"><h1>3</h1></li>
    <li class="span4"><h1>4</h1></li>
    <li class="span4"><h1>5</h1></li>
    <li class="span4"><h1>6</h1></li>
    <li class="span4"><h1>7</h1></li>
    <li class="span4"><h1>8</h1></li>
</ul>

I can't help but thinking it's the wrong use of a row though.

What is the difference between document.location.href and document.location?

document.location is an object, while document.location.href is a string. But the former has a toString method, so you can read from it as if it was a string and get the same value as document.location.href.

In some browsers - most modern ones, I think - you can also assign to document.location as if it were a string. According to the Mozilla documentation however, it is better to use window.location for this purpose as document.location was originally read-only and so may not be as widely supported.

Given a starting and ending indices, how can I copy part of a string in C?

Just use memcpy.

If the destination isn't big enough, strncpy won't null terminate. if the destination is huge compared to the source, strncpy just fills the destination with nulls after the string. strncpy is pointless, and unsuitable for copying strings.

strncpy is like memcpy except it fills the destination with nulls once it sees one in the source. It's absolutely useless for string operations. It's for fixed with 0 padded records.

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

Just do it in the Base, that way any child can be Serialized, less code cleaner code.

public abstract class XmlBaseClass  
{
  public virtual string Serialize()
  {
    this.SerializeValidation();

    XmlSerializerNamespaces XmlNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
    XmlWriterSettings XmlSettings = new XmlWriterSettings
    {
      Indent = true,
      OmitXmlDeclaration = true
    };

    StringWriter StringWriter = new StringWriter();

    XmlSerializer Serializer = new XmlSerializer(this.GetType());
    XmlWriter XmlWriter = XmlWriter.Create(StringWriter, XmlSettings);
    Serializer.Serialize(XmlWriter, this, XmlNamespaces);
    StringWriter.Flush();
    StringWriter.Close();

    return StringWriter.ToString();

  }

  protected virtual void SerializeValidation() {}
}

[XmlRoot(ElementName = "MyRoot", Namespace = "MyNamespace")]
public class XmlChildClass : XmlBaseClass
{
  protected override void SerializeValidation()
  {
    //Add custom validation logic here or anything else you need to do
  }
}

This way you can call Serialize on the child class no matter the circumstance and still be able to do what you need to before object Serializes.

Difference between <context:annotation-config> and <context:component-scan>

The difference between the two is really simple!.

<context:annotation-config /> 

Enables you to use annotations that are restricted to wiring up properties and constructors only of beans!.

Where as

<context:component-scan base-package="org.package"/> 

Enables everything that <context:annotation-config /> can do, with addition of using stereotypes eg.. @Component, @Service , @Repository. So you can wire entire beans and not just restricted to constructors or properties!.

Push commits to another branch

Certainly, though it will only work if it's a fast forward of BRANCH2 or if you force it. The correct syntax to do such a thing is

git push <remote> <source branch>:<dest branch> 

See the description of a "refspec" on the git push man page for more detail on how it works. Also note that both a force push and a reset are operations that "rewrite history", and shouldn't be attempted by the faint of heart unless you're absolutely sure you know what you're doing with respect to any remote repositories and other people who have forks/clones of the same project.

Using :focus to style outer div?

This can now be achieve through the css method :focus-within as examplified in this post: http://www.scottohara.me/blog/2017/05/14/focus-within.html

_x000D_
_x000D_
/*_x000D_
  A normal (though ugly) focus_x000D_
  pseudo-class.  Any element that_x000D_
  can receive focus within the_x000D_
  .my-element parent will receive_x000D_
  a yellow background._x000D_
*/_x000D_
.my-element *:focus {_x000D_
  background: yellow !important;_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
/*_x000D_
  The :focus-within pseudo-class_x000D_
  will NOT style the elements within_x000D_
  the .my-element selector, like the_x000D_
  normal :focus above, but will_x000D_
  style the .my-element container_x000D_
  when its focusable children_x000D_
  receive focus._x000D_
*/_x000D_
.my-element:focus-within {_x000D_
  outline: 3px solid #333;_x000D_
}
_x000D_
<div class="my-element">_x000D_
  <p>A paragraph</p>_x000D_
  <p>_x000D_
    <a href="http://scottohara.me">_x000D_
      My Website_x000D_
    </a>_x000D_
  </p>_x000D_
_x000D_
  <label for="wut_email">_x000D_
    Your email:_x000D_
  </label>_x000D_
  <input type="email" id="wut_email" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Cannot change column used in a foreign key constraint

You can turn off foreign key checks:

SET FOREIGN_KEY_CHECKS = 0;

/* DO WHAT YOU NEED HERE */

SET FOREIGN_KEY_CHECKS = 1;

Please make sure to NOT use this on production and have a backup.

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

I encountered the same problem with Android devices but not iOS devices. Managed to resolve by specifying position:relative in the outer div of the absolutely positioned elements (with overflow:hidden for outer div)

Inserting the iframe into react component

You can use property dangerouslySetInnerHTML, like this

_x000D_
_x000D_
const Component = React.createClass({_x000D_
  iframe: function () {_x000D_
    return {_x000D_
      __html: this.props.iframe_x000D_
    }_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe> tag and pass it to new <iframe> tag, like that

_x000D_
_x000D_
/**_x000D_
 * getAttrs_x000D_
 * returns all attributes from TAG string_x000D_
 * @return Object_x000D_
 */_x000D_
const getAttrs = (iframeTag) => {_x000D_
  var doc = document.createElement('div');_x000D_
  doc.innerHTML = iframeTag;_x000D_
_x000D_
  const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
  return [].slice_x000D_
    .call(iframe.attributes)_x000D_
    .reduce((attrs, element) => {_x000D_
      attrs[element.name] = element.value;_x000D_
      return attrs;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <iframe {...getAttrs(this.props.iframe) } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
_x000D_
_x000D_

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

How to get distinct results in hibernate with joins and row-based limiting (paging)?

You can achieve the desired result by requesting a list of distinct ids instead of a list of distinct hydrated objects.

Simply add this to your criteria:

criteria.setProjection(Projections.distinct(Projections.property("id")));

Now you'll get the correct number of results according to your row-based limiting. The reason this works is because the projection will perform the distinctness check as part of the sql query, instead of what a ResultTransformer does which is to filter the results for distinctness after the sql query has been performed.

Worth noting is that instead of getting a list of objects, you will now get a list of ids, which you can use to hydrate objects from hibernate later.

What are the benefits of using C# vs F# or F# vs C#?

F# is not yet-another-programming-language if you are comparing it to C#, C++, VB. C#, C, VB are all imperative or procedural programming languages. F# is a functional programming language.

Two main benefits of functional programming languages (compared to imperative languages) are 1. that they don't have side-effects. This makes mathematical reasoning about properties of your program a lot easier. 2. that functions are first class citizens. You can pass functions as parameters to another functions just as easily as you can other values.

Both imperative and functional programming languages have their uses. Although I have not done any serious work in F# yet, we are currently implementing a scheduling component in one of our products based on C# and are going to do an experiment by coding the same scheduler in F# as well to see if the correctness of the implementation can be validated more easily than with the C# equivalent.

How can I parse a time string containing milliseconds in it with python?

For python 2 i did this

print ( time.strftime("%H:%M:%S", time.localtime(time.time())) + "." + str(time.time()).split(".",1)[1])

it prints time "%H:%M:%S" , splits the time.time() to two substrings (before and after the .) xxxxxxx.xx and since .xx are my milliseconds i add the second substring to my "%H:%M:%S"

hope that makes sense :) Example output:

13:31:21.72 Blink 01


13:31:21.81 END OF BLINK 01


13:31:26.3 Blink 01


13:31:26.39 END OF BLINK 01


13:31:34.65 Starting Lane 01


System.drawing namespace not found under console application

  1. Add using System.Drawing;
  2. Go to solution explorer and right click on references and select add reference
  3. Click on assemblies on the left
  4. search for system.drawing
  5. check system.drawing
  6. Click OK
  7. Done

jQuery convert line breaks to br (nl2br equivalent)

to improve @Luca Filosofi's accepted answer,

if needed, changing the beginning clause of this regex to be /([^>[\s]?\r\n]?) will also ingore the cases where the newline comes after a tag AND some whitespace, instead of just a tag immediately followed by a newline

How to remove ASP.Net MVC Default HTTP Headers?

You can also remove them by adding code to your global.asax file:

 protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
 {
   HttpContext.Current.Response.Headers.Remove("X-Powered-By");
   HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
   HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");
   HttpContext.Current.Response.Headers.Remove("Server");
 }

can't start MySql in Mac OS 10.6 Snow Leopard

my apple processor version10.6.3 is error and i can click system preference

Redirecting to a certain route based on condition

In your app.js file:

.run(["$rootScope", "$state", function($rootScope, $state) {

      $rootScope.$on('$locationChangeStart', function(event, next, current) {
        if (!$rootScope.loggedUser == null) {
          $state.go('home');
        }    
      });
}])

How to find prime numbers between 0 - 100?

Using Sieve of Eratosthenes, source on Rosettacode

fastest solution: https://repl.it/@caub/getPrimes-bench

_x000D_
_x000D_
function getPrimes(limit) {_x000D_
    if (limit < 2) return [];_x000D_
    var sqrtlmt = limit**.5 - 2;_x000D_
    var nums = Array.from({length: limit-1}, (_,i)=>i+2);_x000D_
    for (var i = 0; i <= sqrtlmt; i++) {_x000D_
        var p = nums[i]_x000D_
        if (p) {_x000D_
            for (var j = p * p - 2; j < nums.length; j += p)_x000D_
                nums[j] = 0;_x000D_
        }_x000D_
    }_x000D_
    return nums.filter(x => x); // return non 0 values_x000D_
}_x000D_
document.body.innerHTML = `<pre style="white-space:pre-wrap">${getPrimes(100).join(', ')}</pre>`;_x000D_
_x000D_
// for fun, this fantasist regexp way (very inefficient):_x000D_
// Array.from({length:101}, (_,i)=>i).filter(n => n>1&&!/^(oo+)\1+$/.test('o'.repeat(n))
_x000D_
_x000D_
_x000D_

How to TryParse for Enum value?

As others have said, you have to implement your own TryParse. Simon Mourier is providing a full implementation which takes care of everything.

If you are using bitfield enums (i.e. flags), you also have to handle a string like "MyEnum.Val1|MyEnum.Val2" which is a combination of two enum values. If you just call Enum.IsDefined with this string, it will return false, even though Enum.Parse handles it correctly.

Update

As mentioned by Lisa and Christian in the comments, Enum.TryParse is now available for C# in .NET4 and up.

MSDN Docs

How to check Grants Permissions at Run-Time?

You can also query by following code snippet as backward compatible;

int hasPermission = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_CONTACTS);
if (hasPermission == PackageManager.PERMISSION_GRANTED) {
    //Do smthng
}

To show only file name without the entire directory path

There are several ways you can achieve this. One would be something like:

for filepath in /path/to/dir/*
do
    filename=$(basename $filepath)

    ... whatever you want to do with the file here
done

Java Date - Insert into database

Before I answer your question, I'd like to mention that you should probably look into using some sort of ORM solution (e.g., Hibernate), wrapped behind a data access tier. What you are doing appear to be very anti-OO. I admittedly do not know what the rest of your code looks like, but generally, if you start seeing yourself using a lot of Utility classes, you're probably taking too structural of an approach.

To answer your question, as others have mentioned, look into java.sql.PreparedStatement, and use java.sql.Date or java.sql.Timestamp. Something like (to use your original code as much as possible, you probably want to change it even more):

java.util.Date myDate = new java.util.Date("10/10/2009");
java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());

sb.append("INSERT INTO USERS");
sb.append("(USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE) ");
sb.append("VALUES ( ");
sb.append("?, ?, ?, ?, ?");
sb.append(")");

Connection conn = ...;// you'll have to get this connection somehow
PreparedStatement stmt = conn.prepareStatement(sb.toString());
stmt.setString(1, userId);
stmt.setString(2, myUser.GetFirstName());
stmt.setString(3, myUser.GetLastName());
stmt.setString(4, myUser.GetSex());
stmt.setDate(5, sqlDate);

stmt.executeUpdate(); // optionally check the return value of this call

One additional benefit of this approach is that it automatically escapes your strings for you (e.g., if were to insert someone with the last name "O'Brien", you'd have problems with your original implementation).

How to make UIButton's text alignment center? Using IB

For swift 4, xcode 9

myButton.contentHorizontalAlignment = .center

How to "Open" and "Save" using java

Maybe you could take a look at JFileChooser, which allow you to use native dialogs in one line of code.

Partly cherry-picking a commit with Git

Building on Mike Monkiewicz answer you can also specify a single or more files to checkout from the supplied sha1/branch.

git checkout -p bc66559 -- path/to/file.java 

This will allow you to interactively pick the changes you want to have applied to your current version of the file.

Equivalent of String.format in jQuery

This violates DRY principle, but it's a concise solution:

var button = '<a href="{link}" class="btn">{text}</a>';
button = button.replace('{text}','Authorize on GitHub').replace('{link}', authorizeUrl);

HTML to PDF with Node.js

In my view, the best way to do this is via an API so that you do not add a large and complex dependency into your app that runs unmanaged code, that needs to be frequently updated.

Here is a simple way to do this, which is free for 800 requests/month:

var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;

// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';



var apiInstance = new CloudmersiveConvertApiClient.ConvertWebApi();

var input = new CloudmersiveConvertApiClient.HtmlToPdfRequest(); // HtmlToPdfRequest | HTML to PDF request parameters
input.Html = "<b>Hello, world!</b>";


var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully. Returned data: ' + data);
  }
};
apiInstance.convertWebHtmlToPdf(input, callback);

With the above approach you can also install the API on-premises or on your own infrastructure if you prefer.

How can I get the active screen dimensions?

in C# winforms I have got start point (for case when we have several monitor/diplay and one form is calling another one) with help of the following method:

private Point get_start_point()
    {
        return
            new Point(Screen.GetBounds(parent_class_with_form.ActiveForm).X,
                      Screen.GetBounds(parent_class_with_form.ActiveForm).Y
                      );
    }

Remove a marker from a GoogleMap

For those that are following the example on this GoogleMaps - MapWithMarker project, you may remove the marker by doing so

override fun onMapReady(googleMap: GoogleMap?) {
    googleMap?.apply {

        // Remove marker
        clear()

        val sydney = LatLng(-33.852, 151.211)
        addMarker(
            MarkerOptions()
                .position(sydney)
                .title("Marker in Sydney")
        )
        moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}

How to return a string from a C++ function?

You never give any value to your strings in main so they are empty, and thus obviously the function returns an empty string.

Replace:

string str1, str2, str3;

with:

string str1 = "the dog jumped over the fence";
string str2 = "the";
string str3 = "that";

Also, you have several problems in your replaceSubstring function:

int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
  • std::string::find returns a std::string::size_type (aka. size_t) not an int. Two differences: size_t is unsigned, and it's not necessarily the same size as an int depending on your platform (eg. on 64 bits Linux or Windows size_t is unsigned 64 bits while int is signed 32 bits).
  • What happens if s2 is not part of s1? I'll leave it up to you to find how to fix that. Hint: std::string::npos ;)

Java generics - why is "extends T" allowed but not "implements T"?

In fact, when using generic on interface, the keyword is also extends. Here is the code example:

There are 2 classes that implements the Greeting interface:

interface Greeting {
    void sayHello();
}

class Dog implements Greeting {
    @Override
    public void sayHello() {
        System.out.println("Greeting from Dog: Hello ");
    }
}

class Cat implements Greeting {
    @Override
    public void sayHello() {
        System.out.println("Greeting from Cat: Hello ");
    }
}

And the test code:

@Test
public void testGeneric() {
    Collection<? extends Greeting> animals;

    List<Dog> dogs = Arrays.asList(new Dog(), new Dog(), new Dog());
    List<Cat> cats = Arrays.asList(new Cat(), new Cat(), new Cat());

    animals = dogs;
    for(Greeting g: animals) g.sayHello();

    animals = cats;
    for(Greeting g: animals) g.sayHello();
}

Printing *s as triangles in Java?

This will print stars in triangle:

`   
public class printstar{
public static void main (String args[]){
int m = 0;
for(int i=1;i<=4;i++){
for(int j=1;j<=4-i;j++){
System.out.print("");}

for (int n=0;n<=i+m;n++){
if (n%2==0){
System.out.print("*");}
else {System.out.print(" ");}
}
m = m+1;
System.out.println("");
}
}
}'

Reading and understanding this should help you with designing the logic next time..

How to select all instances of a variable and edit variable name in Sublime

As user1767754 said, the key here is to not make any selection initially.

Just place the cursor inside the variable name, don't double click to select it. For single character variables, place the cursor at the front or end of the variable to not make any selection initially.

Now keep hitting Cmd+D for next variable selection or Ctrl+Cmd+G for selecting all variables at once. It will magically select only the variables.

Composer: Command Not Found

I am using CentOS and had same problem.

I changed /usr/local/bin/composer to /usr/bin/composer and it worked.

Run below command :

curl -sS https://getcomposer.org/installer | php sudo mv composer.phar /usr/bin/composer

Verify Composer is installed or not

composer --version

Git submodule head 'reference is not a tree' error

Assuming the submodule's repository does contain a commit you want to use (unlike the commit that is referenced from current state of the super-project), there are two ways to do it.

The first requires you to already know the commit from the submodule that you want to use. It works from the “inside, out” by directly adjusting the submodule then updating the super-project. The second works from the “outside, in” by finding the super-project's commit that modified the submodule and then reseting the super-project's index to refer to a different submodule commit.

Inside, Out

If you already know which commit you want the submodule to use, cd to the submodule, check out the commit you want, then git add and git commit it back in the super-project.

Example:

$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'

Oops, someone made a super-project commit that refers to an unpublished commit in the submodule sub. Somehow, we already know that we want the submodule to be at commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c. Go there and check it out directly.

Checkout in the Submodule

$ cd sub
$ git checkout 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
Note: moving to '5d5a3ee314476701a20f2c6ec4a53f88d651df6c' which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
  git checkout -b <new_branch_name>
HEAD is now at 5d5a3ee... quux
$ cd ..

Since we are checking out a commit, this produces a detached HEAD in the submodule. If you want to make sure that the submodule is using a branch, then use git checkout -b newbranch <commit> to create and checkout a branch at the commit or checkout the branch that you want (e.g. one with the desired commit at the tip).

Update the Super-project

A checkout in the submodule is reflected in the super-project as a change to the working tree. So we need to stage the change in the super-project's index and verify the results.

$ git add sub

Check the Results

$ git submodule update
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

The submodule update was silent because the submodule is already at the specified commit. The first diff shows that the index and worktree are the same. The third diff shows that the only staged change is moving the sub submodule to a different commit.

Commit

git commit

This commits the fixed-up submodule entry.


Outside, In

If you are not sure which commit you should use from the submodule, you can look at the history in the superproject to guide you. You can also manage the reset directly from the super-project.

$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'

This is the same situation as above. But this time we will focus on fixing it from the super-project instead of dipping into the submodule.

Find the Super-project's Errant Commit

$ git log --oneline -p -- sub
ce5d37c local change in sub
diff --git a/sub b/sub
index 5d5a3ee..e47c0a1 160000
--- a/sub
+++ b/sub
@@ -1 +1 @@
-Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
+Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
bca4663 added sub
diff --git a/sub b/sub
new file mode 160000
index 0000000..5d5a3ee
--- /dev/null
+++ b/sub
@@ -0,0 +1 @@
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

OK, it looks like it went bad in ce5d37c, so we will restore the submodule from its parent (ce5d37c~).

Alternatively, you can take the submodule's commit from the patch text (5d5a3ee314476701a20f2c6ec4a53f88d651df6c) and use the above “inside, out” process instead.

Checkout in the Super-project

$ git checkout ce5d37c~ -- sub

This reset the submodule entry for sub to what it was at commit ce5d37c~ in the super-project.

Update the Submodule

$ git submodule update
Submodule path 'sub': checked out '5d5a3ee314476701a20f2c6ec4a53f88d651df6c'

The submodule update went OK (it indicates a detached HEAD).

Check the Results

$ git diff ce5d37c~ -- sub
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

The first diff shows that sub is now the same in ce5d37c~. The second diff shows that the index and worktree are the same. The third diff shows the only staged change is moving the sub submodule to a different commit.

Commit

git commit

This commits the fixed-up submodule entry.