Programs & Examples On #Axapta

Microsoft Dynamics AX is one of Microsoft’s Enterprise Resource Planning software products. It is part of the Microsoft Dynamics family. The early versions (from 1.0 to 3.0) were called Axapta, while the later versions (from 3.0 SP6 to AX 2012 and last version AX 7) are called Dynamics AX.

Crop image in PHP

$image = imagecreatefromjpeg($_GET['src']);
$filename = 'images/cropped_whatever.jpg'

Must be replaced with:

$image = imagecreatefromjpeg($_GET['src']);

Then it will work!

How to get exact browser name and version?

  • There is a conflict between (Safari) and (Opera) and (Chrome) !!!

  • The above codes couldn't work properly

This is my code, and it works very well without any conflict:

function ExactBrowserName()
{

$ExactBrowserNameUA=$_SERVER['HTTP_USER_AGENT'];

if (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "opr/")) {
    // OPERA
    $ExactBrowserNameBR="Opera";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "chrome/")) {
    // CHROME
    $ExactBrowserNameBR="Chrome";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "msie")) {
    // INTERNET EXPLORER
    $ExactBrowserNameBR="Internet Explorer";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "firefox/")) {
    // FIREFOX
    $ExactBrowserNameBR="Firefox";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "opr/")==false and strpos(strtolower($ExactBrowserNameUA), "chrome/")==false) {
    // SAFARI
    $ExactBrowserNameBR="Safari";
} else {
    // OUT OF DATA
    $ExactBrowserNameBR="OUT OF DATA";
};

return $ExactBrowserNameBR;
}

How to install cron

Install cron on Linux/Unix:

apt-get install cron

Use cron on Linux/Unix

crontab -e

See the canonical answer about cron for more details: https://serverfault.com/questions/449651/why-is-my-crontab-not-working-and-how-can-i-troubleshoot-it

PHP Fatal error: Uncaught exception 'Exception'

This is expected behavior for an uncaught exception with display_errors off.

Your options here are to turn on display_errors via php or in the ini file or catch and output the exception.

 ini_set("display_errors", 1);

or

 try{
     // code that may throw an exception
 } catch(Exception $e){
     echo $e->getMessage();
 }

If you are throwing exceptions, the intention is that somewhere further down the line something will catch and deal with it. If not it is a server error (500).

Another option for you would be to use set_exception_handler to set a default error handler for your script.

 function default_exception_handler(Exception $e){
          // show something to the user letting them know we fell down
          echo "<h2>Something Bad Happened</h2>";
          echo "<p>We fill find the person responsible and have them shot</p>";
          // do some logging for the exception and call the kill_programmer function.
 }
 set_exception_handler("default_exception_handler");

fatal: Not a git repository (or any of the parent directories): .git

The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo

  1. Are you in the right directory? Does typing ls show the right files?
  2. Have you initialized the repository yet? Typed git init? (git-init documentation)

Either of those would cause your error.

Using variables inside a bash heredoc

In answer to your first question, there's no parameter substitution because you've put the delimiter in quotes - the bash manual says:

The format of here-documents is:

      <<[-]word
              here-document
      delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. [...]

If you change your first example to use <<EOF instead of << "EOF" you'll find that it works.

In your second example, the shell invokes sudo only with the parameter cat, and the redirection applies to the output of sudo cat as the original user. It'll work if you try:

sudo sh -c "cat > /path/to/outfile" <<EOT
my text...
EOT

How can I drop a table if there is a foreign key constraint in SQL Server?

Type this .... SET foreign_key_checks = 0;
delete your table then type SET foreign_key_checks = 1;

MySQL – Temporarily disable Foreign Key Checks or Constraints

Simple way to find if two different lists contain exactly the same elements?

It depends on what concrete List class you are using. The abstract class AbstractCollection has a method called containsAll(Collection) that takes another collection ( a List is a collection) and:

Returns true if this collection contains all of the elements in the specified collection.

So if an ArrayList is being passed in you can call this method to see if they are exactly the same.

       List foo = new ArrayList();
    List bar = new ArrayList();
    String str = "foobar";

    foo.add(str);
    bar.add(str);

    foo.containsAll(bar);

The reason for containsAll() is because it iterates through the first list looking for the match in the second list. So if they are out of order equals() will not pick it up.

EDIT: I just want to make a comment here about the amortized running time of performing the various options being offered. Is running time important? Sure. Is it the only thing you should consider? No.

The cost of copying EVERY single element from your lists into other lists takes time, and it also takes up a good chunk of memory (effectively doubling the memory you are using).

So if memory in your JVM isn't a concern (which it should generally be) then you still need to consider the time it takes to copy every element from two lists into two TreeSets. Remember it is sorting every element as it enters them.

My final advice? You need to consider your data set and how many elements you have in your data set, and also how large each object in your data set is before you can make a good decision here. Play around with them, create one each way and see which one runs faster. It's a good exercise.

How do I replace a character at a particular index in JavaScript?

If you want to replace characters in string, you should create mutable strings. These are essentially character arrays. You could create a factory:

  function MutableString(str) {
    var result = str.split("");
    result.toString = function() {
      return this.join("");
    }
    return result;
  }

Then you can access the characters and the whole array converts to string when used as string:

  var x = MutableString("Hello");
  x[0] = "B"; // yes, we can alter the character
  x.push("!"); // good performance: no new string is created
  var y = "Hi, "+x; // converted to string: "Hi, Bello!"

Convert np.array of type float64 to type uint8 scaling values

A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2], the code right now would scale that to have intensities of [0, 128, 255]. You want these to remain small after converting to np.uint8.

Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo and provide it the type (dtype) of the image and you will obtain a structure of information for that type. You would then access the max field from this structure to determine the maximum value.

So with the above, do the following modifications to your code:

import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)

Note that I've additionally converted the image into np.float64 in case the incoming data type is not so and to maintain floating-point precision when doing the division.

Cross Domain Form POSTing

The same origin policy is applicable only for browser side programming languages. So if you try to post to a different server than the origin server using JavaScript, then the same origin policy comes into play but if you post directly from the form i.e. the action points to a different server like:

<form action="http://someotherserver.com">

and there is no javascript involved in posting the form, then the same origin policy is not applicable.

See wikipedia for more information

Can't find System.Windows.Media namespace?

For Visual Studio 2017

Find "References" in Solution explorer

Right click "References"

Choose "Add Reference..."

Find "Presentation.Core" list and check checkbox

Click OK

How to use ng-if to test if a variable is defined

You can still use angular.isDefined()

You just need to set

$rootScope.angular = angular;

in the "run" phase.

See update plunkr: http://plnkr.co/edit/h4ET5dJt3e12MUAXy1mS?p=preview

symfony 2 twig limit the length of the text and put three dots

An even more elegant solution is to limit the text by the number of words (and not by number of characters). This prevents ugly tear throughs (e.g. 'Stackov...').

Here's an example where I shorten only text blocks longer than 10 words:

{% set text = myentity.text |split(' ') %} 

{% if text|length > 10 %} 
    {% for t in text|slice(0, 10) %}
        {{ t }} 
    {% endfor %}
    ...
{% else %}
    {{ text|join(' ') }}
{% endif %}

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

In the project into the folder Libraries-->right click --> Add Library --> Mysqlconnector 5.1

AngularJS - Access to child scope

Yes, we can assign variables from child controller to the variables in parent controller. This is one possible way:

Overview: The main aim of the code, below, is to assign child controller's $scope.variable to parent controller's $scope.assign

Explanation: There are two controllers. In the html, notice that the parent controller encloses the child controller. That means the parent controller will be executed before child controller. So, first setValue() will be defined and then the control will go to the child controller. $scope.variable will be assigned as "child". Then this child scope will be passed as an argument to the function of parent controller, where $scope.assign will get the value as "child"

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script type="text/javascript">
    var app = angular.module('myApp',[]);

    app.controller('child',function($scope){
        $scope.variable = "child";
        $scope.$parent.setValue($scope);
    });

    app.controller('parent',function($scope){
        $scope.setValue = function(childscope) {
            $scope.assign = childscope.variable;
        }
    });

</script>
<body ng-app="myApp">
 <div ng-controller="parent">
    <p>this is parent: {{assign}}</p>
    <div ng-controller="child">
        <p>this is {{variable}}</p>
    </div>
 </div>
</body>
</html>

How to run html file on localhost?

You can use python -m http.server. By default the local server will run on port 8000. If you would like to change this, simply add the port number python -m http.server 1234

If you are using python 2 (instead of 3), the equivalent command is python -m SimpleHTTPServer

How to run a Maven project from Eclipse?

Well, you need to incorporate exec-maven-plugin, this plug-in performs the same thing that you do on command prompt when you type in java -cp .;jarpaths TestMain. You can pass argument and define which phase (test, package, integration, verify, or deploy), you want this plug-in to call your main class.

You need to add this plug-in under <build> tag and specify parameters. For example

   <project>
    ...
    ...
    <build>
     <plugins>
      <plugin>
       <groupId>org.codehaus.mojo</groupId>
       <artifactId>exec-maven-plugin</artifactId>
       <version>1.1.1</version>
       <executions>
        <execution>
         <phase>test</phase>
         <goals>
          <goal>java</goal>
         </goals>
         <configuration>
          <mainClass>my.company.name.packageName.TestMain</mainClass>
          <arguments>
           <argument>myArg1</argument>
           <argument>myArg2</argument>
          </arguments>
         </configuration>
        </execution>
       </executions>
      </plugin>
     </plugins>
    </build>
    ...
    ...
   </project>

Now, if you right-click on on the project folder and do Run As > Maven Test, or Run As > Maven Package or Run As > Maven Install, the test phase will execute and so your Main class.

Group By Eloquent ORM

try: ->unique('column')

example:

$users = User::get()->unique('column');

How does MySQL CASE work?

CASE in MySQL is both a statement and an expression, where each usage is slightly different.

As a statement, CASE works much like a switch statement and is useful in stored procedures, as shown in this example from the documentation (linked above):

DELIMITER |

CREATE PROCEDURE p()
  BEGIN
    DECLARE v INT DEFAULT 1;

    CASE v
      WHEN 2 THEN SELECT v;
      WHEN 3 THEN SELECT 0;
      ELSE
        BEGIN -- Do other stuff
        END;
    END CASE;
  END;
  |

However, as an expression it can be used in clauses:

SELECT *
  FROM employees
  ORDER BY
    CASE title
      WHEN "President" THEN 1
      WHEN "Manager" THEN 2
      ELSE 3
    END, surname

Additionally, both as a statement and as an expression, the first argument can be omitted and each WHEN must take a condition.

SELECT *
  FROM employees
  ORDER BY
    CASE 
      WHEN title = "President" THEN 1
      WHEN title = "Manager" THEN 2
      ELSE 3
    END, surname

I provided this answer because the other answer fails to mention that CASE can function both as a statement and as an expression. The major difference between them is that the statement form ends with END CASE and the expression form ends with just END.

Apply CSS styles to an element depending on its child elements

On top of @kp's answer:

I'm dealing with this and in my case, I have to show a child element and correct the height of the parent object accordingly (auto-sizing is not working in a bootstrap header for some reason I don't have time to debug).

But instead of using javascript to modify the parent, I think I'll dynamically add a CSS class to the parent and CSS-selectively show the children accordingly. This will maintain the decisions in the logic and not based on a CSS state.

tl;dr; apply the a and b styles to the parent <div>, not the child (of course, not everyone will be able to do this. i.e. Angular components making decisions of their own).

<style>
  .parent            { height: 50px; }
  .parent div        { display: none; }
  .with-children     { height: 100px; }
  .with-children div { display: block; }
</style>

<div class="parent">
  <div>child</div>
</div>

<script>
  // to show the children
  $('.parent').addClass('with-children');
</script>

How to check what version of jQuery is loaded?

// My original 'goto' means to get the version
$.fn.jquery

// Another *similar* option
$().jQuery

// If there is concern that there may be multiple implementations of `$` then:
jQuery.fn.jquery

Recently I have had issues using $.fn.jquery/$().jQuery on a few sites so I wanted to note a third simple command to pull the jQuery version.

If you get back a version number -- usually as a string -- then jQuery is loaded and that is what version you're working with. If not loaded then you should get back undefined or maybe even an error.

Pretty old question and I've seen a few people that have already mentioned my answer in comments. However, I find that sometimes great answers that are left as comments can go unnoticed; especially when there are a lot of comments to an answer you may find yourself digging through piles of them looking for a gem. Hopefully this helps someone out!

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

Restrict varchar() column to specific values?

When you are editing a table
Right Click -> Check Constraints -> Add -> Type something like Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly') in expression field and a good constraint name in (Name) field.
You are done.

How do I escape spaces in path for scp copy in Linux?

I had huge difficulty getting this to work for a shell variable containing a filename with whitespace. For some reason using:

file="foo bar/baz"
scp [email protected]:"'$file'"

as in @Adrian's answer seems to fail.

Turns out that what works best is using a parameter expansion to prepend backslashes to the whitespace as follows:

file="foo bar/baz"
file=${file// /\\ }
scp [email protected]:"$file"

What does `ValueError: cannot reindex from a duplicate axis` mean?

For people who are still struggling with this error, it can also happen if you accidentally create a duplicate column with the same name. Remove duplicate columns like so:

df = df.loc[:,~df.columns.duplicated()]

Create list of object from another using Java 8 Streams

If you want to iterate over a list and create a new list with "transformed" objects, you should use the map() function of stream + collect(). In the following example I find all people with the last name "l1" and each person I'm "mapping" to a new Employee instance.

public class Test {

    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
                new Person("e1", "l1"),
                new Person("e2", "l1"),
                new Person("e3", "l2"),
                new Person("e4", "l2")
        );

        List<Employee> employees = persons.stream()
                .filter(p -> p.getLastName().equals("l1"))
                .map(p -> new Employee(p.getName(), p.getLastName(), 1000))
                .collect(Collectors.toList());

        System.out.println(employees);
    }

}

class Person {

    private String name;
    private String lastName;

    public Person(String name, String lastName) {
        this.name = name;
        this.lastName = lastName;
    }

    // Getter & Setter
}

class Employee extends Person {

    private double salary;

    public Employee(String name, String lastName, double salary) {
        super(name, lastName);
        this.salary = salary;
    }

    // Getter & Setter
}

Add to python path mac os x

Modifications to sys.path only apply for the life of that Python interpreter. If you want to do it permanently you need to modify the PYTHONPATH environment variable:

PYTHONPATH="/Me/Documents/mydir:$PYTHONPATH"
export PYTHONPATH

Note that PATH is the system path for executables, which is completely separate.

**You can write the above in ~/.bash_profile and the source it using source ~/.bash_profile

Using ExcelDataReader to read Excel data starting from a particular cell

One way to do it :

FileStream stream = File.Open(@"c:\working\test.xls", FileMode.Open, FileAccess.Read);

IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);

excelReader.IsFirstRowAsColumnNames = true;

DataSet result = excelReader.AsDataSet();

The result.Tables contains the sheets and the result.tables[0].Rows contains the cell rows.

Change DIV content using ajax, php and jQuery

<script>

function getSummary(id)
{
   $.ajax({

     type: "GET",
     url: 'Your URL',
     data: "id=" + id, // appears as $_GET['id'] @ your backend side
     success: function(data) {
           // data is ur summary
          $('#summary').html(data);
     }

   });

}
</script>

And add onclick event in your lists

<a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div>

Magento: get a static block as html in a phtml file

In the layout (app/design/frontend/your_theme/layout/default.xml):

<default>
    <cms_page> <!-- need to be redefined for your needs -->
        <reference name="content">
            <block type="cms/block" name="cms_newest_product" as="cms_newest_product">
                <action method="setBlockId"><block_id>newest_product</block_id></action>
            </block>
        </reference>
    </cms_page>
</default>

In your phtml template:

<?php echo $this->getChildHtml('newest_product'); ?>

Don't forget about cache cleaning.

I think it help.

Register 32 bit COM DLL to 64 bit Windows 7

For 32 bit DLLS in Windows 64 bit platforms:

  1. Copy whatever.dll to c:\windows\sysWOW64\
  2. Open a CMD prompt AS ADMINISTRATOR (very important)

In the CMD window:

  1. CD c:\windows\sysWOW64\
  2. regsvr32 whatever.dll

You will then be executing the 32-bit regsvr (c:\windows\sysWOW64\regsvr.exe) on a 32 bit dll

How to debug "ImagePullBackOff"?

I was facing the similar problem, but instead of one all of my pods were not ready and displaying Ready status 0/1 Something like enter image description here

I tried a lot of things but at last i found that the context was not correctly set. Please use following command and ensure you are in correct context

kubectl config get-contexts

path.join vs path.resolve with __dirname

From the doc for path.resolve:

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

But path.join keeps trailing slashes

So

__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'

How often does python flush to a file?

You can also check the default buffer size by calling the read only DEFAULT_BUFFER_SIZE attribute from io module.

import io
print (io.DEFAULT_BUFFER_SIZE)

How do I prevent DIV tag starting a new line?

You can simply use:

#contentInfo_new br {display:none;}

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

Looping through an array of objects is a pretty fundamental functionality. This is what works for me.

_x000D_
_x000D_
var person = [];_x000D_
person[0] = {_x000D_
  firstName: "John",_x000D_
  lastName: "Doe",_x000D_
  age: 60_x000D_
};_x000D_
_x000D_
var i, item;_x000D_
_x000D_
for (i = 0; i < person.length; i++) {_x000D_
  for (item in person[i]) {_x000D_
    document.write(item + ": " + person[i][item] + "<br>");_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Git error on git pull (unable to update local ref)

Speaking from a PC user - Reboot.

Honestly, it worked for me. I've solved two strange git issues I thought were corruptions this way.

New features in java 7

In addition to what John Skeet said, here's an overview of the Java 7 project. It includes a list and description of the features.

Note: JDK 7 was released on July 28, 2011, so you should now go to the official java SE site.

How to get absolute value from double - c-language

It's worth noting that Java can overload a method such as abs so that it works with an integer or a double. In C, overloading doesn't exist, so you need different functions for integer versus double.

Regular expression for URL validation (in JavaScript)

In the accepted answer bobince got it right: validating only the scheme name, ://, and spaces and double quotes is usually enough. Here is how the validation can be implemented in JavaScript:

var url = 'http://www.google.com';
var valid = /^(ftp|http|https):\/\/[^ "]+$/.test(url);
// true

or

var r = /^(ftp|http|https):\/\/[^ "]+$/;
r.test('http://www.goo le.com');
// false

or

var url = 'http:www.google.com';
var r = new RegExp(/^(ftp|http|https):\/\/[^ "]+$/);
r.test(url);
// false

References for syntax:

Android: keep Service running when app is killed

If your Service is started by your app then actually your service is running on main process. so when app is killed service will also be stopped. So what you can do is, send broadcast from onTaskRemoved method of your service as follows:

 Intent intent = new Intent("com.android.ServiceStopped");
 sendBroadcast(intent);

and have an broadcast receiver which will again start a service. I have tried it. service restarts from all type of kills.

Python assigning multiple variables to same value? list behavior

in your first example a = b = c = [1, 2, 3] you are really saying:

 'a' is the same as 'b', is the same as 'c' and they are all [1, 2, 3]

If you want to set 'a' equal to 1, 'b' equal to '2' and 'c' equal to 3, try this:

a, b, c = [1, 2, 3]

print(a)
--> 1
print(b)
--> 2
print(c)
--> 3

Hope this helps!

MemoryStream - Cannot access a closed Stream

Since .net45 you can use the LeaveOpen constructor argument of StreamWriter and still use the using statement. Example:

using (var ms = new MemoryStream())
{
    using (var sw = new StreamWriter(ms, Encoding.UTF8, 1024, true))
    {
        sw.WriteLine("data");
        sw.WriteLine("data 2");    
    }

    ms.Position = 0;
    using (var sr = new StreamReader(ms))
    {
        Console.WriteLine(sr.ReadToEnd());
    }
}

Using jQuery to see if a div has a child with a certain class

Use the children funcion of jQuery.

$("#text-field").keydown(function(event) {
    if($('#popup').children('p.filled-text').length > 0) {
        console.log("Found");
     }
});

$.children('').length will return the count of child elements which match the selector.

How to convert List<Integer> to int[] in Java?

With Eclipse Collections, you can do the following if you have a list of type java.util.List<Integer>:

List<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5);
int[] ints = LazyIterate.adapt(integers).collectInt(i -> i).toArray();

Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, ints);

If you already have an Eclipse Collections type like MutableList, you can do the following:

MutableList<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5);
int[] ints = integers.asLazy().collectInt(i -> i).toArray();

Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, ints);

Note: I am a committer for Eclipse Collections

how to start stop tomcat server using CMD?

you can use this trick to run tomcat using cmd and directly by tomcat bin folder.

1. set the path of jdk.

2.

To set path. go to Desktop and right click on computer icon. Click the Properties

go to Advance System Settings.

then Click Advance to Environment variables.

Click new and set path AS,

in the column Variable name=JAVA_HOME

Variable Value=C:\Program Files\Java\jdk1.6.0_19

Click ok ok.

now path is stetted.

3.

Go to tomcat folder where you installed the tomcat. go to bin folder. there are two window batch files.

1.Startup

2.Shutdown.

By using cmd if you installed the tomcate in D Drive

type on cmd screen

  1. D:

  2. Cd tomcat\bin then type Startup.

4. By clicking them you can start and stop the tomcat.

5.

Final step.

if you start and want to check it.

open a Browser in URL bar type.

**HTTP://localhost:8080/**

How to pause in C?

For Linux; getchar() is all you need.

If you are on Windows, check out the following, it is exactly what you need!

kbit() function

  • kbhit() function is used to determine if a key has been pressed or not.
  • To use kbhit() in C or C++ prorams you have to include the header file "conio.h".

For example, see how it works in the following program;

//any_key.c

#include <stdio.h> 
#include <conio.h>

int main(){

    //code here
    printf ("Press any key to continue . . .\n");
    while (1) if (kbhit()) break; 
    //code here 
    return 0;

}

When I compile and run the program, this is what I see.

Only when user presses just one key from the keyboard, kbhit() returns 1.

How to automatically close cmd window after batch file execution?

You could try the somewhat dangerous: taskkill /IM cmd.exe ..dangerous bcz that will kill the cmd that is open and any cmd's opened before it.

Or add a verification to confirm that you had the right cmd.exe and then kill it via PID, such as this:

set loc=%time%%random%
title=%loc%
for /f "tokens=2 delims= " %%A in ('tasklist /v ^| findstr /i "%loc%"') do (taskkill /PID %%A) 

Substitute (pslist &&A) or (tasklist /FI "PID eq %%A") for the (taskkill /PID %%A) if you want to check it first (and maybe have pstools installed).

Logging request/response messages when using HttpClient

See http://mikehadlow.blogspot.com/2012/07/tracing-systemnet-to-debug-http-clients.html

To configure a System.Net listener to output to both the console and a log file, add the following to your assembly configuration file:

<system.diagnostics>
  <trace autoflush="true" />
  <sources>
    <source name="System.Net">
      <listeners>
        <add name="MyTraceFile"/>
        <add name="MyConsole"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add
      name="MyTraceFile"
      type="System.Diagnostics.TextWriterTraceListener"
      initializeData="System.Net.trace.log" />
    <add name="MyConsole" type="System.Diagnostics.ConsoleTraceListener" />
  </sharedListeners>
  <switches>
    <add name="System.Net" value="Verbose" />
  </switches>
</system.diagnostics>

How do I create a master branch in a bare Git repository?

By default there will be no branches listed and pops up only after some file is placed. You don't have to worry much about it. Just run all your commands like creating folder structures, adding/deleting files, commiting files, pushing it to server or creating branches. It works seamlessly without any issue.

https://git-scm.com/docs

Is there a “not in” operator in JavaScript for checking object properties?

Personally I find

if (id in tutorTimes === false) { ... }

easier to read than

if (!(id in tutorTimes)) { ... }

but both will work.

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

getting only name of the class Class.getName()

or programmaticaly

String s = String.class.getName();
s = s.substring(s.lastIndexOf('.') + 1);

Box shadow in IE7 and IE8

You could try this

box-shadow:
progid:DXImageTransform.Microsoft.dropshadow(OffX=0, OffY=10, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=10, OffY=20, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=20, OffY=30, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=30, OffY=40, Color='#19000000');

How do you assert that a certain exception is thrown in JUnit 4 tests?

Now that JUnit 5 and JUnit 4.13 have been released, the best option would be to use Assertions.assertThrows() (for JUnit 5) and Assert.assertThrows() (for JUnit 4.13). See the Junit 5 User Guide.

Here is an example that verifies an exception is thrown, and uses Truth to make assertions on the exception message:

public class FooTest {
  @Test
  public void doStuffThrowsIndexOutOfBoundsException() {
    Foo foo = new Foo();

    IndexOutOfBoundsException e = assertThrows(
        IndexOutOfBoundsException.class, foo::doStuff);

    assertThat(e).hasMessageThat().contains("woops!");
  }
}

The advantages over the approaches in the other answers are:

  1. Built into JUnit
  2. You get a useful exception message if the code in the lambda doesn't throw an exception, and a stacktrace if it throws a different exception
  3. Concise
  4. Allows your tests to follow Arrange-Act-Assert
  5. You can precisely indicate what code you are expecting to throw the exception
  6. You don't need to list the expected exception in the throws clause
  7. You can use the assertion framework of your choice to make assertions about the caught exception

A similar method will be added to org.junit Assert in JUnit 4.13.

Do I need to explicitly call the base virtual destructor?

What the others said, but also note that you do not have to declare the destructor virtual in the derived class. Once you declare a destructor virtual, as you do in the base class, all derived destructors will be virtual whether you declare them so or not. In other words:

struct A {
   virtual ~A() {}
};

struct B : public A {
   virtual ~B() {}   // this is virtual
};

struct C : public A {
   ~C() {}          // this is virtual too
};

Relative imports for the billionth time

There are too much too long anwers in a foreign language. So I'll try to make it short.

If you write from . import module, opposite to what you think, module will not be imported from current directory, but from the top level of your package! If you run .py file as a script, it simply doesn't know where the top level is and thus refuses to work.

If you start it like this py -m package.module from the directory above package, then python knows where the top level is. That's very similar to java: java -cp bin_directory package.class

react-router (v4) how to go back?

this.props.history.goBack();

This is the correct solution for react-router v4

But one thing you should keep in mind is that you need to make sure this.props.history is existed.

That means you need to call this function this.props.history.goBack(); inside the component that is wrapped by < Route/>

If you call this function in a component that deeper in the component tree, it will not work.

EDIT:

If you want to have history object in the component that is deeper in the component tree (which is not wrapped by < Route>), you can do something like this:

...
import {withRouter} from 'react-router-dom';

class Demo extends Component {
    ...
    // Inside this you can use this.props.history.goBack();
}

export default withRouter(Demo);

Replace all occurrences of a String using StringBuilder?

You could use Pattern/Matcher. From the Matcher javadocs:

 Pattern p = Pattern.compile("cat");
 Matcher m = p.matcher("one cat two cats in the yard");
 StringBuffer sb = new StringBuffer();
 while (m.find()) {
     m.appendReplacement(sb, "dog");
 }
 m.appendTail(sb);
 System.out.println(sb.toString());

Android SDK Manager Not Installing Components

go to sdk folder and right click on SDK manager and run with administrator and enjoy installing.

convert date string to mysql datetime field

Use DateTime::createFromFormat like this :

$date = DateTime::createFromFormat('m/d/Y H:i:s', $input_string.' 00:00:00');
$mysql_date_string = $date->format('Y-m-d H:i:s');

You can adapt this to any input format, whereas strtotime() will assume you're using the US date format if you use /, even if you're not.

The added 00:00:00 is because createFromFormat will use the current date to fill missing data, ie : it will take the current hour:min:sec and not 00:00:00 if you don't precise it.

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

How to change Oracle default data pump directory to import dumpfile?

I want change default directory dumpfile.

You could create a new directory and give it required privileges, for example:

SQL> CREATE DIRECTORY dmpdir AS '/opt/oracle';
Directory created.

SQL> GRANT read, write ON DIRECTORY dmpdir TO scott;
Grant succeeded.

To use the newly created directory, you could just add it as a parameter:

DIRECTORY=dmpdir

Oracle introduced a default directory from 10g R2, called DATA_PUMP_DIR, that can be used. To check the location, you could look into dba_directories:

SQL> select DIRECTORY_NAME, DIRECTORY_PATH from dba_directories where DIRECTORY_NAME = 'DATA_PUMP_DIR';

DIRECTORY_NAME       DIRECTORY_PATH
-------------------- --------------------------------------------------
DATA_PUMP_DIR        C:\app\Lalit/admin/orcl/dpdump/

SQL>

Node.js getaddrinfo ENOTFOUND

I was getting the same error and used below below link to get help:

https://nodejs.org/api/http.html#http_http_request_options_callback

I was not having in my code:

req.end();

(NodeJs V: 5.4.0) once added above req.end(); line, I was able to get rid of the error and worked fine for me.

How do I spool to a CSV formatted file using SQLPLUS?

With newer versions of client tools, there are multiple options to format the query output. The rest is to spool it to a file or save the output as a file depending on the client tool. Here are few of the ways:

  • SQL*Plus

Using the SQL*Plus commands you could format to get your desired output. Use SPOOL to spool the output to a file.

For example,

SQL> SET colsep ,
SQL> SET pagesize 20
SQL> SET trimspool ON
SQL> SET linesize 200
SQL> SELECT * FROM scott.emp;

     EMPNO,ENAME     ,JOB      ,       MGR,HIREDATE ,       SAL,      COMM,    DEPTNO
----------,----------,---------,----------,---------,----------,----------,----------
      7369,SMITH     ,CLERK    ,      7902,17-DEC-80,       800,          ,        20
      7499,ALLEN     ,SALESMAN ,      7698,20-FEB-81,      1600,       300,        30
      7521,WARD      ,SALESMAN ,      7698,22-FEB-81,      1250,       500,        30
      7566,JONES     ,MANAGER  ,      7839,02-APR-81,      2975,          ,        20
      7654,MARTIN    ,SALESMAN ,      7698,28-SEP-81,      1250,      1400,        30
      7698,BLAKE     ,MANAGER  ,      7839,01-MAY-81,      2850,          ,        30
      7782,CLARK     ,MANAGER  ,      7839,09-JUN-81,      2450,          ,        10
      7788,SCOTT     ,ANALYST  ,      7566,09-DEC-82,      3000,          ,        20
      7839,KING      ,PRESIDENT,          ,17-NOV-81,      5000,          ,        10
      7844,TURNER    ,SALESMAN ,      7698,08-SEP-81,      1500,          ,        30
      7876,ADAMS     ,CLERK    ,      7788,12-JAN-83,      1100,          ,        20
      7900,JAMES     ,CLERK    ,      7698,03-DEC-81,       950,          ,        30
      7902,FORD      ,ANALYST  ,      7566,03-DEC-81,      3000,          ,        20
      7934,MILLER    ,CLERK    ,      7782,23-JAN-82,      1300,          ,        10

14 rows selected.

SQL>
  • SQL Developer Version pre 4.1

Alternatively, you could use the new /*csv*/ hint in SQL Developer.

/*csv*/

For example, in my SQL Developer Version 3.2.20.10:

enter image description here

Now you could save the output into a file.

  • SQL Developer Version 4.1

New in SQL Developer version 4.1, use the following just like sqlplus command and run as script. No need of the hint in the query.

SET SQLFORMAT csv

Now you could save the output into a file.

Matlab: Running an m-file from command-line

I think that one important point that was not mentioned in the previous answers is that, if not explicitly indicated, the matlab interpreter will remain open. Therefore, to the answer of @hkBattousai I will add the exit command:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m');exit;"

Run function from the command line

python -c 'from myfile import hello; hello()' where myfile must be replaced with the basename of your Python script. (E.g., myfile.py becomes myfile).

However, if hello() is your "permanent" main entry point in your Python script, then the usual way to do this is as follows:

def hello():
    print "Hi :)"

if __name__ == "__main__":
    hello()

This allows you to execute the script simply by running python myfile.py or python -m myfile.

Some explanation here: __name__ is a special Python variable that holds the name of the module currently being executed, except when the module is started from the command line, in which case it becomes "__main__".

Dynamic SQL - EXEC(@SQL) versus EXEC SP_EXECUTESQL(@SQL)

sp_executesql is more likely to promote query plan reuse. When using sp_executesql, parameters are explicitly identified in the calling signature. This excellent article descibes this process.

The oft cited reference for many aspects of dynamic sql is Erland Sommarskog's must read: "The Curse and Blessings of Dynamic SQL".

Getting "type or namespace name could not be found" but everything seems ok?

I encountered this problem when upgrading existing projects from VS2008 to VS2012. I found that two projects (the only two that I created) were targeting different .Net Frameworks (3.5 and 4.0). I resolved this on the Application tab of the projects by making sure that both projects had ".NET Framework 4" in the Target Framework box.

Is there a way of setting culture for a whole application? All current threads and new threads?

In .NET 4.5, you can use the CultureInfo.DefaultThreadCurrentCulture property to change the culture of an AppDomain.

For versions prior to 4.5 you have to use reflection to manipulate the culture of an AppDomain. There is a private static field on CultureInfo (m_userDefaultCulture in .NET 2.0 mscorlib, s_userDefaultCulture in .NET 4.0 mscorlib) that controls what CurrentCulture returns if a thread has not set that property on itself.

This does not change the native thread locale and it is probably not a good idea to ship code that changes the culture this way. It may be useful for testing though.

To add server using sp_addlinkedserver

I had the same issue to connect an SQL_server 2008 to an SQL_server 2016 hosted in a remote server. @Domnic answer didn't worked for me straightforward. I write my tweaked solution here as I think it may be useful for someone else.

An extended answer for remote IP db connections:

Step 1: Link servers

EXEC sp_addlinkedserver @server='SRV_NAME',
   @srvproduct=N'',
   @provider=N'SQLNCLI',   
   @datasrc=N'aaa.bbb.ccc.ddd';

EXEC sp_addlinkedsrvlogin 'SRV_NAME', 'false', NULL, 'your_remote_db_login_user', 'your_remote_db_login_password'

...where SRV_NAME is an invented name. We will use it to refer to the remote server from our queries. aaa.bbb.ccc.ddd is the ip address of the remote server hosting your SQLserver DB.

Step 2: Run your queries For instance:

SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table

...and that's it!

Syntax details: sp_addlinkedserver and sp_addlinkedsrvlogin

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

You have an error in you script tag construction, this:

<script language="JavaScript" type="text/javascript" script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

Should look like this:

<script language="JavaScript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

You have a 'script' word lost in the middle of your script tag. Also you should remove the http:// to let the browser decide whether to use HTTP or HTTPS.

UPDATE

But your main error is that you are including jQuery UI (ONLY) you must include jQuery first! jQuery UI and jQuery are used together, not in separate. jQuery UI depends on jQuery. You should put this line before jQuery UI:

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

Create patch or diff file from git repository and apply it to another different git repository

To produce patch for several commits, you should use format-patch git command, e.g.

git format-patch -k --stdout R1..R2

This will export your commits into patch file in mailbox format.

To generate patch for the last commit, run:

git format-patch -k --stdout HEAD^

Then in another repository apply the patch by am git command, e.g.

git am -3 -k file.patch

See: man git-format-patch and git-am.

Understanding passport serialize deserialize

  1. Where does user.id go after passport.serializeUser has been called?

The user id (you provide as the second argument of the done function) is saved in the session and is later used to retrieve the whole object via the deserializeUser function.

serializeUser determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user = {}. Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id: 'xyz'}

  1. We are calling passport.deserializeUser right after it where does it fit in the workflow?

The first argument of deserializeUser corresponds to the key of the user object that was given to the done function (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc). In deserializeUser that key is matched with the in memory array / database or any data resource.

The fetched object is attached to the request object as req.user

Visual Flow

passport.serializeUser(function(user, done) {
    done(null, user.id);
});              ¦
                 ¦ 
                 ¦
                 +--------------------? saved to session
                                   ¦    req.session.passport.user = {id: '..'}
                                   ¦
                                   ?           
passport.deserializeUser(function(id, done) {
                   +---------------+
                   ¦
                   ? 
    User.findById(id, function(err, user) {
        done(err, user);
    });            +--------------? user object attaches to the request as req.user   
});

How do I commit only some files?

Suppose you made changes to multiple files, like:

  • File1
  • File2
  • File3
  • File4
  • File5

But you want to commit only changes of File1 and File3.

There are two ways for doing this:

1.Stage only these two files, using:

git add file1 file2

then, commit

git commit -m "your message"

then push,

git push

2.Direct commit

git commit file1 file3 -m "my message"

then push,

git push

Actually first method is useful in case if we are modifying files regularly and staging them --> Large Projects, generally Live projects.
But if we are modifying files and not staging them then we can do direct commit --> Small projects

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Render is

def render(request, *args, **kwargs):
    """ Simple wrapper for render_to_response. """
    kwargs['context_instance'] = RequestContext(request)
    return render_to_response(*args, **kwargs)

So there is really no difference between render_to_response except it wraps your context making the template pre-processors work.

Direct to template is a generic view.

There is really no sense in using it here because there is overhead over render_to_response in the form of view function.

Hosting a Maven repository on github

The best solution I've been able to find consists of these steps:

  1. Create a branch called mvn-repo to host your maven artifacts.
  2. Use the github site-maven-plugin to push your artifacts to github.
  3. Configure maven to use your remote mvn-repo as a maven repository.

There are several benefits to using this approach:

  • Maven artifacts are kept separate from your source in a separate branch called mvn-repo, much like github pages are kept in a separate branch called gh-pages (if you use github pages)
  • Unlike some other proposed solutions, it doesn't conflict with your gh-pages if you're using them.
  • Ties in naturally with the deploy target so there are no new maven commands to learn. Just use mvn deploy as you normally would

The typical way you deploy artifacts to a remote maven repo is to use mvn deploy, so let's patch into that mechanism for this solution.

First, tell maven to deploy artifacts to a temporary staging location inside your target directory. Add this to your pom.xml:

<distributionManagement>
    <repository>
        <id>internal.repo</id>
        <name>Temporary Staging Repository</name>
        <url>file://${project.build.directory}/mvn-repo</url>
    </repository>
</distributionManagement>

<plugins>
    <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.8.1</version>
        <configuration>
            <altDeploymentRepository>internal.repo::default::file://${project.build.directory}/mvn-repo</altDeploymentRepository>
        </configuration>
    </plugin>
</plugins>

Now try running mvn clean deploy. You'll see that it deployed your maven repository to target/mvn-repo. The next step is to get it to upload that directory to GitHub.

Add your authentication information to ~/.m2/settings.xml so that the github site-maven-plugin can push to GitHub:

<!-- NOTE: MAKE SURE THAT settings.xml IS NOT WORLD READABLE! -->
<settings>
  <servers>
    <server>
      <id>github</id>
      <username>YOUR-USERNAME</username>
      <password>YOUR-PASSWORD</password>
    </server>
  </servers>
</settings>

(As noted, please make sure to chmod 700 settings.xml to ensure no one can read your password in the file. If someone knows how to make site-maven-plugin prompt for a password instead of requiring it in a config file, let me know.)

Then tell the GitHub site-maven-plugin about the new server you just configured by adding the following to your pom:

<properties>
    <!-- github server corresponds to entry in ~/.m2/settings.xml -->
    <github.global.server>github</github.global.server>
</properties>

Finally, configure the site-maven-plugin to upload from your temporary staging repo to your mvn-repo branch on Github:

<build>
    <plugins>
        <plugin>
            <groupId>com.github.github</groupId>
            <artifactId>site-maven-plugin</artifactId>
            <version>0.11</version>
            <configuration>
                <message>Maven artifacts for ${project.version}</message>  <!-- git commit message -->
                <noJekyll>true</noJekyll>                                  <!-- disable webpage processing -->
                <outputDirectory>${project.build.directory}/mvn-repo</outputDirectory> <!-- matches distribution management repository url above -->
                <branch>refs/heads/mvn-repo</branch>                       <!-- remote branch name -->
                <includes><include>**/*</include></includes>
                <repositoryName>YOUR-REPOSITORY-NAME</repositoryName>      <!-- github repo name -->
                <repositoryOwner>YOUR-GITHUB-USERNAME</repositoryOwner>    <!-- github username  -->
            </configuration>
            <executions>
              <!-- run site-maven-plugin's 'site' target as part of the build's normal 'deploy' phase -->
              <execution>
                <goals>
                  <goal>site</goal>
                </goals>
                <phase>deploy</phase>
              </execution>
            </executions>
        </plugin>
    </plugins>
</build>

The mvn-repo branch does not need to exist, it will be created for you.

Now run mvn clean deploy again. You should see maven-deploy-plugin "upload" the files to your local staging repository in the target directory, then site-maven-plugin committing those files and pushing them to the server.

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building DaoCore 1.3-SNAPSHOT
[INFO] ------------------------------------------------------------------------
...
[INFO] --- maven-deploy-plugin:2.5:deploy (default-deploy) @ greendao ---
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.jar (77 KB at 2936.9 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.pom (3 KB at 1402.3 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/maven-metadata.xml (768 B at 150.0 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/maven-metadata.xml (282 B at 91.8 KB/sec)
[INFO] 
[INFO] --- site-maven-plugin:0.7:site (default) @ greendao ---
[INFO] Creating 24 blobs
[INFO] Creating tree with 25 blob entries
[INFO] Creating commit with SHA-1: 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] Updating reference refs/heads/mvn-repo from ab7afb9a228bf33d9e04db39d178f96a7a225593 to 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.595s
[INFO] Finished at: Sun Dec 23 11:23:03 MST 2012
[INFO] Final Memory: 9M/81M
[INFO] ------------------------------------------------------------------------

Visit github.com in your browser, select the mvn-repo branch, and verify that all your binaries are now there.

enter image description here

Congratulations!

You can now deploy your maven artifacts to a poor man's public repo simply by running mvn clean deploy.

There's one more step you'll want to take, which is to configure any poms that depend on your pom to know where your repository is. Add the following snippet to any project's pom that depends on your project:

<repositories>
    <repository>
        <id>YOUR-PROJECT-NAME-mvn-repo</id>
        <url>https://github.com/YOUR-USERNAME/YOUR-PROJECT-NAME/raw/mvn-repo/</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </snapshots>
    </repository>
</repositories>

Now any project that requires your jar files will automatically download them from your github maven repository.

Edit: to avoid the problem mentioned in the comments ('Error creating commit: Invalid request. For 'properties/name', nil is not a string.'), make sure you state a name in your profile on github.

How to render a DateTime object in a Twig template

Although you can use the

{{ game.gameDate|date('Y-m-d') }}

approach, keep in mind that this version does not honor the user locale, which should not be a problem with a site used by only users of one nationality. International users should display the game date totally different, like extending the \DateTime class, and adding a __toString() method to it that checks the locale and acts accordingly.

Edit:

As pointed out by @Nic in a comment, if you use the Intl extension of Twig, you will have a localizeddate filter available, which shows the date in the user’s locale. This way you can drop my previous idea of extending \DateTime.

Python recursive folder read

The pathlib library is really great for working with files. You can do a recursive glob on a Path object like so.

from pathlib import Path

for elem in Path('/path/to/my/files').rglob('*.*'):
    print(elem)

Why call git branch --unset-upstream to fixup?

For me, .git/refs/origin/master had got corrupt.

I did the following, which fixed the problem for me.

rm .git/refs/remotes/origin/master
git fetch
git branch --set-upstream-to=origin/master

How to choose between Hudson and Jenkins?

Up front .. I am a Hudson committer and author of the Hudson book, but I was not involved in the whole split of the projects.

In any case here is my advice:

Check out both and see what fits your needs better.

Hudson is going to complete the migration to be a top level Eclipse projects later this year and has gotten a whole bunch of full time developers, QA and others working on the project. It is still going strong and has a lot of users and with being the default CI server at Eclipse it will continue to serve the needs of many Java developers. Looking at the roadmap and plans for the future you can see that after the Maven 3 integration accomplished with the 2.1.0 release a whole bunch of other interesting feature are ahead.

http://www.eclipse.org/hudson

Jenkins on the other side has won over many original Hudson users and has a large user community across multiple technologies and also has a whole bunch of developers working on it.

At this stage both CI servers are great tools to use and depending on your needs in terms of technology to integrate with one or the other might be better. Both products are available as open source and you can get commercial support from various companies for both.

In any case .. if you are not using a CI server yet.. start now with either of them and you will see huge benefits.

Update Jan 2013: After a long process of IP cleanup and further improvements Hudson 3.0 as the first Eclipse foundation approved release is now available.

How do I detach objects in Entity Framework Code First?

If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:

var data = context.MyEntities.AsNoTracking().Where(...).ToList();

As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.

Code to loop through all records in MS Access

Found a good code with comments explaining each statement. Code found at - accessallinone

Sub DAOLooping()
On Error GoTo ErrorHandler

Dim strSQL As String
Dim rs As DAO.Recordset

strSQL = "tblTeachers"
'For the purposes of this post, we are simply going to make 
'strSQL equal to tblTeachers.
'You could use a full SELECT statement such as:
'SELECT * FROM tblTeachers (this would produce the same result in fact).
'You could also add a Where clause to filter which records are returned:
'SELECT * FROM tblTeachers Where ZIPPostal = '98052'
' (this would return 5 records)

Set rs = CurrentDb.OpenRecordset(strSQL)
'This line of code instantiates the recordset object!!! 
'In English, this means that we have opened up a recordset 
'and can access its values using the rs variable.

With rs


    If Not .BOF And Not .EOF Then
    'We don’t know if the recordset has any records, 
    'so we use this line of code to check. If there are no records 
    'we won’t execute any code in the if..end if statement.    

        .MoveLast
        .MoveFirst
        'It is not necessary to move to the last record and then back 
        'to the first one but it is good practice to do so.

        While (Not .EOF)
        'With this code, we are using a while loop to loop 
        'through the records. If we reach the end of the recordset, .EOF 
        'will return true and we will exit the while loop.

            Debug.Print rs.Fields("teacherID") & " " & rs.Fields("FirstName")
            'prints info from fields to the immediate window

            .MoveNext
            'We need to ensure that we use .MoveNext, 
            'otherwise we will be stuck in a loop forever… 
            '(or at least until you press CTRL+Break)
        Wend

    End If

    .close
    'Make sure you close the recordset...
End With

ExitSub:
    Set rs = Nothing
    '..and set it to nothing
    Exit Sub
ErrorHandler:
    Resume ExitSub
End Sub

Recordsets have two important properties when looping through data, EOF (End-Of-File) and BOF (Beginning-Of-File). Recordsets are like tables and when you loop through one, you are literally moving from record to record in sequence. As you move through the records the EOF property is set to false but after you try and go past the last record, the EOF property becomes true. This works the same in reverse for the BOF property.

These properties let us know when we have reached the limits of a recordset.

css3 text-shadow in IE9

As IE9 does not support CSS3 text-shadow, I would just use the filter property for IE instead. Live example: http://jsfiddle.net/dmM2S/

text-shadow:1px 1px 1px red; /* CSS3 */

can be replaced with

filter: Shadow(Color=red, Direction=130, Strength=1); /* IE Proprietary Filter*/

You can get the results to be very similar.

CSS: Force float to do a whole new line

I fixed it by removing float:left, and adding display:inline-block instead. Haven't used it for images, but should work fine, there, too.

How to pass parameters in $ajax POST?

In a POST request, the parameters are sent in the body of the request, that's why you don't see them in the URL.

If you want to see them, change

    type: 'POST',

to

    type: 'GET',

Note that browsers have development tools which lets you see the complete requests that your code issues. In Chrome, it's in the "Network" panel.

How to debug apk signed for release?

I tried with the following and it's worked:

release {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

ORA-01882: timezone region not found

In Netbeans,

  1. Right-click your project -> Properties
  2. Go to Run (under Categories)
  3. Enter -Duser.timezone=UTC or -Duser.timezone=GMT under VM Options.

Click Ok, then re-run your program.

Note: You can as well set to other timestones besides UTC & GMT.

useState set method not reflecting change immediately

Much like setState in Class components created by extending React.Component or React.PureComponent, the state update using the updater provided by useState hook is also asynchronous, and will not be reflected immediately.

Also, the main issue here is not just the asynchronous nature but the fact that state values are used by functions based on their current closures, and state updates will reflect in the next re-render by which the existing closures are not affected, but new ones are created. Now in the current state, the values within hooks are obtained by existing closures, and when a re-render happens, the closures are updated based on whether the function is recreated again or not.

Even if you add a setTimeout the function, though the timeout will run after some time by which the re-render would have happened, the setTimeout will still use the value from its previous closure and not the updated one.

setMovies(result);
console.log(movies) // movies here will not be updated

If you want to perform an action on state update, you need to use the useEffect hook, much like using componentDidUpdate in class components since the setter returned by useState doesn't have a callback pattern

useEffect(() => {
    // action on update of movies
}, [movies]);

As far as the syntax to update state is concerned, setMovies(result) will replace the previous movies value in the state with those available from the async request.

However, if you want to merge the response with the previously existing values, you must use the callback syntax of state updation along with the correct use of spread syntax like

setMovies(prevMovies => ([...prevMovies, ...result]));

Difference between document.addEventListener and window.addEventListener?

The window binding refers to a built-in object provided by the browser. It represents the browser window that contains the document. Calling its addEventListener method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.

<p>Some paragraph.</p>
<script>
  window.addEventListener("click", () => {
    console.log("Test");
  });
</script>

Following points should be noted before select window or document to addEventListners

  1. Most of the events are same for window or document but some events like resize, and other events related to loading, unloading, and opening/closing should all be set on the window.
  2. Since window has the document it is good practice to use document to handle (if it can handle) since event will hit document first.
  3. Internet Explorer doesn't respond to many events registered on the window,so you will need to use document for registering event.

How to run Maven from another directory (without cd to project dir)?

You can use the parameter -f (or --file) and specify the path to your pom file, e.g. mvn -f /path/to/pom.xml

This runs maven "as if" it were in /path/to for the working directory.

Is there an easy way to check the .NET Framework version?

public class DA {
  public static class VersionNetFramework {
    public static string Get45or451FromRegistry()
    {//https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
        using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
        {
            int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release"));
            if (true)
            {
                return (@"Version: " + CheckFor45DotVersion(releaseKey));
            }
        }
    }
    // Checking the version using >= will enable forward compatibility, 
    // however you should always compile your code on newer versions of
    // the framework to ensure your app works the same.
    private static string CheckFor45DotVersion(int releaseKey)
    {//https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
        if (releaseKey >= 394271)
            return "4.6.1 installed on all other Windows OS versions or later";
        if (releaseKey >= 394254)
            return "4.6.1 installed on Windows 10 or later";
        if (releaseKey >= 393297)
            return "4.6 installed on all other Windows OS versions or later";
        if (releaseKey >= 393295)
            return "4.6 installed with Windows 10 or later";
        if (releaseKey >= 379893)
            return "4.5.2 or later";
        if (releaseKey >= 378758)
            return "4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2 or later";
        if (releaseKey >= 378675)
            return "4.5.1 installed with Windows 8.1 or later";
        if (releaseKey >= 378389)
            return "4.5 or later";

        return "No 4.5 or later version detected";
    }
    public static string GetVersionFromRegistry()
    {//https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
        string res = @"";
        // Opens the registry key for the .NET Framework entry.
        using (RegistryKey ndpKey =
            RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "").
            OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
        {
            // As an alternative, if you know the computers you will query are running .NET Framework 4.5 
            // or later, you can use:
            // using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, 
            // RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
            foreach (string versionKeyName in ndpKey.GetSubKeyNames())
            {
                if (versionKeyName.StartsWith("v"))
                {

                    RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
                    string name = (string)versionKey.GetValue("Version", "");
                    string sp = versionKey.GetValue("SP", "").ToString();
                    string install = versionKey.GetValue("Install", "").ToString();
                    if (install == "") //no install info, must be later.
                        res += (versionKeyName + "  " + name) + Environment.NewLine;
                    else
                    {
                        if (sp != "" && install == "1")
                        {
                            res += (versionKeyName + "  " + name + "  SP" + sp) + Environment.NewLine;
                        }

                    }
                    if (name != "")
                    {
                        continue;
                    }
                    foreach (string subKeyName in versionKey.GetSubKeyNames())
                    {
                        RegistryKey subKey = versionKey.OpenSubKey(subKeyName);
                        name = (string)subKey.GetValue("Version", "");
                        if (name != "")
                            sp = subKey.GetValue("SP", "").ToString();
                        install = subKey.GetValue("Install", "").ToString();
                        if (install == "") //no install info, must be later.
                            res += (versionKeyName + "  " + name) + Environment.NewLine;
                        else
                        {
                            if (sp != "" && install == "1")
                            {
                                res += ("  " + subKeyName + "  " + name + "  SP" + sp) + Environment.NewLine;
                            }
                            else if (install == "1")
                            {
                                res += ("  " + subKeyName + "  " + name) + Environment.NewLine;
                            }
                        }
                    }
                }
            }
        }
        return res;
    }
    public static string GetUpdateHistory()
    {//https://msdn.microsoft.com/en-us/library/hh925567(v=vs.110).aspx
        string res=@"";
        using (RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\Updates"))
        {
            foreach (string baseKeyName in baseKey.GetSubKeyNames())
            {
                if (baseKeyName.Contains(".NET Framework") || baseKeyName.StartsWith("KB") || baseKeyName.Contains(".NETFramework"))
                {

                    using (RegistryKey updateKey = baseKey.OpenSubKey(baseKeyName))
                    {
                        string name = (string)updateKey.GetValue("PackageName", "");
                        res += baseKeyName + "  " + name + Environment.NewLine;
                        foreach (string kbKeyName in updateKey.GetSubKeyNames())
                        {
                            using (RegistryKey kbKey = updateKey.OpenSubKey(kbKeyName))
                            {
                                name = (string)kbKey.GetValue("PackageName", "");
                                res += ("  " + kbKeyName + "  " + name) + Environment.NewLine;

                                if (kbKey.SubKeyCount > 0)
                                {
                                    foreach (string sbKeyName in kbKey.GetSubKeyNames())
                                    {
                                        using (RegistryKey sbSubKey = kbKey.OpenSubKey(sbKeyName))
                                        {
                                            name = (string)sbSubKey.GetValue("PackageName", "");
                                            if (name == "")
                                                name = (string)sbSubKey.GetValue("Description", "");
                                            res += ("    " + sbKeyName + "  " + name) + Environment.NewLine;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return res;
    }
}

using class DA.VersionNetFramework

private void Form1_Shown(object sender, EventArgs e)
{
    //
    // Current OS Information
    //
    richTextBox1.Text = @"Current OS Information:";
    richTextBox1.AppendText(Environment.NewLine +
                            "Machine Name: " + Environment.MachineName);
    richTextBox1.AppendText(Environment.NewLine +
                            "Platform: " + Environment.OSVersion.Platform.ToString());
    richTextBox1.AppendText(Environment.NewLine +
                            Environment.OSVersion);
    //
    // .NET Framework Environment Information
    //
    richTextBox1.AppendText(Environment.NewLine + Environment.NewLine +
                                       ".NET Framework Environment Information:");
    richTextBox1.AppendText(Environment.NewLine +
                            "Environment.Version " + Environment.Version);
    richTextBox1.AppendText(Environment.NewLine + 
                            DA.VersionNetFramework.GetVersionDicription());
    //
    // .NET Framework Information From Registry
    //
    richTextBox1.AppendText(Environment.NewLine + Environment.NewLine +
                                       ".NET Framework Information From Registry:");
    richTextBox1.AppendText(Environment.NewLine +
                            DA.VersionNetFramework.GetVersionFromRegistry());
    //
    // .NET Framework 4.5 or later Information From Registry
    //
    richTextBox1.AppendText(Environment.NewLine + 
                                       ".NET Framework 4.5 or later Information From Registry:");
    richTextBox1.AppendText(Environment.NewLine +
                            DA.VersionNetFramework.Get45or451FromRegistry());
    //
    // Update History
    //
    richTextBox1.AppendText(Environment.NewLine + Environment.NewLine +
                            "Update History");
    richTextBox1.AppendText(Environment.NewLine + 
                            DA.VersionNetFramework.GetUpdateHistory());
    //
    // Setting Cursor to first character of textbox
    //
    if (!richTextBox1.Text.Equals(""))
    {
        richTextBox1.SelectionStart = 1;
    }
}

Result:

Current OS Information: Machine Name: D1 Platform: Win32NT Microsoft Windows NT 6.2.9200.0

.NET Framework Environment Information: Environment.Version 4.0.30319.42000 .NET 4.6 on Windows 8.1 64 - bit or later

.NET Framework Information From Registry: v2.0.50727 2.0.50727.4927 SP2 v3.0 3.0.30729.4926 SP2 v3.5 3.5.30729.4926 SP1

v4
Client 4.6.00079 Full 4.6.00079 v4.0
Client 4.0.0.0

.NET Framework 4.5 or later Information From Registry: Version: 4.6 installed with Windows 10 or later

Update History Microsoft .NET Framework 4 Client Profile
KB2468871
KB2468871v2
KB2478063
KB2533523
KB2544514
KB2600211
KB2600217
Microsoft .NET Framework 4 Extended
KB2468871
KB2468871v2
KB2478063
KB2533523
KB2544514
KB2600211
KB2600217
Microsoft .NET Framework 4 Multi-Targeting Pack
KB2504637 Update for (KB2504637)

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

Recursive file search using PowerShell

When searching folders where you might get an error based on security (e.g. C:\Users), use the following command:

Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse -ErrorAction SilentlyContinue -Force

What is the fastest way to send 100,000 HTTP requests in Python?

Threads are absolutely not the answer here. They will provide both process and kernel bottlenecks, as well as throughput limits that are not acceptable if the overall goal is "the fastest way".

A little bit of twisted and its asynchronous HTTP client would give you much better results.

Automating the InvokeRequired code pattern

Here's the form I've been using in all my code.

private void DoGUISwitch()
{ 
    Invoke( ( MethodInvoker ) delegate {
        object1.Visible = true;
        object2.Visible = false;
    });
} 

I've based this on the blog entry here. I have not had this approach fail me, so I see no reason to complicate my code with a check of the InvokeRequired property.

Hope this helps.

How do I read configuration settings from Symfony2 config.yml?

I learnt a easy way from code example of http://tutorial.symblog.co.uk/

1) notice the ZendeskBlueFormBundle and file location

# myproject/app/config/config.yml

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: @ZendeskBlueFormBundle/Resources/config/config.yml }

framework:

2) notice Zendesk_BlueForm.emails.contact_email and file location

# myproject/src/Zendesk/BlueFormBundle/Resources/config/config.yml

parameters:
    # Zendesk contact email address
    Zendesk_BlueForm.emails.contact_email: [email protected]

3) notice how i get it in $client and file location of controller

# myproject/src/Zendesk/BlueFormBundle/Controller/PageController.php

    public function blueFormAction($name, $arg1, $arg2, $arg3, Request $request)
    {
    $client = new ZendeskAPI($this->container->getParameter("Zendesk_BlueForm.emails.contact_email"));
    ...
    }

Carriage Return\Line feed in Java

bw.newLine(); cannot ensure compatibility with all systems.

If you are sure it is going to be opened in windows, you can format it to windows newline.

If you are already using native unix commands, try unix2dos and convert teh already generated file to windows format and then send the mail.

If you are not using unix commands and prefer to do it in java, use ``bw.write("\r\n")` and if it does not complicate your program, have a method that finds out the operating system and writes the appropriate newline.

How to parse JSON with VBA without external libraries?

Call me simple but I just declared a Variant and split the responsetext from my REST GET on the quote comma quote between each item, then got the value I wanted by looking for the last quote with InStrRev. I'm sure that's not as elegant as some of the other suggestions but it works for me.

         varLines = Split(.responsetext, """,""")
        strType = Mid(varLines(8), InStrRev(varLines(8), """") + 1)

How to set the authorization header using curl

Bearer tokens look like this:

curl -H "Authorization: Bearer <ACCESS_TOKEN>" http://www.example.com

What is difference between @RequestBody and @RequestParam?

@RequestParam annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type. This annotation indicates that a method parameter should be bound to a web request parameter.

For example Angular request for Spring RequestParam(s) would look like that:

$http.post('http://localhost:7777/scan/l/register?username="Johny"&password="123123"&auth=true')
      .success(function (data, status, headers, config) {
                        ...
                    })

Endpoint with RequestParam:

@RequestMapping(method = RequestMethod.POST, value = "/register")
public Map<String, String> register(Model uiModel,
                                    @RequestParam String username,
                                    @RequestParam String password,
                                    @RequestParam boolean auth,
                                    HttpServletRequest httpServletRequest) {...

@RequestBody annotated parameters get linked to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters. This annotation indicates a method parameter should be bound to the body of the web request.

For example Angular request for Spring RequestBody would look like that:

$scope.user = {
            username: "foo",
            auth: true,
            password: "bar"
        };    
$http.post('http://localhost:7777/scan/l/register', $scope.user).
                        success(function (data, status, headers, config) {
                            ...
                        })

Endpoint with RequestBody:

@RequestMapping(method = RequestMethod.POST, produces = "application/json", 
                value = "/register")
public Map<String, String> register(Model uiModel,
                                    @RequestBody User user,
                                    HttpServletRequest httpServletRequest) {... 

Hope this helps.

Any way to Invoke a private method?

You can use Manifold's @Jailbreak for direct, type-safe Java reflection:

@Jailbreak Foo foo = new Foo();
foo.callMe();

public class Foo {
    private void callMe();
}

@Jailbreak unlocks the foo local variable in the compiler for direct access to all the members in Foo's hierarchy.

Similarly you can use the jailbreak() extension method for one-off use:

foo.jailbreak().callMe();

Through the jailbreak() method you can access any member in Foo's hierarchy.

In both cases the compiler resolves the method call for you type-safely, as if a public method, while Manifold generates efficient reflection code for you under the hood.

Alternatively, if the type is not known statically, you can use Structural Typing to define an interface a type can satisfy without having to declare its implementation. This strategy maintains type-safety and avoids performance and identity issues associated with reflection and proxy code.

Discover more about Manifold.

How to remove margin space around body or clear default css styles

I had the same problem and my first <p> element which was at the top of the page and also had a browser webkit default margin. This was pushing my entire div down which had the same effect you were talking about so watch out for any text-based elements that are at the very top of the page.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My Website</title>
  </head>
  <body style="margin:0;">
      <div id="image" style="background: url(pixabay-cleaning-kids-720.jpg) 
no-repeat; width: 100%; background-size: 100%;height:100vh">
<p>Text in Paragraph</p>
      </div>
    </div>
  </body>
</html>

So just remember to check all child elements not only the html and body tags.

convert string to char*

There are many ways. Here are at least five:

/*
 * An example of converting std::string to (const)char* using five
 * different methods. Error checking is emitted for simplicity.
 *
 * Compile and run example (using gcc on Unix-like systems):
 *
 *  $ g++ -Wall -pedantic -o test ./test.cpp
 *  $ ./test
 *  Original string (0x7fe3294039f8): hello
 *  s1 (0x7fe3294039f8): hello
 *  s2 (0x7fff5dce3a10): hello
 *  s3 (0x7fe3294000e0): hello
 *  s4 (0x7fe329403a00): hello
 *  s5 (0x7fe329403a10): hello
 */

#include <alloca.h>
#include <string>
#include <cstring>

int main()
{
    std::string s0;
    const char *s1;
    char *s2;
    char *s3;
    char *s4;
    char *s5;

    // This is the initial C++ string.
    s0 = "hello";

    // Method #1: Just use "c_str()" method to obtain a pointer to a
    // null-terminated C string stored in std::string object.
    // Be careful though because when `s0` goes out of scope, s1 points
    // to a non-valid memory.
    s1 = s0.c_str();

    // Method #2: Allocate memory on stack and copy the contents of the
    // original string. Keep in mind that once a current function returns,
    // the memory is invalidated.
    s2 = (char *)alloca(s0.size() + 1);
    memcpy(s2, s0.c_str(), s0.size() + 1);

    // Method #3: Allocate memory dynamically and copy the content of the
    // original string. The memory will be valid until you explicitly
    // release it using "free". Forgetting to release it results in memory
    // leak.
    s3 = (char *)malloc(s0.size() + 1);
    memcpy(s3, s0.c_str(), s0.size() + 1);

    // Method #4: Same as method #3, but using C++ new/delete operators.
    s4 = new char[s0.size() + 1];
    memcpy(s4, s0.c_str(), s0.size() + 1);

    // Method #5: Same as 3 but a bit less efficient..
    s5 = strdup(s0.c_str());

    // Print those strings.
    printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
    printf("s1 (%p): %s\n", s1, s1);
    printf("s2 (%p): %s\n", s2, s2);
    printf("s3 (%p): %s\n", s3, s3);
    printf("s4 (%p): %s\n", s4, s4);
    printf("s5 (%p): %s\n", s5, s5);

    // Release memory...
    free(s3);
    delete [] s4;
    free(s5);
}

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

Unable to execute dex: Multiple dex files define

I have also faced this problem in my project. AVD is not able to reload assets,lib,res and etc folder contexts. problem : Dex Loader] Unable to execute dex: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl.

Then,I created new projects and copied MainActivity.java,activity_main.xml, drawable context. Then delete old project from package explore,restart your Eclipse and AVD. My project is now working properly.... :) I hope this steps will help u little bit folks..!!

How to copy static files to build directory with Webpack?

I was stuck here too. copy-webpack-plugin worked for me.

However, 'copy-webpack-plugin' was not necessary in my case (i learned later).

webpack ignores root paths
example

<img src="/images/logo.png'>

Hence, to make this work without using 'copy-webpack-plugin' use '~' in paths

<img src="~images/logo.png'>

'~' tells webpack to consider 'images' as a module

note: you might have to add the parent directory of images directory in

resolve: {
    modules: [
        'parent-directory of images',
        'node_modules'
    ]
}

Visit https://vuejs-templates.github.io/webpack/static.html

How to activate the Bootstrap modal-backdrop?

Just append a div with that class to body, then remove it when you're done:

// Show the backdrop
$('<div class="modal-backdrop"></div>').appendTo(document.body);

// Remove it (later)
$(".modal-backdrop").remove();

Live Example:

_x000D_
_x000D_
$("input").click(function() {_x000D_
  var bd = $('<div class="modal-backdrop"></div>');_x000D_
  bd.appendTo(document.body);_x000D_
  setTimeout(function() {_x000D_
    bd.remove();_x000D_
  }, 2000);_x000D_
});
_x000D_
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
<script src="//code.jquery.com/jquery.min.js"></script>_x000D_
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
<p>Click the button to get the backdrop for two seconds.</p>_x000D_
<input type="button" value="Click Me">
_x000D_
_x000D_
_x000D_

How to get a list of properties with a given attribute?

The solution I end up using most is based off of Tomas Petricek's answer. I usually want to do something with both the attribute and property.

var props = from p in this.GetType().GetProperties()
            let attr = p.GetCustomAttributes(typeof(MyAttribute), true)
            where attr.Length == 1
            select new { Property = p, Attribute = attr.First() as MyAttribute};

How do you serve a file for download with AngularJS or Javascript?

If you have access to on the server, consider setting headers as answered in this more general question.

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"

Reading the comments on that answer, it is advisable to use a more specific Content-Type than octet-stream.

IntelliJ IDEA JDK configuration on Mac OS

Just tried this recently and when trying to select the JDK... /System/Library/Java/JavaVirtualMachines/ appears as empty when opening&selecting through IntelliJ. Therefore i couldn't select the JDK...

I've found that to workaround this, when the finder windows open (pressing [+] JDK) just use the shortcut Shift + CMD + G to specify the path. (/System/Library/Java/JavaVirtualMachines/1.6.0.jdk in my case)

And voila, IntelliJ can find everything from that point on.

How to generate the JPA entity Metamodel?

Let's assume our application uses the following Post, PostComment, PostDetails, and Tag entities, which form a one-to-many, one-to-one, and many-to-many table relationships:

JPA Criteria Metamodel

How to generate the JPA Criteria Metamodel

The hibernate-jpamodelgen tool provided by Hibernate ORM can be used to scan the project entities and generate the JPA Criteria Metamodel. All you need to do is add the following annotationProcessorPath to the maven-compiler-plugin in the Maven pom.xml configuration file:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>${maven-compiler-plugin.version}</version>
    <configuration>
        <annotationProcessorPaths>
            <annotationProcessorPath>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-jpamodelgen</artifactId>
                <version>${hibernate.version}</version>
            </annotationProcessorPath>
        </annotationProcessorPaths>
    </configuration>
</plugin>

Now, when the project is compiled, you can see that in the target folder, the following Java classes are generated:

> tree target/generated-sources/
target/generated-sources/
+-- annotations
    +-- com
        +-- vladmihalcea
            +-- book
                +-- hpjp
                    +-- hibernate
                        +-- forum
                        ¦   +-- PostComment_.java
                        ¦   +-- PostDetails_.java
                        ¦   +-- Post_.java
                        ¦   +-- Tag_.java

Tag entity Metamodel

If the Tag entity is mapped as follows:

@Entity
@Table(name = "tag")
public class Tag {

    @Id
    private Long id;

    private String name;

    //Getters and setters omitted for brevity
}

The Tag_ Metamodel class is generated like this:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Tag.class)
public abstract class Tag_ {

    public static volatile SingularAttribute<Tag, String> name;
    public static volatile SingularAttribute<Tag, Long> id;

    public static final String NAME = "name";
    public static final String ID = "id";
}

The SingularAttribute is used for the basic id and name Tag JPA entity attributes.

Post entity Metamodel

The Post entity is mapped like this:

@Entity
@Table(name = "post")
public class Post {

    @Id
    private Long id;

    private String title;

    @OneToMany(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();

    @OneToOne(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        fetch = FetchType.LAZY
    )
    @LazyToOne(LazyToOneOption.NO_PROXY)
    private PostDetails details;

    @ManyToMany
    @JoinTable(
        name = "post_tag",
        joinColumns = @JoinColumn(name = "post_id"),
        inverseJoinColumns = @JoinColumn(name = "tag_id")
    )
    private List<Tag> tags = new ArrayList<>();
    
    //Getters and setters omitted for brevity
}

The Post entity has two basic attributes, id and title, a one-to-many comments collection, a one-to-one details association, and a many-to-many tags collection.

The Post_ Metamodel class is generated as follows:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Post.class)
public abstract class Post_ {

    public static volatile ListAttribute<Post, PostComment> comments;
    public static volatile SingularAttribute<Post, PostDetails> details;
    public static volatile SingularAttribute<Post, Long> id;
    public static volatile SingularAttribute<Post, String> title;
    public static volatile ListAttribute<Post, Tag> tags;

    public static final String COMMENTS = "comments";
    public static final String DETAILS = "details";
    public static final String ID = "id";
    public static final String TITLE = "title";
    public static final String TAGS = "tags";
}

The basic id and title attributes, as well as the one-to-one details association, are represented by a SingularAttribute while the comments and tags collections are represented by the JPA ListAttribute.

PostDetails entity Metamodel

The PostDetails entity is mapped like this:

@Entity
@Table(name = "post_details")
public class PostDetails {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "created_on")
    private Date createdOn;

    @Column(name = "created_by")
    private String createdBy;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    @JoinColumn(name = "id")
    private Post post;
    
    //Getters and setters omitted for brevity
}

All entity attributes are going to be represented by the JPA SingularAttribute in the associated PostDetails_ Metamodel class:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(PostDetails.class)
public abstract class PostDetails_ {

    public static volatile SingularAttribute<PostDetails, Post> post;
    public static volatile SingularAttribute<PostDetails, String> createdBy;
    public static volatile SingularAttribute<PostDetails, Long> id;
    public static volatile SingularAttribute<PostDetails, Date> createdOn;

    public static final String POST = "post";
    public static final String CREATED_BY = "createdBy";
    public static final String ID = "id";
    public static final String CREATED_ON = "createdOn";
}

PostComment entity Metamodel

The PostComment is mapped as follows:

@Entity
@Table(name = "post_comment")
public class PostComment {

    @Id
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private Post post;

    private String review;
    
    //Getters and setters omitted for brevity
}

And, all entity attributes are represented by the JPA SingularAttribute in the associated PostComments_ Metamodel class:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(PostComment.class)
public abstract class PostComment_ {

    public static volatile SingularAttribute<PostComment, Post> post;
    public static volatile SingularAttribute<PostComment, String> review;
    public static volatile SingularAttribute<PostComment, Long> id;

    public static final String POST = "post";
    public static final String REVIEW = "review";
    public static final String ID = "id";
}

Using the JPA Criteria Metamodel

Without the JPA Metamodel, a Criteria API query that needs to fetch the PostComment entities filtered by their associated Post title would look like this:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<PostComment> query = builder.createQuery(PostComment.class);
Root<PostComment> postComment = query.from(PostComment.class);

Join<PostComment, Post> post = postComment.join("post");

query.where(
    builder.equal(
        post.get("title"),
        "High-Performance Java Persistence"
    )
);

List<PostComment> comments = entityManager
    .createQuery(query)
    .getResultList();

Notice that we used the post String literal when creating the Join instance, and we used the title String literal when referencing the Post title.

The JPA Metamodel allows us to avoid hard-coding entity attributes, as illustrated by the following example:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<PostComment> query = builder.createQuery(PostComment.class);
Root<PostComment> postComment = query.from(PostComment.class);

Join<PostComment, Post> post = postComment.join(PostComment_.post);

query.where(
    builder.equal(
        post.get(Post_.title),
        "High-Performance Java Persistence"
    )
);

List<PostComment> comments = entityManager
    .createQuery(query)
    .getResultList();

Or, let's say we want to fetch a DTO projection while filtering the Post title and the PostDetails createdOn attributes.

We can use the Metamodel when creating the join attributes, as well as when building the DTO projection column aliases or when referencing the entity attributes we need to filter:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);

Root<PostComment> postComment = query.from(PostComment.class);
Join<PostComment, Post> post = postComment.join(PostComment_.post);

query.multiselect(
    postComment.get(PostComment_.id).alias(PostComment_.ID),
    postComment.get(PostComment_.review).alias(PostComment_.REVIEW),
    post.get(Post_.title).alias(Post_.TITLE)
);

query.where(
    builder.and(
        builder.like(
            post.get(Post_.title),
            "%Java Persistence%"
        ),
        builder.equal(
            post.get(Post_.details).get(PostDetails_.CREATED_BY),
            "Vlad Mihalcea"
        )
    )
);

List<PostCommentSummary> comments = entityManager
    .createQuery(query)
    .unwrap(Query.class)
    .setResultTransformer(Transformers.aliasToBean(PostCommentSummary.class))
    .getResultList();

Cool, right?

How to add a custom button to the toolbar that calls a JavaScript function?

There might be Several plugins but one may use CSS for creating button. First of all click on Source button mentioned in Editor then paste the button code over there, As I use CSS to create button and added href to it.

<p dir="ltr" style="text-align:center"><a href="https://play.google.com/store/apps/details?id=com.mobicom.mobiune&hl=en" style="background-color:#0080ff; border: none;color: white;padding: 6px 20px;text-align: center;text-decoration: none;display: inline-block;border-radius: 8px;font-size: 15px; font-weight: bold;">Open App</a></p>

This is the Button Written Open App over It. You May change the Color as i am using #0080ff (Light Blue)

how to run a command at terminal from java program?

You don't actually need to run a command from an xterm session, you can run it directly:

String[] arguments = new String[] {"/path/to/executable", "arg0", "arg1", "etc"};
Process proc = new ProcessBuilder(arguments).start();

If the process responds interactively to the input stream, and you want to inject values, then do what you did before:

OutputStream out = proc.getOutputStream();  
out.write("command\n");  
out.flush();

Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.

Android 6.0 Marshmallow. Cannot write to SD Card

I faced the same problem. There are two types of permissions in Android:

  • Dangerous (access to contacts, write to external storage...)
  • Normal

Normal permissions are automatically approved by Android while dangerous permissions need to be approved by Android users.

Here is the strategy to get dangerous permissions in Android 6.0

  1. Check if you have the permission granted
  2. If your app is already granted the permission, go ahead and perform normally.
  3. If your app doesn't have the permission yet, ask for user to approve
  4. Listen to user approval in onRequestPermissionsResult

Here is my case: I need to write to external storage.

First, I check if I have the permission:

...
private static final int REQUEST_WRITE_STORAGE = 112;
...
boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
    ActivityCompat.requestPermissions(parentActivity,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                REQUEST_WRITE_STORAGE);
}

Then check the user's approval:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case REQUEST_WRITE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                //reload my activity with permission granted or use the features what required the permission
            } else
            {
                Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
            }
        }
    }

}

You can read more about the new permission model here: https://developer.android.com/training/permissions/requesting.html

handling DATETIME values 0000-00-00 00:00:00 in JDBC

DATE_FORMAT(column name, '%Y-%m-%d %T') as dtime

Use this to avoid the error. It return the date in string format and then you can get it as a string.

resultset.getString("dtime");

This actually does NOT work. Even though you call getString. Internally mysql still tries to convert it to date first.

at com.mysql.jdbc.ResultSetImpl.getDateFromString(ResultSetImpl.java:2270)

~[mysql-connector-java-5.1.15.jar:na] at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5743)

~[mysql-connector-java-5.1.15.jar:na] at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5576)

~[mysql-connector-java-5.1.15.jar:na]

Saving a text file on server using JavaScript

You must have a server-side script to handle your request, it can't be done using javascript.

To send raw data without URIencoding or escaping special characters to the php and save it as new txt file you can send ajax request using post method and FormData like:

JS:

var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);

PHP:

if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";//generates random name

$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}

Edit:

As Florian mentioned below, the XHR fallback is not required since FormData is not supported in older browsers (formdata browser compatibiltiy), so you can declare XHR variable as:

var xhr = new XMLHttpRequest();

Also please note that this works only for browsers that support FormData such as IE +10.

How to convert a GUID to a string in C#?

Guid guidId = Guid.Parse("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
string guidValue = guidId.ToString("D"); //return with hyphens

How to convert a Kotlin source file to a Java source file

I compile Kotlin to byte code and then de-compile that to Java. I compile with the Kotlin compiler and de-compile with cfr.

My project is here.

This allows me to compile this:

package functionsiiiandiiilambdas.functions.p01tailiiirecursive

tailrec fun findFixPoint(x: Double = 1.0): Double =
        if (x == Math.cos(x)) x else findFixPoint(Math.cos(x))

To this:

package functionsiiiandiiilambdas.functions.p01tailiiirecursive;

public final class ExampleKt {
  public static final double findFixPoint(double x) {
    while (x != Math.cos(x)) {
      x = Math.cos(x);
    }
    return x;
  }

  public static /* bridge */ /* synthetic */ double findFixPoint$default(
      double d, int n, Object object) {
    if ((n & 1) != 0) {
      d = 1.0;
    }
    return ExampleKt.findFixPoint(d);
  }
}

@Cacheable key on multiple method arguments

Use this

@Cacheable(value="bookCache", key="#isbn + '_' + #checkWarehouse + '_' + #includeUsed")

Check substring exists in a string in C

Using C - No built in functions

string_contains() does all the heavy lifting and returns 1 based index. Rest are driver and helper codes.

Assign a pointer to the main string and the substring, increment substring pointer when matching, stop looping when substring pointer is equal to substring length.

read_line() - A little bonus code for reading the user input without predefining the size of input user should provide.

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

int string_len(char * string){
  int len = 0;
  while(*string!='\0'){
    len++;
    string++;
  }
  return len;
}

int string_contains(char *string, char *substring){
  int start_index = 0;
  int string_index=0, substring_index=0;
  int substring_len =string_len(substring);
  int s_len = string_len(string);
  while(substring_index<substring_len && string_index<s_len){
    if(*(string+string_index)==*(substring+substring_index)){
      substring_index++;
    }
    string_index++;
    if(substring_index==substring_len){
      return string_index-substring_len+1;
    }
  }

  return 0;

}

#define INPUT_BUFFER 64
char *read_line(){
  int buffer_len = INPUT_BUFFER;
  char *input = malloc(buffer_len*sizeof(char));
  int c, count=0;

  while(1){
    c = getchar();

    if(c==EOF||c=='\n'){
      input[count]='\0';
      return input;
    }else{
      input[count]=c;
      count++;
    }

    if(count==buffer_len){
      buffer_len+=INPUT_BUFFER;
      input = realloc(input, buffer_len*sizeof(char));
    }

  }
}

int main(void) {
  while(1){
    printf("\nEnter the string: ");
    char *string = read_line();
    printf("Enter the sub-string: ");
    char *substring = read_line(); 
    int position = string_contains(string,substring);
    if(position){ 
      printf("Found at position: %d\n", position);
    }else{
      printf("Not Found\n");
    }
  }
  return 0;
}

How do I compare two hashes?

How about another, simpler approach:

require 'fileutils'
FileUtils.cmp(file1, file2)

C# : assign data to properties via constructor vs. instantiating

Object initializers are cool because they allow you to set up a class inline. The tradeoff is that your class cannot be immutable. Consider:

public class Album 
{
    // Note that we make the setter 'private'
    public string Name { get; private set; }
    public string Artist { get; private set; }
    public int Year { get; private set; }

    public Album(string name, string artist, int year)
    {
        this.Name = name;
        this.Artist = artist;
        this.Year = year;
    }
}

If the class is defined this way, it means that there isn't really an easy way to modify the contents of the class after it has been constructed. Immutability has benefits. When something is immutable, it is MUCH easier to determine that it's correct. After all, if it can't be modified after construction, then there is no way for it to ever be 'wrong' (once you've determined that it's structure is correct). When you create anonymous classes, such as:

new { 
    Name = "Some Name",
    Artist = "Some Artist",
    Year = 1994
};

the compiler will automatically create an immutable class (that is, anonymous classes cannot be modified after construction), because immutability is just that useful. Most C++/Java style guides often encourage making members const(C++) or final (Java) for just this reason. Bigger applications are just much easier to verify when there are fewer moving parts.

That all being said, there are situations when you want to be able quickly modify the structure of your class. Let's say I have a tool that I want to set up:

public void Configure(ConfigurationSetup setup);

and I have a class that has a number of members such as:

class ConfigurationSetup {
    public String Name { get; set; }
    public String Location { get; set; }
    public Int32 Size { get; set; }
    public DateTime Time { get; set; }

    // ... and some other configuration stuff... 
}

Using object initializer syntax is useful when I want to configure some combination of properties, but not neccesarily all of them at once. For example if I just want to configure the Name and Location, I can just do:

ConfigurationSetup setup = new ConfigurationSetup {
    Name = "Some Name",
    Location = "San Jose"
};

and this allows me to set up some combination without having to define a new constructor for every possibly permutation.

On the whole, I would argue that making your classes immutable will save you a great deal of development time in the long run, but having object initializer syntax makes setting up certain configuration permutations much easier.

How can I tell if a Java integer is null?

parseInt() is just going to throw an exception if the parsing can't complete successfully. You can instead use Integers, the corresponding object type, which makes things a little bit cleaner. So you probably want something closer to:

Integer s = null;

try { 
  s = Integer.valueOf(startField.getText());
}
catch (NumberFormatException e) {
  // ...
}

if (s != null) { ... }

Beware if you do decide to use parseInt()! parseInt() doesn't support good internationalization, so you have to jump through even more hoops:

try {
    NumberFormat nf = NumberFormat.getIntegerInstance(locale);
    nf.setParseIntegerOnly(true);
    nf.setMaximumIntegerDigits(9); // Or whatever you'd like to max out at.

    // Start parsing from the beginning.
    ParsePosition p = new ParsePosition(0);

    int val = format.parse(str, p).intValue();
    if (p.getIndex() != str.length()) {
        // There's some stuff after all the digits are done being processed.
    }

    // Work with the processed value here.
} catch (java.text.ParseFormatException exc) {
    // Something blew up in the parsing.
}

Checkout multiple git repos into same Jenkins workspace

We are using git-repo to manage our multiple GIT repositories. There is also a Jenkins Repo plugin that allows to checkout all or part of the repositories managed by git-repo to the same Jenkins job workspace.

How to load a xib file in a UIView

For swift 3 & 4

let customView = Bundle.main.loadNibNamed("CustomView", owner: nil, options: nil)?.first as? CustomView

What is the purpose of global.asax in asp.net

The Global.asax can be used to handle events arising from the application. This link provides a good explanation: http://aspalliance.com/1114

How to run DOS/CMD/Command Prompt commands from VB.NET?

I was inspired by Steve's answer but thought I'd add a bit of flare to it. I like to do the work up front of writing extension methods so later I have less work to do calling the method.

For example with the modified version of Steve's answer below, instead of making this call...

MyUtilities.RunCommandCom("DIR", "/W", true)

I can actually just type out the command and call it from my strings like this...

Directly in code.

Call "CD %APPDATA% & TREE".RunCMD()

OR

From a variable.

Dim MyCommand = "CD %APPDATA% & TREE"
MyCommand.RunCMD()

OR

From a textbox.

textbox.text.RunCMD(WaitForProcessComplete:=True)


Extension methods will need to be placed in a Public Module and carry the <Extension> attribute over the sub. You will also want to add Imports System.Runtime.CompilerServices to the top of your code file.

There's plenty of info on SO about Extension Methods if you need further help.


Extension Method

Public Module Extensions
''' <summary>
''' Extension method to run string as CMD command.
''' </summary>
''' <param name="command">[String] Command to run.</param>
''' <param name="ShowWindow">[Boolean](Default:False) Option to show CMD window.</param>
''' <param name="WaitForProcessComplete">[Boolean](Default:False) Option to wait for CMD process to complete before exiting sub.</param>
''' <param name="permanent">[Boolean](Default:False) Option to keep window visible after command has finished. Ignored if ShowWindow is False.</param>
<Extension>
Public Sub RunCMD(command As String, Optional ShowWindow As Boolean = False, Optional WaitForProcessComplete As Boolean = False, Optional permanent As Boolean = False)
    Dim p As Process = New Process()
    Dim pi As ProcessStartInfo = New ProcessStartInfo()
    pi.Arguments = " " + If(ShowWindow AndAlso permanent, "/K", "/C") + " " + command
    pi.FileName = "cmd.exe"
    pi.CreateNoWindow = Not ShowWindow
    If ShowWindow Then
        pi.WindowStyle = ProcessWindowStyle.Normal
    Else
        pi.WindowStyle = ProcessWindowStyle.Hidden
    End If
    p.StartInfo = pi
    p.Start()
    If WaitForProcessComplete Then Do Until p.HasExited : Loop
End Sub
End Module

Error:Unable to locate adb within SDK in Android Studio

My Android Studio version 3.6.1

After getting updated the latest version I have been facing this problem for few hours. My steps to solve this:

-> Updated sdk platform-tools [though it's not fetching my device yet]

-> Change the USB cable, then my 2 devices both are getting connected with Studio and run my app successfully.

I don't know this silly step might help anyone but U can have a look on that. I just share my experience, Thanks.

How should I call 3 functions in order to execute them one after the other?

You could also use promises in this way:

    some_3secs_function(this.some_value).then(function(){
       some_5secs_function(this.some_other_value).then(function(){
          some_8secs_function(this.some_other_other_value);
       });
    });

You would have to make some_value global in order to access it from inside the .then

Alternatively, from the outer function you could return the value the inner function would use, like so:

    one(some_value).then(function(return_of_one){
       two(return_of_one).then(function(return_of_two){
          three(return_of_two);
       });
    });

ES6 Update

Since async/await is widely available now, this is the way to accomplish the same:

async function run(){    
    await $('#art1').animate({'width':'1000px'},1000,'linear').promise()
    await $('#art2').animate({'width':'1000px'},1000,'linear').promise()
    await $('#art3').animate({'width':'1000px'},1000,'linear').promise()
}

Which is basically "promisifying" your functions (if they're not already asynchronous), and then awaiting them

OpenCV - Apply mask to a color image

The other methods described assume a binary mask. If you want to use a real-valued single-channel grayscale image as a mask (e.g. from an alpha channel), you can expand it to three channels and then use it for interpolation:

assert len(mask.shape) == 2 and issubclass(mask.dtype.type, np.floating)
assert len(foreground_rgb.shape) == 3
assert len(background_rgb.shape) == 3

alpha3 = np.stack([mask]*3, axis=2)
blended = alpha3 * foreground_rgb + (1. - alpha3) * background_rgb

Note that mask needs to be in range 0..1 for the operation to succeed. It is also assumed that 1.0 encodes keeping the foreground only, while 0.0 means keeping only the background.

If the mask may have the shape (h, w, 1), this helps:

alpha3 = np.squeeze(np.stack([np.atleast_3d(mask)]*3, axis=2))

Here np.atleast_3d(mask) makes the mask (h, w, 1) if it is (h, w) and np.squeeze(...) reshapes the result from (h, w, 3, 1) to (h, w, 3).

Can't change z-index with JQuery

That's invalid Javascript syntax; a property name cannot have a -.

Use either zIndex or "z-index".

How can I split this comma-delimited string in Python?

Question is a little vague.

list_of_lines = multiple_lines.split("\n")
for line in list_of_lines:
    list_of_items_in_line = line.split(",")
    first_int = int(list_of_items_in_line[0])

etc.

What is the difference between String and StringBuffer in Java?

I found interest answer for compare performance String vs StringBuffer by Reggie Hutcherso Source: http://www.javaworld.com/javaworld/jw-03-2000/jw-0324-javaperf.html

Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.

The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Using the String class, concatenations are typically performed as follows:

 String str = new String ("Stanford  ");
 str += "Lost!!";

If you were to use StringBuffer to perform the same concatenation, you would need code that looks like this:

 StringBuffer str = new StringBuffer ("Stanford ");
 str.append("Lost!!");

Developers usually assume that the first example above is more efficient because they think that the second example, which uses the append method for concatenation, is more costly than the first example, which uses the + operator to concatenate two String objects.

The + operator appears innocent, but the code generated produces some surprises. Using a StringBuffer for concatenation can in fact produce code that is significantly faster than using a String. To discover why this is the case, we must examine the generated bytecode from our two examples. The bytecode for the example using String looks like this:

0 new #7 <Class java.lang.String>
3 dup 
4 ldc #2 <String "Stanford ">
6 invokespecial #12 <Method java.lang.String(java.lang.String)>
9 astore_1
10 new #8 <Class java.lang.StringBuffer>
13 dup
14 aload_1
15 invokestatic #23 <Method java.lang.String valueOf(java.lang.Object)>
18 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)>
21 ldc #1 <String "Lost!!">
23 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)>
26 invokevirtual #22 <Method java.lang.String toString()>
29 astore_1

The bytecode at locations 0 through 9 is executed for the first line of code, namely:

 String str = new String("Stanford ");

Then, the bytecode at location 10 through 29 is executed for the concatenation:

 str += "Lost!!";

Things get interesting here. The bytecode generated for the concatenation creates a StringBuffer object, then invokes its append method: the temporary StringBuffer object is created at location 10, and its append method is called at location 23. Because the String class is immutable, a StringBuffer must be used for concatenation.

After the concatenation is performed on the StringBuffer object, it must be converted back into a String. This is done with the call to the toString method at location 26. This method creates a new String object from the temporary StringBuffer object. The creation of this temporary StringBuffer object and its subsequent conversion back into a String object are very expensive.

In summary, the two lines of code above result in the creation of three objects:

  1. A String object at location 0
  2. A StringBuffer object at location 10
  3. A String object at location 26

Now, let's look at the bytecode generated for the example using StringBuffer:

0 new #8 <Class java.lang.StringBuffer>
3 dup
4 ldc #2 <String "Stanford ">
6 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)>
9 astore_1
10 aload_1 
11 ldc #1 <String "Lost!!">
13 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)>
16 pop

The bytecode at locations 0 to 9 is executed for the first line of code:

 StringBuffer str = new StringBuffer("Stanford ");

The bytecode at location 10 to 16 is then executed for the concatenation:

 str.append("Lost!!");

Notice that, as is the case in the first example, this code invokes the append method of a StringBuffer object. Unlike the first example, however, there is no need to create a temporary StringBuffer and then convert it into a String object. This code creates only one object, the StringBuffer, at location 0.

In conclusion, StringBuffer concatenation is significantly faster than String concatenation. Obviously, StringBuffers should be used in this type of operation when possible. If the functionality of the String class is desired, consider using a StringBuffer for concatenation and then performing one conversion to String.

How to install python developer package?

yum install python-devel will work.

If yum doesn't work then use

apt-get install python-dev

How to combine GROUP BY, ORDER BY and HAVING

Your code should be contain WHILE before group by and having :

SELECT Email, COUNT(*)

FROM user_log

WHILE Email IS NOT NULL

GROUP BY Email

HAVING COUNT(*) > 1

ORDER BY UpdateDate DESC

SOAP Action WSDL

I have come across exactly the same problem when trying to write a client for the National Rail SOAP service with Perl.

The problem was caused because the Perl module that I'm using 'SOAP::Lite' inserts a '#' in the SOAPAction header ...

SOAPAction: "http://thalesgroup.com/RTTI/2008-02-20/ldb/#GetDepartureBoard"

This is not interpreted correctly by .NET servers. I found this out from Example 3-19 in O'Reilly's Programming Web Services with SOAP . The solution was given below in section 3-20, namely you need to explicitly specify the format of the header with the 'on_action' method.

print SOAP::Lite
  -> uri('urn:Example1')
  -> on_action(sub{sprintf '%s/%s', @_ })
  -> proxy('http://localhost:8080/helloworld/example1.asmx')
  -> sayHello($name)
  -> result . "\n\n";

My guess is that soapclient.com is using SOAP::Lite behind the scenes and so are hitting the same problem when talking to National Rail.

The solution is to write your own client so that you have control over the format of the SOAPAction header ... but you've probably done that already.

How can I debug a Perl script?

If you want to do remote debugging (for CGI or if you don't want to mess output with debug command line), use this:

Given test:

use v5.14;
say 1;
say 2;
say 3;

Start a listener on whatever host and port on terminal 1 (here localhost:12345):

$ nc -v -l localhost -p 12345

For readline support use rlwrap (you can use on perl -d too):

$ rlwrap nc -v -l localhost -p 12345

And start the test on another terminal (say terminal 2):

$ PERLDB_OPTS="RemotePort=localhost:12345" perl -d test

Input/Output on terminal 1:

Connection from 127.0.0.1:42994

Loading DB routines from perl5db.pl version 1.49
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(test:2):    say 1;
  DB<1> n
main::(test:3):    say 2;
  DB<1> select $DB::OUT

  DB<2> n
2
main::(test:4):    say 3;
  DB<2> n
3
Debugged program terminated.  Use q to quit or R to restart,
use o inhibit_exit to avoid stopping after program termination,
h q, h R or h o to get additional info.
  DB<2>

Output on terminal 2:

1

Note the sentence if you want output on debug terminal

select $DB::OUT

If you are Vim user, install this plugin: dbg.vim which provides basic support for Perl.

Create a date from day month and year with T-SQL

Sql Server 2012 has a function that will create the date based on the parts (DATEFROMPARTS). For the rest of us, here is a db function I created that will determine the date from the parts (thanks @Charles)...

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[func_DateFromParts]'))
    DROP FUNCTION [dbo].[func_DateFromParts]
GO

CREATE FUNCTION [dbo].[func_DateFromParts]
(
    @Year INT,
    @Month INT,
    @DayOfMonth INT,
    @Hour INT = 0,  -- based on 24 hour clock (add 12 for PM :)
    @Min INT = 0,
    @Sec INT = 0
)
RETURNS DATETIME
AS
BEGIN

    RETURN DATEADD(second, @Sec, 
            DATEADD(minute, @Min, 
            DATEADD(hour, @Hour,
            DATEADD(day, @DayOfMonth - 1, 
            DATEADD(month, @Month - 1, 
            DATEADD(Year, @Year-1900, 0))))))

END

GO

You can call it like this...

SELECT dbo.func_DateFromParts(2013, 10, 4, 15, 50, DEFAULT)

Returns...

2013-10-04 15:50:00.000

How to change a string into uppercase

s = 'sdsd'
print (s.upper())
upper = raw_input('type in something lowercase.')
lower = raw_input('type in the same thing caps lock.')
print upper.upper()
print lower.lower()

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Port 80

What I do on my cloud instances is I redirect port 80 to port 3000 with this command:

sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000

Then I launch my Node.js on port 3000. Requests to port 80 will get mapped to port 3000.

You should also edit your /etc/rc.local file and add that line minus the sudo. That will add the redirect when the machine boots up. You don't need sudo in /etc/rc.local because the commands there are run as root when the system boots.

Logs

Use the forever module to launch your Node.js with. It will make sure that it restarts if it ever crashes and it will redirect console logs to a file.

Launch on Boot

Add your Node.js start script to the file you edited for port redirection, /etc/rc.local. That will run your Node.js launch script when the system starts.

Digital Ocean & other VPS

This not only applies to Linode, but Digital Ocean, AWS EC2 and other VPS providers as well. However, on RedHat based systems /etc/rc.local is /ect/rc.d/local.

How do I remove all non-ASCII characters with regex and Notepad++?

Click on View/Show Symbol/Show All Character - to show the [SOH] characters in the file Click on the [SOH] symbol in the file CTRL=H to bring up the replace Leave the 'Find What:' as is Change the 'Replace with:' to the character of your choosing (comma,semicolon, other...) Click 'Replace All' Done and done!

Mysql adding user for remote access

An alternative way is to use MySql Workbench. Go to Administration -> Users and privileges -> and change 'localhost' with '%' in 'Limit to Host Matching' (From host) attribute for users you wont to give remote access Or create new user ( Add account button ) with '%' on this attribute instead localhost.

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

I have tried all suggestions and found my own simple solution.

The problem is that codes written in external environment like C need compiler. Look for its own VS environment, i.e. VS 2008.

Currently my machine runs VS 2012 and faces Unable to find vcvarsall.bat. I studied codes that i want to install to find the VS version. It was VS 2008. i have add to system variable VS90COMNTOOLS as variable name and gave the value of VS120COMNTOOLS.

You can find my step by step solution below:

  1. Right click on My Computer.
  2. Click Properties
  3. Advanced system settings
  4. Environment variables
  5. Add New system variable
  6. Enter VS90COMNTOOLS to the variable name
  7. Enter the value of current version to the new variable.
  8. Close all windows

Now open a new session and pip install your-package

Is there a way to comment out markup in an .ASPX page?

Yes, there are special server side comments:

<%-- Text not sent to client  --%>

Check for false

Checking if something isn't false... So it's true, just if you're doing something that is quantum physics.

if(!(borrar() === false))

or

if(borrar() === true)

Rubymine: How to make Git ignore .idea files created by Rubymine

I tried to added those files into my .gitignore and it was useless...

Nevertheless, as Petr Syrov said, you can use git rm -r --cached .idea into your terminal and those files won't be a problem anymore!

RecyclerView: Inconsistency detected. Invalid item position

It also can be related with setting the adapter multiple times at the same time. I had a callback method which was triggered 5-6 times at the same time and I was setting the adapter in that callback so RecycledViewPool couldn't handle with all of those datas contemporaneously. It's a fat chance but you better check it out anyway.

Where does VBA Debug.Print log to?

Where do you want to see the output?

Messages being output via Debug.Print will be displayed in the immediate window which you can open by pressing Ctrl+G.

You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar

enter image description here

What is the difference between DAO and Repository patterns?

in a very simple sentence: The significant difference being that Repositories represent collections, whilst DAOs are closer to the database, often being far more table-centric.

Add Auto-Increment ID to existing table?

Check for already existing primary key with different column. If yes, drop the primary key using:

ALTER TABLE Table1
DROP CONSTRAINT PK_Table1_Col1
GO

and then write your query as it is.

OSX -bash: composer: command not found

On Mac OS X, for anyone having:

-bash: /usr/local/bin/composer: Permission denied

problem, while trying to move downloaded composer.phar using:

mv composer.phar /usr/local/bin/composer

this is the cause:

System Integrity Protection

and this is the solution:

  1. Reboot in recovery mode: restart you mac and hold down cmd+R.
  2. Open the terminal once recovery mode has started via Utilities>Terminal via the bar at the top.
  3. Type in csrutil disable and hit enter. You should see a msg returned saying that:

    the System Integrity Protection is off.

  4. Restart the computer as normal and then go set up composer. I had to put it in /usr/bin and NOT /usr/local/bin because for some reason it just didn't work there.
  5. Go back to recovery mode and enable System Integrity Protector by typing csrutil enable
  6. Come back in normal boot up and check that composer works. It did for me.

The above 6 steps are copied from here, so all the credit belongs to the user Vasheer there.

cast a List to a Collection

Not knowing your code, it's a bit hard to answer your question, but based on all the info here, I believe the issue is you're trying to use Collections.sort passing in an object defined as Collection, and sort doesn't support that.

First question. Why is client defined so generically? Why isn't it a List, Map, Set or something a little more specific?

If client was defined as a List, Map or Set, you wouldn't have this issue, as then you'd be able to directly use Collections.sort(client).

HTH

Specifying and saving a figure with exact size in pixels

Comparison of different approaches

Here is a quick comparison of some of the approaches I've tried with images showing what the give.

Baseline example without trying to set the image dimensions

Just to have a comparison point:

base.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

fig, ax = plt.subplots()
print('fig.dpi = {}'.format(fig.dpi))
print('fig.get_size_inches() = ' + str(fig.get_size_inches())
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig('base.png', format='png')

run:

./base.py
identify base.png

outputs:

fig.dpi = 100.0
fig.get_size_inches() = [6.4 4.8]
base.png PNG 640x480 640x480+0+0 8-bit sRGB 13064B 0.000u 0:00.000

enter image description here

My best approach so far: plt.savefig(dpi=h/fig.get_size_inches()[1] height-only control

I think this is what I'll go with most of the time, as it is simple and scales:

get_size.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'get_size.png',
    format='png',
    dpi=height/fig.get_size_inches()[1]
)

run:

./get_size.py 431

outputs:

get_size.png PNG 574x431 574x431+0+0 8-bit sRGB 10058B 0.000u 0:00.000

enter image description here

and

./get_size.py 1293

outputs:

main.png PNG 1724x1293 1724x1293+0+0 8-bit sRGB 46709B 0.000u 0:00.000

enter image description here

I tend to set just the height because I'm usually most concerned about how much vertical space the image is going to take up in the middle of my text.

plt.savefig(bbox_inches='tight' changes image size

I always feel that there is too much white space around images, and tended to add bbox_inches='tight' from: Removing white space around a saved image in matplotlib

However, that works by cropping the image, and you won't get the desired sizes with it.

Instead, this other approach proposed in the same question seems to work well:

plt.tight_layout(pad=1)
plt.savefig(...

which gives the exact desired height for height equals 431:

enter image description here

Fixed height, set_aspect, automatically sized width and small margins

Ermmm, set_aspect messes things up again and prevents plt.tight_layout from actually removing the margins...

Asked at: How to obtain a fixed height in pixels, fixed data x/y aspect ratio and automatically remove remove horizontal whitespace margin in Matplotlib?

plt.savefig(dpi=h/fig.get_size_inches()[1] + width control

If you really need a specific width in addition to height, this seems to work OK:

width.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

h = int(sys.argv[1])
w = int(sys.argv[2])
fig, ax = plt.subplots()
wi, hi = fig.get_size_inches()
fig.set_size_inches(hi*(w/h), hi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'width.png',
    format='png',
    dpi=h/hi
)

run:

./width.py 431 869

output:

width.png PNG 869x431 869x431+0+0 8-bit sRGB 10965B 0.000u 0:00.000

enter image description here

and for a small width:

./width.py 431 869

output:

width.png PNG 211x431 211x431+0+0 8-bit sRGB 6949B 0.000u 0:00.000

enter image description here

So it does seem that fonts are scaling correctly, we just get some trouble for very small widths with labels getting cut off, e.g. the 100 on the top left.

I managed to work around those with Removing white space around a saved image in matplotlib

plt.tight_layout(pad=1)

which gives:

width.png PNG 211x431 211x431+0+0 8-bit sRGB 7134B 0.000u 0:00.000

enter image description here

From this, we also see that tight_layout removes a lot of the empty space at the top of the image, so I just generally always use it.

Fixed magic base height, dpi on fig.set_size_inches and plt.savefig(dpi= scaling

I believe that this is equivalent to the approach mentioned at: https://stackoverflow.com/a/13714720/895245

magic.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

magic_height = 300
w = int(sys.argv[1])
h = int(sys.argv[2])
dpi = 80
fig, ax = plt.subplots(dpi=dpi)
fig.set_size_inches(magic_height*w/(h*dpi), magic_height/dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'magic.png',
    format='png',
    dpi=h/magic_height*dpi,
)

run:

./magic.py 431 231

outputs:

magic.png PNG 431x231 431x231+0+0 8-bit sRGB 7923B 0.000u 0:00.000

enter image description here

And to see if it scales nicely:

./magic.py 1291 693

outputs:

magic.png PNG 1291x693 1291x693+0+0 8-bit sRGB 25013B 0.000u 0:00.000

enter image description here

So we see that this approach also does work well. The only problem I have with it is that you have to set that magic_height parameter or equivalent.

Fixed DPI + set_size_inches

This approach gave a slightly wrong pixel size, and it makes it is hard to scale everything seamlessly.

set_size_inches.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

w = int(sys.argv[1])
h = int(sys.argv[2])
fig, ax = plt.subplots()
fig.set_size_inches(w/fig.dpi, h/fig.dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(
    0,
    60.,
    'Hello',
    # Keep font size fixed independently of DPI.
    # https://stackoverflow.com/questions/39395616/matplotlib-change-figsize-but-keep-fontsize-constant
    fontdict=dict(size=10*h/fig.dpi),
)
plt.savefig(
    'set_size_inches.png',
    format='png',
)

run:

./set_size_inches.py 431 231

outputs:

set_size_inches.png PNG 430x231 430x231+0+0 8-bit sRGB 8078B 0.000u 0:00.000

so the height is slightly off, and the image:

enter image description here

The pixel sizes are also correct if I make it 3 times larger:

./set_size_inches.py 1291 693

outputs:

set_size_inches.png PNG 1291x693 1291x693+0+0 8-bit sRGB 19798B 0.000u 0:00.000

enter image description here

We understand from this however that for this approach to scale nicely, you need to make every DPI-dependant setting proportional to the size in inches.

In the previous example, we only made the "Hello" text proportional, and it did retain its height between 60 and 80 as we'd expect. But everything for which we didn't do that, looks tiny, including:

  • line width of axes
  • tick labels
  • point markers

SVG

I could not find how to set it for SVG images, my approaches only worked for PNG e.g.:

get_size_svg.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'get_size_svg.svg',
    format='svg',
    dpi=height/fig.get_size_inches()[1]
)

run:

./get_size_svg.py 431

and the generated output contains:

<svg height="345.6pt" version="1.1" viewBox="0 0 460.8 345.6" width="460.8pt"

and identify says:

get_size_svg.svg SVG 614x461 614x461+0+0 8-bit sRGB 17094B 0.000u 0:00.000

and if I open it in Chromium 86 the browser debug tools mouse image hover confirm that height as 460.79.

But of course, since SVG is a vector format, everything should in theory scale, so you can just convert to any fixed sized format without loss of resolution, e.g.:

inkscape -h 431 get_size_svg.svg -b FFF -e get_size_svg.png

gives the exact height:

TODO regenerate image, messed up the upload somehow.

I use Inkscape instead of Imagemagick's convert here because you need to mess with -density as well to get sharp SVG resizes with ImageMagick:

And setting <img height="" on the HTML should also just work for the browser.

Tested on matplotlib==3.2.2.

How to read pdf file and write it to outputStream

You can use PdfBox from Apache which is simple to use and has good performance.

Here is an example of extracting text from a PDF file (you can read more here) :

import java.io.*;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.util.*;

public class PDFTest {

 public static void main(String[] args){
 PDDocument pd;
 BufferedWriter wr;
 try {
         File input = new File("C:\\Invoice.pdf");  // The PDF file from where you would like to extract
         File output = new File("C:\\SampleText.txt"); // The text file where you are going to store the extracted data
         pd = PDDocument.load(input);
         System.out.println(pd.getNumberOfPages());
         System.out.println(pd.isEncrypted());
         pd.save("CopyOfInvoice.pdf"); // Creates a copy called "CopyOfInvoice.pdf"
         PDFTextStripper stripper = new PDFTextStripper();
         wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
         stripper.writeText(pd, wr);
         if (pd != null) {
             pd.close();
         }
        // I use close() to flush the stream.
        wr.close();
 } catch (Exception e){
         e.printStackTrace();
        } 
     }
}

UPDATE:

You can get the text using PDFTextStripper:

PDFTextStripper reader = new PDFTextStripper();
String pageText = reader.getText(pd); // PDDocument object created

Installing R with Homebrew

You can also install R from this page:

https://cran.r-project.org/bin/macosx/

It works out of the box

Remove last character from C++ string

buf.erase(buf.size() - 1);

This assumes you know that the string is not empty. If so, you'll get an out_of_range exception.

tkinter: Open a new window with a button prompt

Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import to Tkinter rather than tkinter (the difference being the capitalization):

import tkinter as tk
#import Tkinter as tk  # for python 2
    
def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.

How do I bind onchange event of a TextBox using JQuery?

Combination of keyup and change is not necessarily enough (browser's autocomplete and paste using mouse also changes the contents of a text box, but doesn't fire either of these events):

jquery change not working incase of dynamic value change

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

To track down the correct parameters you need to go first to ?plot.default, which refers you to ?par and ?axis:

plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
           col.lab="red", cex.lab=1.5,    #  for the xlab and ylab
           col="green")                   #  for the points

How to get a context in a recycler view adapter

If you are using Databinding on layout you can get the context from holder. An exemple below.

@Override
public void onBindViewHolder(@NonNull GenericViewHolder holder, int position) {
    View currentView = holder.binding.getRoot().findViewById(R.id.cycle_count_manage_location_line_layout);// id of your root layout
    currentView.setBackgroundColor(ContextCompat.getColor(holder.binding.getRoot().getContext(), R.color.light_green));
}

is vs typeof

Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.

is tells you if the object implements ClassA anywhere in its type heirarchy. GetType() tells you about the most-derived type.

Not the same thing.

How do you synchronise projects to GitHub with Android Studio?

Github with android studio

/*For New - Run these command in terminal*/
echo "# Your Repository" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/username/repository.git
git push -u origin master

/*For Exist - Run these command in terminal*/
git remote add origin https://github.com/username/repository.git
git push -u origin master
//git push -f origin master
//git push origin master --force

/*For Update - Run these command in terminal*/
git add .
git commit -m "your message"
git push

Matplotlib figure facecolor (background color)

If you want to change background color, try this:

plt.rcParams['figure.facecolor'] = 'white'

split python source code into multiple files?

You can do the same in python by simply importing the second file, code at the top level will run when imported. I'd suggest this is messy at best, and not a good programming practice. You would be better off organizing your code into modules

Example:

F1.py:

print "Hello, "
import f2

F2.py:

print "World!"

When run:

python ./f1.py
Hello, 
World!

Edit to clarify: The part I was suggesting was "messy" is using the import statement only for the side effect of generating output, not the creation of separate source files.

PostgreSQL: how to convert from Unix epoch to date?

select to_timestamp(cast(epoch_ms/1000 as bigint))::date

worked for me

Converting between datetime, Timestamp and datetime64

Some solutions work well for me but numpy will deprecate some parameters. The solution that work better for me is to read the date as a pandas datetime and excract explicitly the year, month and day of a pandas object. The following code works for the most common situation.

def format_dates(dates):
    dt = pd.to_datetime(dates)
    try: return [datetime.date(x.year, x.month, x.day) for x in dt]    
    except TypeError: return datetime.date(dt.year, dt.month, dt.day)

iOS: UIButton resize according to text length

If your button was made with Interface Builder, and you're changing the title in code, you can do this:

[self.button setTitle:@"Button Title" forState:UIControlStateNormal];
[self.button sizeToFit];

Python 3: EOF when reading a line (Sublime Text 2 is angry)

It seems as of now, the only solution is still to install SublimeREPL.

To extend on Raghav's answer, it can be quite annoying to have to go into the Tools->SublimeREPL->Python->Run command every time you want to run a script with input, so I devised a quick key binding that may be handy:

To enable it, go to Preferences->Key Bindings - User, and copy this in there:

[
    {"keys":["ctrl+r"] , 
    "caption": "SublimeREPL: Python - RUN current file",
    "command": "run_existing_window_command", 
    "args":
        {
            "id": "repl_python_run",
            "file": "config/Python/Main.sublime-menu"
        }
    },
]

Naturally, you would just have to change the "keys" argument to change the shortcut to whatever you'd like.

Difference between array_push() and $array[] =

You can add more than 1 element in one shot to array using array_push,

e.g. array_push($array_name, $element1, $element2,...)

Where $element1, $element2,... are elements to be added to array.

But if you want to add only one element at one time, then other method (i.e. using $array_name[]) should be preferred.

What is Persistence Context?

While @pritam kumar gives a good overview the 5th point is not true.

Persistence Context can be either Transaction Scoped-- the Persistence Context 'lives' for the length of the transaction, or Extended-- the Persistence Context spans multiple transactions.

https://blogs.oracle.com/carolmcdonald/entry/jpa_caching

JPA's EntityManager and Hibernate's Session offer an extended Persistence Context.

Why do I get "'property cannot be assigned" when sending an SMTP email?

Just need to try this:

string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "companyemail";
string password = "password";
string emailTo = "Your email";
string subject = "Hello!";
string body = "Hello, Mr.";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
   smtp.Credentials = new NetworkCredential(emailFrom, password);
   smtp.EnableSsl = enableSSL;
   smtp.Send(mail);
}

How do I create a comma-separated list using a SQL query?

I believe what you want is:

SELECT ItemName, GROUP_CONCAT(DepartmentId) FROM table_name GROUP BY ItemName

If you're using MySQL

Reference

What is the difference between sed and awk?

Both tools are meant to work with text and there are tasks both tools can be used for.

For me the rule to separate them is: Use sed to automate tasks you would do otherwise in a text editor manually. That's why it is called stream editor. (You can use the same commands to edit text in vim). Use awk if you want to analyze text, meaning counting fields, calculate totals, extract and reorganize structures etc.

Also you should not forget about grep. Use grep if you only want to search/extract something in a text (file)

How to connect with Java into Active Directory

You can use DDC (Domain Directory Controller). It is a new, easy to use, Java SDK. You don't even need to know LDAP to use it. It exposes an object-oriented API instead.

You can find it here.

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

You should execute the next query:

GRANT ALL ON TABLE mytable TO myuser;

Or if your error is in a view then maybe the table does not have permission, so you should execute the next query:

GRANT ALL ON TABLE tbm_grupo TO myuser;

Why is the console window closing immediately once displayed my output?

I always add the following statement to a console application.(Create a code snippet for this if you wish)

Console.WriteLine("Press any key to quit!");
Console.ReadKey();

Doing this helps when you want to experiment different concepts through console application.

Ctr + F5 will make the Console stay but you cant debug! All the console applications that I have written in realworld is always non-interactive and triggered by a Scheduler such as TWS or CA Work station and did not require something like this.

Re-doing a reverted merge in Git

Let's assume you have such history

---o---o---o---M---W---x-------x-------*
              /                      
      ---A---B

Where A, B failed commits and W - is revert of M

So before I start fixing found problems I do cherry-pick of W commit to my branch

git cherry-pick -x W

Then I revert W commit on my branch

git revert W 

After I can continue fixing.

The final history could look like:

---o---o---o---M---W---x-------x-------*
              /                       /     
      ---A---B---W---W`----------C---D

When I send a PR it will clearly shows that PR is undo revert and adds some new commits.

How to convert Excel values into buckets?

A nice way to create buckets is the LOOKUP() function.

In this example contains cell A1 is a count of days. The vthe second parameter is a list of values. The third parameter is the list of bucket names.

=LOOKUP(A1,{0,7,14,31,90,180,360},{"0-6","7-13","14-30","31-89","90-179","180-359",">360"})

What design patterns are used in Spring framework?

The DI thing actually is some kind of strategy pattern. Whenever you want to be some logic/implementation exchangeable you typically find an interface and an appropriate setter method on the host class to wire your custom implementation of that interface.

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

I met with this problem too. And I figured it out by the following way:

First, open the terminal and write

mongod --dbpath {your project's path}

Second, open a new terminal and enter your project's path, write

mongo

Then it runs successfully

Pinging an IP address using PHP and echoing the result

I use this function :

<?php
function is_ping_address($ip) {
    exec('ping -c1 -w1 '.$ip, $outcome, $status);
    preg_match('/([0-9]+)% packet loss/', $outcome[3], $arr);
    return ( $arr[1] == 100 ) ? false : true;
}

How do I get the current location of an iframe?

I like your server side idea, even if my proposed implementation of it sounds a little bit ghetto.

You could set the .innerHTML of the iframe to the HTML contents you grab server side. Depending on how you grab this, you will have to pay attention to relative versus absolute paths.

Plus, depending on how the page you are grabbing interacts with other pages, this could totally not work (cookies being set for the page you are grabbing won't work across domains, maybe state is being tracked in Javascript... Lots of reasons this might not work.)

I don't believe that tracking the current state of the page you are trying to mirror is theoretically possible, but I'm not sure. The site could track all sorts of things server side, you won't have access to this state. Imagine the case where on a page load a variable is set to a random value server-side, how would you capture this state?

Do these ideas help with anything?

-Brian J. Stinar-

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

For bootstrap 3.0, this worked for me:

.myclass .glyphicon {color:blue !important;}

SELECT * FROM in MySQLi

Is this statement a thing of the past?

Yes. Don't use SELECT *; it's a maintenance nightmare. There are tons of other threads on SO about why this construct is bad, and how avoiding it will help you write better queries.

See also:

Best way to concatenate List of String objects?

Rather than depending on ArrayList.toString() implementation, you could write a one-liner, if you are using java 8:

String result = sList.stream()
                     .reduce("", String::concat);

If you prefer using StringBuffer instead of String since String::concat has a runtime of O(n^2), you could convert every String to StringBuffer first.

StringBuffer result = sList.stream()
                           .map(StringBuffer::new)
                           .reduce(new StringBuffer(""), StringBuffer::append);

How can I account for period (AM/PM) using strftime?

format = '%Y-%m-%d %H:%M %p'

The format is using %H instead of %I. Since %H is the "24-hour" format, it's likely just discarding the %p information. It works just fine if you change the %H to %I.

Filter Pyspark dataframe column with None value

PySpark provides various filtering options based on arithmetic, logical and other conditions. Presence of NULL values can hamper further processes. Removing them or statistically imputing them could be a choice.

Below set of code can be considered:

# Dataset is df
# Column name is dt_mvmt
# Before filtering make sure you have the right count of the dataset
df.count() # Some number

# Filter here
df = df.filter(df.dt_mvmt.isNotNull())

# Check the count to ensure there are NULL values present (This is important when dealing with large dataset)
df.count() # Count should be reduced if NULL values are present

How can I parse a YAML file from a Linux shell script?

A quick way to do the thing now (previous ones haven't worked for me):

sudo wget https://github.com/mikefarah/yq/releases/download/v4.4.1/yq_linux_amd64 -O /usr/bin/yq &&\
sudo chmod +x /usr/bin/yq

Example asd.yaml:

a_list:
  - key1: value1
    key2: value2
    key3: value3

parsing root:

user@vm:~$ yq e '.' asd.yaml                                                                                                         
a_list:
  - key1: value1
    key2: value2
    key3: value3

parsing key3:

user@vm:~$ yq e '.a_list[0].key3' asd.yaml                                                                                             
value3

Where is the Java SDK folder in my computer? Ubuntu 12.04

you can simply write the following command in the terminal of your linux system and get the java path :- echo $JAVA_HOME

How to base64 encode image in linux bash / shell

There is a Linux command for that: base64

base64 DSC_0251.JPG >DSC_0251.b64

To assign result to variable use

test=`base64 DSC_0251.JPG`

How can one develop iPhone apps in Java?

If you've completed your other projects, why not take the time to learn Objective-C? There is a ton of material out on the web to help you get started. Honestly, it won't be that hard and learning to do some memory management will be a great learning exercise. Have you programmed in C before?

Most cross compilers won't do a great job in converting your code, and debugging your project may become much more difficult if you develop them this way.

Convert list to dictionary using linq and not worrying about duplicates

You can also use the ToLookup LINQ function, which you then can use almost interchangeably with a Dictionary.

_people = personList
    .ToLookup(e => e.FirstandLastName, StringComparer.OrdinalIgnoreCase);
_people.ToDictionary(kl => kl.Key, kl => kl.First()); // Potentially unnecessary

This will essentially do the GroupBy in LukeH's answer, but will give the hashing that a Dictionary provides. So, you probably don't need to convert it to a Dictionary, but just use the LINQ First function whenever you need to access the value for the key.

How do I install g++ on MacOS X?

Installing XCode requires:

  • Enrolling on the Apple website (not fun)
  • Downloading a 4.7G installer

To install g++ *WITHOUT* having to download the MASSIVE 4.7G xCode install, try this package:

https://github.com/kennethreitz/osx-gcc-installer

The DMG files linked on that page are ~270M and much quicker to install. This was perfect for me, getting homebrew up and running with a minimum of hassle.

The github project itself is basically a script that repackages just the critical chunks of xCode for distribution. In order to run that script and build the DMG files, you'd need to already have an XCode install, which would kind of defeat the point, so the pre-built DMG files are hosted on the project page.

PHP: How do you determine every Nth iteration of a loop?

How about: if(($counter % $display) == 0)

PHP Remove elements from associative array

Why do not use array_diff?

$array = array(
    1 => 'Awaiting for Confirmation', 
    2 => 'Asssigned', 
    3 => 'In Progress', 
    4 => 'Completed', 
    5 => 'Mark As Spam', 
);
$to_delete = array('Completed', 'Mark As Spam');
$array = array_diff($array, $to_delete);

Just note that your array would be reindexed.

Convert tuple to list and back

To convert tuples to list

(Commas were missing between the tuples in the given question, it was added to prevent error message)

Method 1:

level1 = (
     (1,1,1,1,1,1),
     (1,0,0,0,0,1),
     (1,0,0,0,0,1),
     (1,0,0,0,0,1),
     (1,0,0,0,0,1),
     (1,1,1,1,1,1))

level1 = [list(row) for row in level1]

print(level1)

Method 2:

level1 = map(list,level1)

print(list(level1))

Method 1 took --- 0.0019991397857666016 seconds ---

Method 2 took --- 0.0010001659393310547 seconds ---