Programs & Examples On #Pragma

The #pragma directives offer a way for each compiler to offer machine- and operating system-specific features while retaining overall compatibility with the C and C++ languages.

Use of #pragma in C

I would generally try to avoid the use of #pragmas if possible, since they're extremely compiler-dependent and non-portable. If you want to use them in a portable fashion, you'll have to surround every pragma with a #if/#endif pair. GCC discourages the use of pragmas, and really only supports some of them for compatibility with other compilers; GCC has other ways of doing the same things that other compilers use pragmas for.

For example, here's how you'd ensure that a structure is packed tightly (i.e. no padding between members) in MSVC:

#pragma pack(push, 1)
struct PackedStructure
{
  char a;
  int b;
  short c;
};
#pragma pack(pop)
// sizeof(PackedStructure) == 7

Here's how you'd do the same thing in GCC:

struct PackedStructure __attribute__((__packed__))
{
  char a;
  int b;
  short c;
};
// sizeof(PackedStructure == 7)

The GCC code is more portable, because if you want to compile that with a non-GCC compiler, all you have to do is

#define __attribute__(x)

Whereas if you want to port the MSVC code, you have to surround each pragma with a #if/#endif pair. Not pretty.

What does "#pragma comment" mean?

I've always called them "compiler directives." They direct the compiler to do things, branching, including libs like shown above, disabling specific errors etc., during the compilation phase.

Compiler companies usually create their own extensions to facilitate their features. For example, (I believe) Microsoft started the "#pragma once" deal and it was only in MS products, now I'm not so sure.

Pragma Directives It includes "#pragma comment" in the table you'll see.

HTH

I suspect GCC, for example, has their own set of #pragma's.

Disable single warning error

In certain situations you must have a named parameter but you don't use it directly.
For example, I ran into it on VS2010, when 'e' is used only inside a decltype statement, the compiler complains but you must have the named varible e.

All the above non-#pragma suggestions all boil down to just adding a single statement:

bool f(int e)
{ 
   // code not using e
   return true;
   e; // use without doing anything
}

How to disable GCC warnings for a few lines of code

To net everything out, this is an example of temporarily disabling a warning:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-result"
    write(foo, bar, baz);
#pragma GCC diagnostic pop

You can check the GCC documentation on diagnostic pragmas for more details.

What is the significance of #pragma marks? Why do we need #pragma marks?

#pragma mark directives show up in Xcode in the menus for direct access to methods. They have no impact on the program at all.

For example, using it with Xcode 4 will make those items appear directly in the Jump Bar.

There is a special pragma mark - which creates a line.

enter image description here

Calculate percentage saved between two numbers?

I know this is fairly old but I figured this was as good as any to put this. I found a post from yahoo with a good explanation:

Let's say you have two numbers, 40 and 30.  

  30/40*100 = 75.
  So 30 is 75% of 40.  

  40/30*100 = 133. 
  So 40 is 133% of 30. 

The percentage increase from 30 to 40 is:  
  (40-30)/30 * 100 = 33%  

The percentage decrease from 40 to 30 is:
  (40-30)/40 * 100 = 25%. 

These calculations hold true whatever your two numbers.

Original Post

How to format a numeric column as phone number in SQL

You can also try this:

CREATE  function [dbo].[fn_FormatPhone](@Phone varchar(30)) 
returns varchar(30)
As
Begin
declare @FormattedPhone varchar(30)

set     @Phone = replace(@Phone, '.', '-') --alot of entries use periods instead of dashes
set @FormattedPhone =
    Case
      When isNumeric(@Phone) = 1 Then
        case
          when len(@Phone) = 10 then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 4, 3)+ '-' +substring(@Phone, 7, 4)
          when len(@Phone) = 7  then substring(@Phone, 1, 3)+ '-' +substring(@Phone, 4, 4)
          else @Phone
        end
      When @phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 8, 4)
      When @phone like '[0-9][0-9][0-9] [0-9][0-9][0-9] [0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 9, 4)
      When @phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 9, 4)
      Else @Phone
    End
return  @FormattedPhone

end

use on it select

(SELECT [dbo].[fn_FormatPhone](f.coffphone)) as 'Phone'

Output will be

enter image description here

How to change font size on part of the page in LaTeX?

http://en.wikibooks.org/wiki/LaTeX/Formatting

use \alltt environment instead. Then set size using the same commands as outside verbatim environment.

What is hashCode used for? Is it unique?

MSDN says:

A hash code is a numeric value that is used to identify an object during equality testing. It can also serve as an index for an object in a collection.

The GetHashCode method is suitable for use in hashing algorithms and data structures such as a hash table.

The default implementation of the GetHashCode method does not guarantee unique return values for different objects. Furthermore, the .NET Framework does not guarantee the default implementation of the GetHashCode method, and the value it returns will be the same between different versions of the .NET Framework. Consequently, the default implementation of this method must not be used as a unique object identifier for hashing purposes.

The GetHashCode method can be overridden by a derived type. Value types must override this method to provide a hash function that is appropriate for that type and to provide a useful distribution in a hash table. For uniqueness, the hash code must be based on the value of an instance field or property instead of a static field or property.

Objects used as a key in a Hashtable object must also override the GetHashCode method because those objects must generate their own hash code. If an object used as a key does not provide a useful implementation of GetHashCode, you can specify a hash code provider when the Hashtable object is constructed. Prior to the .NET Framework version 2.0, the hash code provider was based on the System.Collections.IHashCodeProvider interface. Starting with version 2.0, the hash code provider is based on the System.Collections.IEqualityComparer interface.

Basically, hash codes exist to make hashtables possible.
Two equal objects are guaranteed to have equal hashcodes.
Two unequal objects are not guaranteed to have unequal hashcodes (that's called a collision).

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

How do I check that multiple keys are in a dict in a single pass?

Well, you could do this:

>>> if all (k in foo for k in ("foo","bar")):
...     print "They're there!"
...
They're there!

Change the On/Off text of a toggle button Android

It appears you no longer need toggleButton.setTextOff(textOff); and toggleButton.setTextOn(textOn);. The text for each toggled state will change by merely including the relevant xml characteristics. This will override the default ON/OFF text.

<ToggleButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/toggleText"
    android:textOff="ADD TEXT"
    android:textOn="CLOSE TEXT"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="10dp"
    android:visibility="gone"/>

How to find the port for MS SQL Server 2008?

I came across this because I just had problems creating a remote connection and couldn't understand why setting up 1433 port in firewall is not doing the job. I finally have the full picture now, so I thought I should share.

First of all is a must to enable "TCP/IP" using the SQL Server Configuration Manager under Protocols for SQLEXPRESS!

When a named instance is used ("SQLExpress" in this case), this will listen on a dynamic port. To find this dynamic port you have couple of options; to name a few:

  • checking ERRORLOG of SQL Server located in '{MS SQL Server Path}\{MS SQL Server instance name}\MSSQL\Log' (inside you'll find a line similar to this: "2013-07-25 10:30:36.83 Server Server is listening on [ 'any' <ipv4> 51118]" --> so 51118 is the dynamic port in this case.

  • checking registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\{MSSQL instance name}\MSSQLServer\SuperSocketNetLib\Tcp\IPAll, for my case TcpDynamicPorts=51118.

    Edit: {MSSQL instance name} is something like: MSSQL10_50.SQLEXPRESS, not only SQLEXPRESS

Of course, allowing this TCP port in firewall and creating a remote connection by passing in: "x.x.x.x,51118" (where x.x.x.x is the server ip) already solves it at this point.

But then I wanted to connect remotely by passing in the instance name (e.g: x.x.x.x\SQLExpress). This is when SQL Browser service comes into play. This is the unit which resolves the instance name into the 51118 port. SQL Browser service listens on UDP port 1434 (standard & static), so I had to allow this also in server's firewall.

To extend a bit the actual answer: if someone else doesn't like dynamic ports and wants a static port for his SQL Server instance, should try this link.

Remove or adapt border of frame of legend using matplotlib

When plotting a plot using matplotlib:

How to remove the box of the legend?

plt.legend(frameon=False)

How to change the color of the border of the legend box?

leg = plt.legend()
leg.get_frame().set_edgecolor('b')

How to remove only the border of the box of the legend?

leg = plt.legend()
leg.get_frame().set_linewidth(0.0)

Apache: client denied by server configuration

Here's my symfony 1.4 virtual host file on debian, which works fine.

  <Directory /var/www/sf_project/web/>
    Options All Indexes FollowSymLinks    
    AllowOverride All
    Order allow,deny
    Allow from all
  </Directory>

If you wan't to restrict access to a specific ip range, e.g. localhost use this:

Allow from 127.0.0.0/8

The mod_authz_host is responsible for filtering ip ranges. You can look up detailed things in there.

But maybe the problem could be related to some kind of misconfiguration in your "apache2.conf".

On what OS is the apache running?

How to obtain Certificate Signing Request

To manually generate a Certificate, you need a Certificate Signing Request (CSR) file from your Mac. To create a CSR file, follow the instructions below to create one using Keychain Access.

Create a CSR file. In the Applications folder on your Mac, open the Utilities folder and launch Keychain Access.

Within the Keychain Access drop down menu, select Keychain Access > Certificate Assistant > Request a Certificate from a Certificate Authority.

In the Certificate Information window, enter the following information: In the User Email Address field, enter your email address. In the Common Name field, create a name for your private key (e.g., John Doe Dev Key). The CA Email Address field should be left empty. In the "Request is" group, select the "Saved to disk" option. Click Continue within Keychain Access to complete the CSR generating process.

PHP - Get bool to echo false when false

var_export provides the desired functionality.

This will always print a value rather than printing nothing for null or false. var_export prints a PHP representation of the argument it's passed, the output could be copy/pasted back into PHP.

var_export(true);    // true
var_export(false);   // false
var_export(1);       // 1
var_export(0);       // 0
var_export(null);    // NULL
var_export('true');  // 'true'   <-- note the quotes
var_export('false'); // 'false'

If you want to print strings "true" or "false", you can cast to a boolean as below, but beware of the peculiarities:

var_export((bool) true);   // true
var_export((bool) false);  // false
var_export((bool) 1);      // true
var_export((bool) 0);      // false
var_export((bool) '');     // false
var_export((bool) 'true'); // true
var_export((bool) null);   // false

// !! CAREFUL WITH CASTING !!
var_export((bool) 'false'); // true
var_export((bool) '0');     // false

How to check if input is numeric in C++

I guess ctype.h is the header file that you need to look at. it has numerous functions for handling digits as well as characters. isdigit or iswdigit is something that will help you in this case.

Here is a reference: http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/isdigit_xml.html

what does this mean ? image/png;base64?

That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).

Regex to validate JSON

I tried @mario's answer, but it didn't work for me, because I've downloaded test suite from JSON.org (archive) and there were 4 failed tests (fail1.json, fail18.json, fail25.json, fail27.json).

I've investigated the errors and found out, that fail1.json is actually correct (according to manual's note and RFC-7159 valid string is also a valid JSON). File fail18.json was not the case either, cause it contains actually correct deeply-nested JSON:

[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]

So two files left: fail25.json and fail27.json:

["  tab character   in  string  "]

and

["line
break"]

Both contains invalid characters. So I've updated the pattern like this (string subpattern updated):

$pcreRegex = '/
          (?(DEFINE)
             (?<number>   -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? )
             (?<boolean>   true | false | null )
             (?<string>    " ([^"\n\r\t\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " )
             (?<array>     \[  (?:  (?&json)  (?: , (?&json)  )*  )?  \s* \] )
             (?<pair>      \s* (?&string) \s* : (?&json)  )
             (?<object>    \{  (?:  (?&pair)  (?: , (?&pair)  )*  )?  \s* \} )
             (?<json>   \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) \s* )
          )
          \A (?&json) \Z
          /six';

So now all legal tests from json.org can be passed.

Redirect HTTP to HTTPS on default virtual host without ServerName

Try adding this in your vhost config:

RewriteEngine On
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]

"Warning: iPhone apps should include an armv6 architecture" even with build config set

Here is Apple's documentation:

Technical Q&A QA1760

It says there are two things that you must get right:

  1. Add armv6 to the Architecture build settings
  2. Set Build Active Architecture Only to No.

If this still doesn't help you, double check that you are really changing the architecture build settings for the right build configuration – I wasted half an hour fiddling with the wrong one and wondering why it didn't work...

Select Edit Scheme... in the Product menu, click the "Archive" scheme in the left list and check the Build Configuration. Change the value if it was not what you expected.

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

when bullet have to hide then use:

li { list-style: none;}

when bullet have to list show, then use:

li { list-style: initial;}

Static Initialization Blocks

Here's an example:

  private static final HashMap<String, String> MAP = new HashMap<String, String>();
  static {
    MAP.put("banana", "honey");
    MAP.put("peanut butter", "jelly");
    MAP.put("rice", "beans");
  }

The code in the "static" section(s) will be executed at class load time, before any instances of the class are constructed (and before any static methods are called from elsewhere). That way you can make sure that the class resources are all ready to use.

It's also possible to have non-static initializer blocks. Those act like extensions to the set of constructor methods defined for the class. They look just like static initializer blocks, except the keyword "static" is left off.

How to convert string to integer in UNIX

let d=d1-d2;echo $d;

This should help.

How do I make a JAR from a .java file?

Open a command prompt.

Go to the directory where you have your .java files

Create a directory build

Run java compilation from the command line

javac -d ./build *.java

if there are no errors, in the build directory you should have your class tree

move to the build directory and do a

jar cvf YourJar.jar *

For adding manifest check jar command line switches

How can I store HashMap<String, ArrayList<String>> inside a list?

First you need to define the List as :

List<Map<String, ArrayList<String>>> list = new ArrayList<>();

To add the Map to the List , use add(E e) method :

list.add(map);

Get class labels from Keras functional model

y_prob = model.predict(x) 
y_classes = y_prob.argmax(axis=-1)

As suggested here.

Random String Generator Returning Same String

Combining the answer by "Pushcode" and the one using the seed for the random generator. I needed it to create a serie of pseudo-readable 'words'.

private int RandomNumber(int min, int max, int seed=0)
{
    Random random = new Random((int)DateTime.Now.Ticks + seed);
    return random.Next(min, max);
}

How do I import the javax.servlet API in my Eclipse project?

In my case, when I went to the Targetted Runtimes, screen, Tomcat 7 was not listed (disabled) despite being installed.

To fix, I had to go to Preferences->Server->Runtime Environments then uninstall and reinstall Tomcat 7.

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

Whenever you create or update package name Make sure your package name is exactly the same [Upper case and lower case matters]

Do below step.

1). Check applicationId in App level gradle file,

2). Check package_name in your google-services.json file,

3). Check package in your AndroidManifest file

and for full confirmation make sure that your working package directory name i.e.("com.example.app") is also the same.

EDIT [ Any one who is facing this issue in productFlavour scenario, go check out Droid Chris's Solution ]

iterating through Enumeration of hastable keys throws NoSuchElementException error

Every time you call e.nextElement() you take the next object from the iterator. You have to check e.hasMoreElement() between each call.


Example:

while(e.hasMoreElements()){
    String param = e.nextElement();
    System.out.println(param);
}

batch file to copy files to another location?

Two approaches:

  • When you login: you can to create a copy_my_files.bat file into your All Programs > Startup folder with this content (its a plain text document):

    • xcopy c:\folder\*.* d:\another_folder\.

    Use xcopy c:\folder\*.* d:\another_folder\. /Y to overwrite the file without any prompt.

  • Everytime a folder changes: if you can to use C#, you can to create a program using FileSystemWatcher

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so: IsEmpty(.Cell(i,1)) does ->

return .Cell(i,1) <> Empty

How to really read text file from classpath in Java

You say "I am trying to read a text file which is set in CLASSPATH system variable." My guess this is on Windows and you are using this ugly dialog to edit the "System Variables".

Now you run your Java program in the console. And that doesn't work: The console gets a copy of the values of the system variables once when it is started. This means any change in the dialog afterwards doesn't have any effect.

There are these solutions:

  1. Start a new console after every change

  2. Use set CLASSPATH=... in the console to set the copy of the variable in the console and when your code works, paste the last value into the variable dialog.

  3. Put the call to Java into .BAT file and double click it. This will create a new console every time (thus copying the current value of the system variable).

BEWARE: If you also have a User variable CLASSPATH then it will shadow your system variable. That is why it is usually better to put the call to your Java program into a .BAT file and set the classpath in there (using set CLASSPATH=) rather than relying on a global system or user variable.

This also makes sure that you can have more than one Java program working on your computer because they are bound to have different classpaths.

Spring 3 MVC resources and tag <mvc:resources />

Found the error:

Final xxx-servlet.xml config:

<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />

Image in src/webapp/resources/logo.png

Works!

C programming in Visual Studio

Short answer: Yes, you need to rename .cpp files to c, so you can write C: https://msdn.microsoft.com/en-us/library/bb384838.aspx?f=255&MSPPError=-2147217396

From the link above:

By default, the Visual C++ compiler treats all files that end in .c as C source code, and all files that end in .cpp as C++ source code. To force the compiler to treat all files as C regardless of file name extension, use the /Tc compiler option.

That being said, I do not recommend learning C language in Visual Studio, why VS? It does have lots of features you are not going to use while learning C

CALL command vs. START with /WAIT option

For exe files, I suppose the differences are nearly unimportant.
But to start an exe you don't even need CALL.

When starting another batch it's a big difference,
as CALL will start it in the same window and the called batch has access to the same variable context.
So it can also change variables which affects the caller.

START will create a new cmd.exe for the called batch and without /b it will open a new window.
As it's a new context, variables can't be shared.

Differences

Using start /wait <prog>
- Changes of environment variables are lost when the <prog> ends
- The caller waits until the <prog> is finished

Using call <prog>
- For exe it can be ommited, because it's equal to just starting <prog>
- For an exe-prog the caller batch waits or starts the exe asynchronous, but the behaviour depends on the exe itself.
- For batch files, the caller batch continues, when the called <batch-file> finishes, WITHOUT call the control will not return to the caller batch

Addendum:

Using CALL can change the parameters (for batch and exe files), but only when they contain carets or percent signs.

call myProg param1 param^^2 "param^3" %%path%%

Will be expanded to (from within an batch file)

myProg param1 param2 param^^3 <content of path>

Number of rows affected by an UPDATE in PL/SQL

SQL%ROWCOUNT can also be used without being assigned (at least from Oracle 11g).

As long as no operation (updates, deletes or inserts) has been performed within the current block, SQL%ROWCOUNT is set to null. Then it stays with the number of line affected by the last DML operation:

say we have table CLIENT

create table client (
  val_cli integer
 ,status varchar2(10)
)
/

We would test it this way:

begin
  dbms_output.put_line('Value when entering the block:'||sql%rowcount);

  insert into client 
            select 1, 'void' from dual
  union all select 4, 'void' from dual
  union all select 1, 'void' from dual
  union all select 6, 'void' from dual
  union all select 10, 'void' from dual;  
  dbms_output.put_line('Number of lines affected by previous DML operation:'||sql%rowcount);

  for val in 1..10
    loop
      update client set status = 'updated' where val_cli = val;
      if sql%rowcount = 0 then
        dbms_output.put_line('no client with '||val||' val_cli.');
      elsif sql%rowcount = 1 then
        dbms_output.put_line(sql%rowcount||' client updated for '||val);
      else -- >1
        dbms_output.put_line(sql%rowcount||' clients updated for '||val);
      end if;
  end loop;  
end;

Resulting in:

Value when entering the block:
Number of lines affected by previous DML operation:5
2 clients updated for 1
no client with 2 val_cli.
no client with 3 val_cli.
1 client updated for 4
no client with 5 val_cli.
1 client updated for 6
no client with 7 val_cli.
no client with 8 val_cli.
no client with 9 val_cli.
1 client updated for 10

Generate an integer that is not among four billion given ones

They may be looking to see if you have heard of a probabilistic Bloom Filter which can very efficiently determine absolutely if a value is not part of a large set, (but can only determine with high probability it is a member of the set.)

Object Dump JavaScript

function mydump(arr,level) {
    var dumped_text = "";
    if(!level) level = 0;

    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";

    if(typeof(arr) == 'object') {  
        for(var item in arr) {
            var value = arr[item];

            if(typeof(value) == 'object') { 
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += mydump(value,level+1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { 
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
}

How do I start Mongo DB from Windows?

there are 2 ways start mongoDB Install location ( ex : C:/ )

first of all : copy mongoDB install folder into C:/ location then changed name to "mongodb" or something what u want. here is ex with "mongodb" name

1 : setup mongoDB is an windows service

    1.1 : Make directory name "data" in C:/ ( so we have C:/data ),after that make directory "C:/data/db" <br>
    1.2 : run in CMD ( Run as Admin) command ->  "echo logpath=C:/mongodb/log/mongo.log > C:/mongodb/mongodb.cfg" <br>
    1.3 : run in CMD (Run as Adin) command -> "C:/mongodb/bin/mongod.exe --config C:/mongodb/mongod.cfg --install" <br>
    1.4 : run command "net start MongoDB" <br>

2: a small .BAT file to start mongoDB without install copy and paste to notepad and save file with filetype ".bat" here is it :

C:\mongodb\bin\mongod.exe –dbpath=C:/mongodb/data/db
   PAUSE

if you getting error 1078 or 1087 lets remove all data in C:/data/db and restart mongoDB ( copy old data to new folder and back it up after restart mongoDB )

3 . GUI for mongoDB

i'm using rockmongo

have fun with it

How to get all keys with their values in redis

Below is just a little variant of the script provided by @"Juuso Ohtonen".

I have add a password variable and counter so you can can check the progression of your backup. Also I replaced simple brackets [] by double brackets [[]] to prevent an error I had on macos.

1. Get the total number of keys

$ sudo redis-cli
INFO keyspace
AUTH yourpassword
INFO keyspace

2. Edit the script

#!/bin/bash

# Default to '*' key pattern, meaning all redis keys in the namespace
REDIS_KEY_PATTERN="${REDIS_KEY_PATTERN:-*}"
PASS="yourpassword"
i=1
for key in $(redis-cli -a "$PASS" --scan --pattern "$REDIS_KEY_PATTERN")
do
    echo $i.
    ((i=i+1))
    type=$(redis-cli -a "$PASS" type $key)
    if [[ $type = "list" ]]
    then
        printf "$key => \n$(redis-cli -a "$PASS" lrange $key 0 -1 | sed 's/^/  /')\n"
    elif [[ $type = "hash" ]]
    then
        printf "$key => \n$(redis-cli -a "$PASS" hgetall $key | sed 's/^/  /')\n"
    else
        printf "$key => $(redis-cli -a "$PASS" get $key)\n"
    fi
    echo
done

3. Execute the script

bash redis_print.sh > redis.bak

4. Check progression

tail redis.bak

Symfony2 Setting a default choice field selection

the solution: for type entity use option "data" but value is a object. ie:

$em = $this->getDoctrine()->getEntityManager();

->add('sucursal', 'entity', array
(

    'class' => 'TestGeneralBundle:Sucursal',
    'property'=>'descripcion',
    'label' => 'Sucursal',
    'required' => false,
    'data'=>$em->getReference("TestGeneralBundle:Sucursal",3)           

))

How to get primary key of table?

How about this:

SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'Your Database'
  AND TABLE_NAME = 'Your Table name'
  AND COLUMN_KEY = 'PRI';


SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'Your Database'
  AND TABLE_NAME = 'Your Table name'
  AND COLUMN_KEY = 'UNI';

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

Angular and Typescript: Can't find names - Error: cannot find name

A known issue: https://github.com/angular/angular/issues/4902

Core reason: the .d.ts file implicitly included by TypeScript varies with the compile target, so one needs to have more ambient declarations when targeting es5 even if things are actually present in the runtimes (e.g. chrome). More on lib.d.ts

Get current time as formatted string in Go?

As an echo to @Bactisme's response, the way one would go about retrieving the current timestamp (in milliseconds, for example) is:

msec := time.Now().UnixNano() / 1000000

Resource: https://gobyexample.com/epoch

fastest way to export blobs from table into individual files

For me what worked by combining all the posts I have read is:

1.Enable OLE automation - if not enabled

sp_configure 'show advanced options', 1;  
GO  
RECONFIGURE;  
GO  
sp_configure 'Ole Automation Procedures', 1;  
GO  
RECONFIGURE;  
GO

2.Create a folder where the generated files will be stored:

C:\GREGTESTING

3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
enter image description here

CREATE TABLE [dbo].[Document](
    [Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [Extension] [varchar](50) NULL,
    [FileName] [varchar](200) NULL,
    [Doc_Content] [varbinary](max) NULL   
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 

INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
    SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)

Important note!

Don't forget to add in Doc_Content column the varbinary of file you want to generate!

4.Run the below script

DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max) 
, @fPath varchar(max)  
, @folderPath  varchar(max)

--Get Data into temp Table variable so that we can iterate over it 
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num]  varchar(100) , [FileName]  varchar(100), [Doc_Content] varBinary(max) )



INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM  [dbo].[Document]



SELECT @i = COUNT(1) FROM @Doctable   

WHILE @i >= 1   

BEGIN    

SELECT 
    @data = [Doc_Content],
    @fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
    @folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;  
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+  @fPath   

--Reset the variables for next use
SELECT @data = NULL  
, @init = NULL
, @fPath = NULL  
, @folderPath = NULL
SET @i -= 1
END   

5.The results is shown below: enter image description here

What is the equivalent of the C# 'var' keyword in Java?

Lombok supports var but it's still classified as experimental:

import lombok.experimental.var;

var number = 1; // Inferred type: int
number = 2; // Legal reassign since var is not final
number = "Hi"; // Compilation error since a string cannot be assigned to an int variable
System.out.println(number);

Here is a pitfall to avoid when trying to use it in IntelliJ IDEA. It appears to work as expected though including auto completion and everything. Until there is a "non-hacky" solution (e.g. due to JEP 286: Local-Variable Type Inference), this might be your best bet right now.

Note that val is support by Lombok as well without modifying or creating a lombok.config.

Check if a string is a date value

Here's a minimalist version.

var isDate = function (date) {
    return!!(function(d){return(d!=='Invalid Date'&&!isNaN(d))})(new Date(date));
}

Could not find the main class, program will exit

I had this problem when I "upgraded" to Windows 7, which is 64-bit. My go to Java JRE is a 64-bit JVM. I had a 32-bit JRE on my machine for my browser, so I set up a system variable:

JRE32=C:\Program Files\Java\jre7

When I run:

"%JRE32\bin\java" -version

I get:

java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) Client VM (build 24.51-b03, mixed mode, sharing)

Which is a 32-bit JVM. It would say "Java HotSpot(TM) 64-Bit" otherwise.

I edited the "squirrel-sql.bat" file, REMarking out line 4 and adding line 5 as follows:

(4) rem set "IZPACK_JAVA=%JAVA_HOME%"
(5) set IZPACK_JAVA=%JRE32%

And now everything works, fine and dandy.

Is there anything like .NET's NotImplementedException in Java?

No there isn't and it's probably not there, because there are very few valid uses for it. I would think twice before using it. Also, it is indeed easy to create yourself.

Please refer to this discussion about why it's even in .NET.

I guess UnsupportedOperationException comes close, although it doesn't say the operation is just not implemented, but unsupported even. That could imply no valid implementation is possible. Why would the operation be unsupported? Should it even be there? Interface segregation or Liskov substitution issues maybe?

If it's work in progress I'd go for ToBeImplementedException, but I've never caught myself defining a concrete method and then leave it for so long it makes it into production and there would be a need for such an exception.

Are the shift operators (<<, >>) arithmetic or logical in C?

Here are functions to guarantee logical right shift and arithmetic right shift of an int in C:

int logicalRightShift(int x, int n) {
    return (unsigned)x >> n;
}
int arithmeticRightShift(int x, int n) {
    if (x < 0 && n > 0)
        return x >> n | ~(~0U >> n);
    else
        return x >> n;
}

Make JQuery UI Dialog automatically grow or shrink to fit its contents

If you need it to work in IE7, you can't use the undocumented, buggy, and unsupported {'width':'auto'} option. Instead, add the following to your .dialog():

'open': function(){ $(this).dialog('option', 'width', this.scrollWidth) }

Whether .scrollWidth includes the right-side padding depends on the browser (Firefox differs from Chrome), so you can either add a subjective "good enough" number of pixels to .scrollWidth, or replace it with your own width-calculation function.

You might want to include width: 0 among your .dialog() options, since this method will never decrease the width, only increase it.

Tested to work in IE7, IE8, IE9, IE10, IE11, Firefox 30, Chrome 35, and Opera 22.

.htaccess redirect http to https

Insert this code in your .htaccess file. And it should work

RewriteCond %{HTTP_HOST} yourDomainName\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yourDomainName.com/$1 [R,L]

How to add a new project to Github using VS Code

Go to VS COde -> View -> Terminal

enter image description here

git init git add . git commit -m "FirstCommit" git remote add origin https://github.com/dotnetpiper/cdn git pull origin master git push -f origin master

Note : Some time git push -u origin master doesn't work anticipated.

Does svn have a `revert-all` command?

Use the recursive switch --recursive (-R)

svn revert -R .

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

in the new actionmailer, "razorengine" is a dependency. The latest version of Razorengine installs the dependency to System.Web.Razor 3.0.0.

If you use an earlier version in your application (i suppose you are using actionmailer in another project and that you reference the mail functionality from another project) than you get this issue of course.

In an earlier application, i had a webapplication MVC that uses system.web.Razor version 2.0.0. Of course, i got the issue to. How to fix? => Simple!

  1. Just uninstall the entire actionmailer in your actionmailer project.
  2. Install a previous version of RazorEngin

    Install-Package RazorEngine -Version 3.3.0 (because version 3.3.0 will reference system.web.razor 2.0.0)

  3. Install actionmailer again (it will not install the latest version of RazorEngin because you allready did that yourselve)
Succes!

How to import existing Android project into Eclipse?

You can also use Make new > General > Project, then import the project to that project directory

Macro to Auto Fill Down to last adjacent cell

ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

How does one Display a Hyperlink in React Native App?

The selected answer refers only to iOS. For both platforms, you can use the following component:

import React, { Component, PropTypes } from 'react';
import {
  Linking,
  Text,
  StyleSheet
} from 'react-native';

export default class HyperLink extends Component {

  constructor(){
      super();
      this._goToURL = this._goToURL.bind(this);
  }

  static propTypes = {
    url: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
  }

  render() {

    const { title} = this.props;

    return(
      <Text style={styles.title} onPress={this._goToURL}>
        >  {title}
      </Text>
    );
  }

  _goToURL() {
    const { url } = this.props;
    Linking.canOpenURL(url).then(supported => {
      if (supported) {
        Linking.openURL(this.props.url);
      } else {
        console.log('Don\'t know how to open URI: ' + this.props.url);
      }
    });
  }
}

const styles = StyleSheet.create({
  title: {
    color: '#acacac',
    fontWeight: 'bold'
  }
});

jQuery.click() vs onClick

Difference in works. If you use click(), you can add several functions, but if you use an attribute, only one function will be executed - the last one.

DEMO

HTML

<span id="JQueryClick">Click #JQuery</span> </br>
<span id="JQueryAttrClick">Click #Attr</span> </br>

JavaScript

$('#JQueryClick').click(function(){alert('1')})
$('#JQueryClick').click(function(){alert('2')})

$('#JQueryAttrClick').attr('onClick'," alert('1')" ) //This doesn't work
$('#JQueryAttrClick').attr('onClick'," alert('2')" )

If we are talking about performance, in any case directly using is always faster, but using of an attribute, you will be able to assign only one function.

Formatting code snippets for blogging on Blogger

It looks like there have been some changes with SyntaxHighlighter 2.0 that make it easier to use with Blogger.

There are hosted versions of the styles and Javascripts at: http://alexgorbatchev.com/pub/sh/

Filtering a list based on a list of booleans

With python 3 you can use list_a[filter] to get True values. To get False values use list_a[~filter]

Vuejs and Vue.set(), update array

EDIT 2

  • For all object changes that need reactivity use Vue.set(object, prop, value)
  • For array mutations, you can look at the currently supported list here

EDIT 1

For vuex you will want to do Vue.set(state.object, key, value)


Original

So just for others who come to this question. It appears at some point in Vue 2.* they removed this.items.$set(index, val) in favor of this.$set(this.items, index, val).

Splice is still available and here is a link to array mutation methods available in vue link.

What does "connection reset by peer" mean?

This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.

This can happen if the other side crashes and then comes back up or if it calls close() on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.

It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.

Can I inject a service into a directive in AngularJS?

You can also use the $inject service to get whatever service you like. I find that useful if I don't know the service name ahead of time but know the service interface. For example a directive that will plug a table into an ngResource end point or a generic delete-record button which interacts with any api end point. You don't want to re-implement the table directive for every controller or data-source.

template.html

<div my-directive api-service='ServiceName'></div>

my-directive.directive.coffee

angular.module 'my.module'
  .factory 'myDirective', ($injector) ->
    directive = 
      restrict: 'A'
      link: (scope, element, attributes) ->
        scope.apiService = $injector.get(attributes.apiService)

now your 'anonymous' service is fully available. If it is ngResource for example you can then use the standard ngResource interface to get your data

For example:

scope.apiService.query((response) ->
  scope.data = response
, (errorResponse) ->
  console.log "ERROR fetching data for service: #{attributes.apiService}"
  console.log errorResponse.data
)

I have found this technique to be very useful when making elements that interact with API endpoints especially.

show/hide a div on hover and hover out

Here are different method of doing this. And i found your code is even working fine.

Your code: http://jsfiddle.net/NKC2j/

Jquery toggle class demo: http://jsfiddle.net/NKC2j/2/

Jquery fade toggle: http://jsfiddle.net/NKC2j/3/

Jquery slide toggle: http://jsfiddle.net/NKC2j/4/

And you can do this with CSS as answered by Sandeep

Find unused code

Resharper is good for this like others have stated. Be careful though, these tools don't find you code that is used by reflection, e.g. cannot know if some code is NOT used by reflection.

What is lexical scope?

IBM defines it as:

The portion of a program or segment unit in which a declaration applies. An identifier declared in a routine is known within that routine and within all nested routines. If a nested routine declares an item with the same name, the outer item is not available in the nested routine.

Example 1:

function x() {
    /*
    Variable 'a' is only available to function 'x' and function 'y'.
    In other words the area defined by 'x' is the lexical scope of
    variable 'a'
    */
    var a = "I am a";

    function y() {
        console.log( a )
    }
    y();

}
// outputs 'I am a'
x();

Example 2:

function x() {

    var a = "I am a";

    function y() {
         /*
         If a nested routine declares an item with the same name,
         the outer item is not available in the nested routine.
         */
        var a = 'I am inner a';
        console.log( a )
    }
    y();

}
// outputs 'I am inner a'
x();

How to sort an STL vector?

A pointer-to-member allows you to write a single comparator, which can work with any data member of your class:

#include <algorithm>
#include <vector>
#include <string>
#include <iostream>

template <typename T, typename U>
struct CompareByMember {
    // This is a pointer-to-member, it represents a member of class T
    // The data member has type U
    U T::*field;
    CompareByMember(U T::*f) : field(f) {}
    bool operator()(const T &lhs, const T &rhs) {
        return lhs.*field < rhs.*field;
    }
};

struct Test {
    int a;
    int b;
    std::string c;
    Test(int a, int b, std::string c) : a(a), b(b), c(c) {}
};

// for convenience, this just lets us print out a Test object
std::ostream &operator<<(std::ostream &o, const Test &t) {
    return o << t.c;
}

int main() {
    std::vector<Test> vec;
    vec.push_back(Test(1, 10, "y"));
    vec.push_back(Test(2, 9, "x"));

    // sort on the string field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,std::string>(&Test::c));
    std::cout << "sorted by string field, c: ";
    std::cout << vec[0] << " " << vec[1] << "\n";

    // sort on the first integer field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,int>(&Test::a));
    std::cout << "sorted by integer field, a: ";
    std::cout << vec[0] << " " << vec[1] << "\n";

    // sort on the second integer field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,int>(&Test::b));
    std::cout << "sorted by integer field, b: ";
    std::cout << vec[0] << " " << vec[1] << "\n";
}

Output:

sorted by string field, c: x y
sorted by integer field, a: y x
sorted by integer field, b: x y

Java Round up Any Number

int RoundedUp = (int) Math.ceil(RandomReal);

This seemed to do the perfect job. Worked everytime.

Datetime in C# add days

Its because the AddDays() method returns a new DateTime, that you are not assigning or using anywhere.

Example of use:

DateTime newDate = endDate.AddDays(2);

How to insert default values in SQL table?

To insert the default values you should omit them something like this :

Insert into Table (Field2) values(5)

All other fields will have null or their default values if it has defined.

Unexpected character encountered while parsing value

I faced similar error message in Xamarin forms when sending request to webApi to get a Token,

  • Make sure all keys (key : value) (ex.'username', 'password', 'grant_type') in the Json file are exactly what the webApi expecting, otherwise it fires this exception.

Unhandled Exception: Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0

Border around each cell in a range

You can also include this task within another macro, without opening a new one:

I don't put Sub and end Sub, because the macro contains much longer code, as per picture below

With Sheets("1_PL").Range("EF1631:JJ1897")
    With .Borders
    .LineStyle = xlContinuous
    .Color = vbBlack
    .Weight = xlThin
    End With
[![enter image description here][1]][1]End With

How do I set Java's min and max heap size through environment variables?

You can't do it using environment variables directly. You need to use the set of "non standard" options that are passed to the java command. Run: java -X for details. The options you're looking for are -Xmx and -Xms (this is "initial" heap size, so probably what you're looking for.)

Some products like Ant or Tomcat might come with a batch script that looks for the JAVA_OPTS environment variable, but it's not part of the Java runtime. If you are using one of those products, you may be able to set the variable like:

set JAVA_OPTS="-Xms128m -Xmx256m"  

You can also take this approach with your own command line like:

set JAVA_OPTS="-Xms128m -Xmx256m"  
java ${JAVA_OPTS} MyClass

jQuery.active function

This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache (where all of jQuery.data() goes).

I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart() and $.ajaxStop() (which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.


When jQuery starts an AJAX request, this happens:

if ( s.global && ! jQuery.active++ ) {
  jQuery.event.trigger( "ajaxStart" );
}

This is what causes the $.ajaxStart() event to fire, the number of connections just went from 0 to 1 (jQuery.active++ isn't 0 after this one, and !0 == true), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend abort via return false or an ajax call complete function runs):

if ( s.global && ! --jQuery.active ) {
  jQuery.event.trigger( "ajaxStop" );
}

This is what causes the $.ajaxStop() event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.

Replace the single quote (') character from a string

As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ("'") or you can escape it inside single quotes ('\'').

To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:

>>> "didn't".replace("'", "")
'didnt'

TabLayout tab selection

A bit late but might be a useful solution. I am using my TabLayout directly in my Fragment and trying to select a tab quite early in the Fragment's Lifecycle. What worked for me was to wait until the TabLayout finished drawing its child views by using android.view.View#post method. i.e:

int myPosition = 0;
myFilterTabLayout.post(() -> { filterTabLayout.getTabAt(myPosition).select(); });

Autowiring two beans implementing same interface - how to set default bean to autowire?

The use of @Qualifier will solve the issue.
Explained as below example : 
public interface PersonType {} // MasterInterface

@Component(value="1.2") 
public class Person implements  PersonType { //Bean implementing the interface
@Qualifier("1.2")
    public void setPerson(PersonType person) {
        this.person = person;
    }
}

@Component(value="1.5")
public class NewPerson implements  PersonType { 
@Qualifier("1.5")
    public void setNewPerson(PersonType newPerson) {
        this.newPerson = newPerson;
    }
}

Now get the application context object in any component class :

Object obj= BeanFactoryAnnotationUtils.qualifiedBeanOfType((ctx).getAutowireCapableBeanFactory(), PersonType.class, type);//type is the qualifier id

you can the object of class of which qualifier id is passed.

case statement in SQL, how to return multiple variables?

Depending on your use case, instead of using a case statement, you can use the union of multiple select statements, one for each condition.

My goal when I found this question was to select multiple columns conditionally. I didn't necessarily need the case statement, so this is what I did.

For example:

  SELECT
    a1,
    a2,
    a3,
    ...
  WHERE <condition 1>
    AND (<other conditions>)
  UNION
  SELECT
    b1,
    b2,
    b3,
    ...
  WHERE <condition 2>
    AND (<other conditions>)
  UNION
  SELECT
  ...
-- and so on

Be sure that exactly one condition evaluates to true at a time.

I'm using Postgresql, and the query planner was smart enough to not run a select statement at all if the condition in the where clause evaluated to false (i.e. only one of the select statement actually runs), so this was also performant for me.

How do I modify fields inside the new PostgreSQL JSON datatype?

To build upon @pozs's answers, here are a couple more PostgreSQL functions which may be useful to some. (Requires PostgreSQL 9.3+)

Delete By Key: Deletes a value from JSON structure by key.

CREATE OR REPLACE FUNCTION "json_object_del_key"(
  "json"          json,
  "key_to_del"    TEXT
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT CASE
  WHEN ("json" -> "key_to_del") IS NULL THEN "json"
  ELSE (SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')
          FROM (SELECT *
                  FROM json_each("json")
                 WHERE "key" <> "key_to_del"
               ) AS "fields")::json
END
$function$;

Recursive Delete By Key: Deletes a value from JSON structure by key-path. (requires @pozs's json_object_set_key function)

CREATE OR REPLACE FUNCTION "json_object_del_path"(
  "json"          json,
  "key_path"      TEXT[]
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT CASE
  WHEN ("json" -> "key_path"[l] ) IS NULL THEN "json"
  ELSE
     CASE COALESCE(array_length("key_path", 1), 0)
         WHEN 0 THEN "json"
         WHEN 1 THEN "json_object_del_key"("json", "key_path"[l])
         ELSE "json_object_set_key"(
           "json",
           "key_path"[l],
           "json_object_del_path"(
             COALESCE(NULLIF(("json" -> "key_path"[l])::text, 'null'), '{}')::json,
             "key_path"[l+1:u]
           )
         )
       END
    END
  FROM array_lower("key_path", 1) l,
       array_upper("key_path", 1) u
$function$;

Usage examples:

s1=# SELECT json_object_del_key ('{"hello":[7,3,1],"foo":{"mofu":"fuwa", "moe":"kyun"}}',
                                 'foo'),
            json_object_del_path('{"hello":[7,3,1],"foo":{"mofu":"fuwa", "moe":"kyun"}}',
                                 '{"foo","moe"}');

 json_object_del_key |          json_object_del_path
---------------------+-----------------------------------------
 {"hello":[7,3,1]}   | {"hello":[7,3,1],"foo":{"mofu":"fuwa"}}

SSH to Elastic Beanstalk instance

On mac you can install the cli using brew:

brew install awsebcli

With the command line tool you can then ssh with:

eb ssh environment-name

and also do other operations. This assumes you have added a security group that allows ssh from your ip.

How should I use Outlook to send code snippets?

Here's what works for me, and is quickest and causes the least amount of pain / annoyance:

1) Paste you code snippet into sublime; make sure your syntax is looking good.

2) Right click and choose 'Copy as RTF'

3) Paste into your email

4) Done

presentViewController and displaying navigation bar

try this

     let transition: CATransition = CATransition()
    let timeFunc : CAMediaTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    transition.duration = 1
    transition.timingFunction = timeFunc
    transition.type = kCATransitionPush
    transition.subtype = kCATransitionFromRight
    self.view.window!.layer.addAnimation(transition, forKey: kCATransition)
    self.presentViewController(vc, animated:true, completion:nil)

Combine two columns of text in pandas dataframe

if both columns are strings, you can concatenate them directly:

df["period"] = df["Year"] + df["quarter"]

If one (or both) of the columns are not string typed, you should convert it (them) first,

df["period"] = df["Year"].astype(str) + df["quarter"]

Beware of NaNs when doing this!


If you need to join multiple string columns, you can use agg:

df['period'] = df[['Year', 'quarter', ...]].agg('-'.join, axis=1)

Where "-" is the separator.

How to get scrollbar position with Javascript?

You can use element.scrollTop and element.scrollLeft to get the vertical and horizontal offset, respectively, that has been scrolled. element can be document.body if you care about the whole page. You can compare it to element.offsetHeight and element.offsetWidth (again, element may be the body) if you need percentages.

Ansible - read inventory hosts and variables to group_vars/all file

If you want to refer one host define under /etc/ansible/host in a task or role, the bellow link might help:

https://www.middlewareinventory.com/blog/ansible-get-ip-address/

What is the easiest way to encrypt a password when I save it to the registry?

..NET provides cryptographics services in class contained in the System.Security.Cryptography namespace.

How to use querySelectorAll only for elements that have a specific attribute set?

With your example:

<input type="checkbox" id="c2" name="c2" value="DE039230952"/>

Replace $$ with document.querySelectorAll in the examples:

$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230

Use the examples directly with:

const $$ = document.querySelectorAll.bind(document);

Some additions:

$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Hendry's answer is 100% correct. I had the same problem with my application, where there is repository project dealing with database with use of methods encapsulating EF db context operation. Other projects use this repository, and I don't want to reference EF in those projects. Somehow I don't feel it's proper, I need EF only in repository project. Anyway, copying EntityFramework.SqlServer.dll to other project output directory solves the problem. To avoid problems, when you forget to copy this dll, you can change repository build directory. Go to repository project's properties, select Build tab, and in output section you can set output directory to other project's build directory. Sure, it's just workaround. Maybe the hack, mentioned in some placec, is better:

var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance;

Still, for development purposes it is enough. Later, when preparing install or publish, you can add this file to package.

I'm quite new to EF. Is there any better method to solve this issue? I don't like "hack" - it makes me feel that there is something that is "not secure".

Echo newline in Bash prints literal \n

I just use echo no arguments

echo "Hello"
echo
echo "World"

How to get the GL library/headers?

In Visual Studio :

//OpenGL
#pragma comment(lib, "opengl32")
#pragma comment(lib, "glu32")
#include <gl/gl.h>
#include <gl/glu.h>

Headers are in the SDK : C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\gl

What is the difference between a string and a byte string?

The only thing that a computer can store is bytes.

To store anything in a computer, you must first encode it, i.e. convert it to bytes. For example:

  • If you want to store music, you must first encode it using MP3, WAV, etc.
  • If you want to store a picture, you must first encode it using PNG, JPEG, etc.
  • If you want to store text, you must first encode it using ASCII, UTF-8, etc.

MP3, WAV, PNG, JPEG, ASCII and UTF-8 are examples of encodings. An encoding is a format to represent audio, images, text, etc in bytes.

In Python, a byte string is just that: a sequence of bytes. It isn't human-readable. Under the hood, everything must be converted to a byte string before it can be stored in a computer.

On the other hand, a character string, often just called a "string", is a sequence of characters. It is human-readable. A character string can't be directly stored in a computer, it has to be encoded first (converted into a byte string). There are multiple encodings through which a character string can be converted into a byte string, such as ASCII and UTF-8.

'I am a string'.encode('ASCII')

The above Python code will encode the string 'I am a string' using the encoding ASCII. The result of the above code will be a byte string. If you print it, Python will represent it as b'I am a string'. Remember, however, that byte strings aren't human-readable, it's just that Python decodes them from ASCII when you print them. In Python, a byte string is represented by a b, followed by the byte string's ASCII representation.

A byte string can be decoded back into a character string, if you know the encoding that was used to encode it.

b'I am a string'.decode('ASCII')

The above code will return the original string 'I am a string'.

Encoding and decoding are inverse operations. Everything must be encoded before it can be written to disk, and it must be decoded before it can be read by a human.

Squash the first two commits in Git?

I've reworked VonC's script to do everything automatically and not ask me for anything. You give it two commit SHA1s and it will squash everything between them into one commit named "squashed history":

#!/bin/sh
# Go back to the last commit that we want
# to form the initial commit (detach HEAD)
git checkout $2

# reset the branch pointer to the initial commit (= $1),
# but leaving the index and working tree intact.
git reset --soft $1

# amend the initial tree using the tree from $2
git commit --amend -m "squashed history"

# remember the new commit sha1
TARGET=`git rev-list HEAD --max-count=1`

# go back to the original branch (assume master for this example)
git checkout master

# Replay all the commits after $2 onto the new initial commit
git rebase --onto $TARGET $2

nodemon not found in npm

under your current project directory, run

npm install nodemon --save //save in package.json so that the following code cam find your nodemon

then under "scripts" in your package.json file, add "start": "nodemon app.js" (or whatever your entry point is)
so it looks like this:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
}

and then run

npm start

That avoids complicate PATH settings and it works on my mac
hope can help you ;)

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

Html.Label gives you a label for an input whose name matches the specified input text (more specifically, for the model property matching the string expression):

// Model
public string Test { get; set; }

// View
@Html.Label("Test")

// Output
<label for="Test">Test</label>

Html.LabelFor gives you a label for the property represented by the provided expression (typically a model property):

// Model
public class MyModel
{
    [DisplayName("A property")]
    public string Test { get; set; }
}

// View
@model MyModel
@Html.LabelFor(m => m.Test)

// Output
<label for="Test">A property</label>

Html.LabelForModel is a bit trickier. It returns a label whose for value is that of the parameter represented by the model object. This is useful, in particular, for custom editor templates. For example:

// Model
public class MyModel
{
    [DisplayName("A property")]
    public string Test { get; set; }
}

// Main view
@Html.EditorFor(m => m.Test)

// Inside editor template
@Html.LabelForModel()

// Output
<label for="Test">A property</label>

Use URI builder in Android or create URL with variables

Excellent answer from above turned into a simple utility method.

private Uri buildURI(String url, Map<String, String> params) {

    // build url with parameters.
    Uri.Builder builder = Uri.parse(url).buildUpon();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.appendQueryParameter(entry.getKey(), entry.getValue());
    }

    return builder.build();
}

Count occurrences of a char in a string using Bash

I would use the following awk command:

string="text,text,text,text"
char=","
awk -F"${char}" '{print NF-1}' <<< "${string}"

I'm splitting the string by $char and print the number of resulting fields minus 1.

If your shell does not support the <<< operator, use echo:

echo "${string}" | awk -F"${char}" '{print NF-1}'

Eclipse shows errors but I can't find them

If you see the error in problem panel it will say : Description Resource Path Location Type Project configuration is not up-to-date with pom.xml. Select: Maven->Update Project... from the project context menu or use Quick Fix.

Solution : Right click on project > select : Maven->Update Project

Error gone.

Cannot start MongoDB as a service

These are the steps I followed to install mongoDB on windows 7

  1. download the .msi file from the mongodb site--> https://www.mongodb.com/download-center?jmp=nav#community and run it

  2. Wherever your mondoDb is downloaded (generally in the c drive Program Files folder), go to that folder and wherever is the bin folder in that same folder create your data folder and your log folder

3.Inside your data folder create your db folder

The structure would look something like this

  1. Now open command prompt as administrator.

  2. change your file path and enter the bin folder.( in this case it would be c>program files>MongoDB>bin> )

  3. Type in the following command : mongod --directoryperdb --dbpath "C:/Program Files\MongoDB\data" --logpath "C:\Program Files\MongoDB\log\mongo.log" --logappend --rest --install

  4. This would set the logpath and database path. Lastly run net start MongoDB . Hope this helps.

Leave menu bar fixed on top when scrolled

This effect is typically achieved by having some jquery logic as follows:

$(window).bind('scroll', function () {
    if ($(window).scrollTop() > 50) {
        $('.menu').addClass('fixed');
    } else {
        $('.menu').removeClass('fixed');
    }
});

This says once the window has scrolled past a certain number of vertical pixels, it adds a class to the menu that changes it's position value to "fixed".

For complete implementation details see: http://jsfiddle.net/adamb/F4BmP/

How to use NSJSONSerialization

NOTE: For Swift 3. Your JSON String is returning Array instead of Dictionary. Please try out the following:

        //Your JSON String to be parsed
        let jsonString = "[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";

        //Converting Json String to NSData
        let data = jsonString.data(using: .utf8)

        do {

            //Parsing data & get the Array
            let jsonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [AnyObject]

            //Print the whole array object
            print(jsonData)

            //Get the first object of the Array
            let firstPerson = jsonData[0] as! [String:Any]

            //Looping the (key,value) of first object
            for (key, value) in firstPerson {
                //Print the (key,value)
                print("\(key) - \(value) ")
            }

        } catch let error as NSError {
            //Print the error
            print(error)
        }

What is the cleanest way to get the progress of JQuery ajax request?

jQuery has already implemented promises, so it's better to use this technology and not move events logic to options parameter. I made a jQuery plugin that adds progress promise and now it's easy to use just as other promises:

$.ajax(url)
  .progress(function(){
    /* do some actions */
  })
  .progressUpload(function(){
    /* do something on uploading */
  });

Check it out at github

How do I uninstall a package installed using npm link?

"npm install" replaces all dependencies in your node_modules installed with "npm link" with versions from npmjs (specified in your package.json)

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

Split into train test and valid

x =np.expand_dims(np.arange(100), -1)


print(x)

indices = np.random.permutation(x.shape[0])

training_idx, test_idx, val_idx = indices[:int(x.shape[0]*.9)], indices[int(x.shape[0]*.9):int(x.shape[0]*.95)],  indices[int(x.shape[0]*.9):int(x.shape[0]*.95)]


training, test, val = x[training_idx,:], x[test_idx,:], x[val_idx,:]

print(training, test, val)

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

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

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

Please look at below code:

public interface InterfaceA {
  public void print();
}


public interface InterfaceB {
  public int print();
}

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

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

So it goes haywire for compiler.

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

Python dictionary replace values

via dict.update() function

In case you need a declarative solution, you can use dict.update() to change values in a dict.

Either like this:

my_dict.update({'key1': 'value1', 'key2': 'value2'})

or like this:

my_dict.update(key1='value1', key2='value2')

via dictionary unpacking

Since Python 3.5 you can also use dictionary unpacking for this:

my_dict = { **my_dict, 'key1': 'value1', 'key2': 'value2'}

Note: This creates a new dictionary.

via merge operator or update operator

Since Python 3.9 you can also use the merge operator on dictionaries:

my_dict = my_dict | {'key1': 'value1', 'key2': 'value2'}

Note: This creates a new dictionary.

Or you can use the update operator:

my_dict |= {'key1': 'value1', 'key2': 'value2'}

What is stdClass in PHP?

stdClass is a another great PHP feature. You can create a anonymous PHP class. Lets check an example.

$page=new stdClass();
$page->name='Home';
$page->status=1;

now think you have a another class that will initialize with a page object and execute base on it.

<?php
class PageShow {

    public $currentpage;

    public function __construct($pageobj)
    {
        $this->currentpage = $pageobj;
    }

    public function show()
    {
        echo $this->currentpage->name;
        $state = ($this->currentpage->status == 1) ? 'Active' : 'Inactive';
        echo 'This is ' . $state . ' page';
    }
}

Now you have to create a new PageShow object with a Page Object.

Here no need to write a new Class Template for this you can simply use stdClass to create a Class on the fly.

    $pageview=new PageShow($page);
    $pageview->show();

Is it possible to capture the stdout from the sh DSL command in the pipeline

A short version would be:

echo sh(script: 'ls -al', returnStdout: true).result

Reading Datetime value From Excel sheet

Alternatively, if your cell is already a real date, just use .Value instead of .Value2:

excelApp.Range[namedRange].Value
{21/02/2013 00:00:00}
    Date: {21/02/2013 00:00:00}
    Day: 21
    DayOfWeek: Thursday
    DayOfYear: 52
    Hour: 0
    Kind: Unspecified
    Millisecond: 0
    Minute: 0
    Month: 2
    Second: 0
    Ticks: 634970016000000000
    TimeOfDay: {00:00:00}
    Year: 2013

excelApp.Range[namedRange].Value2
41326.0

Apply CSS styles to an element depending on its child elements

In my case, I had to change the cell padding of an element that contained an input checkbox for a table that's being dynamically rendered with DataTables:

<td class="dt-center">
    <input class="a" name="constCheck" type="checkbox" checked="">
</td>

After implementing the following line code within the initComplete function I was able to produce the correct padding, which fixed the rows from being displayed with an abnormally large height

 $('tbody td:has(input.a)').css('padding', '0px');

Now, you can see that the correct styles are being applied to the parent element:

<td class=" dt-center" style="padding: 0px;">
    <input class="a" name="constCheck" type="checkbox" checked="">
</td>

Essentially, this answer is an extension of @KP's answer, but the more collaboration of implementing this the better. In summation, I hope this helps someone else because it works! Lastly, thank you so much @KP for leading me in the right direction!

Stop node.js program from command line

You can use fuser to get what you want to be done.

In order to obtain the process ids of the tasks running on a port you can do:

fuser <<target_port>>/tcp

Let's say the port is 8888, the command becomes:

fuser 8888/tcp

And to kill a process that is running on a port, simply add -k switch.

fuser <<target_port>>/tcp -k

Example (port is 8888):

fuser 8888/tcp -k

That's it! It will close the process listening on the port. I usually do this before running my server application.

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

How to store .pdf files into MySQL as BLOBs using PHP?

In regards to Gordon M's answer above, the 1st and 2nd parameter in mysqli_real_escape_string () call should be swapped for the newer php versions, according to: http://php.net/manual/en/mysqli.real-escape-string.php

Java Ordered Map

I have used Simple Hash map, linked list and Collections to sort a Map by values.

import java.util.*;
import java.util.Map.*;
public class Solution {

    public static void main(String[] args) {
        // create a simple hash map and insert some key-value pairs into it
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("Python", 3);
        map.put("C", 0);
        map.put("JavaScript", 4);
        map.put("C++", 1);
        map.put("Golang", 5);
        map.put("Java", 2);
        // Create a linked list from the above map entries
        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
        // sort the linked list using Collections.sort()
        Collections.sort(list, new Comparator<Entry<String, Integer>>(){
        @Override
         public int compare(Entry<String, Integer> m1, Entry<String, Integer> m2) {
        return m1.getValue().compareTo(m2.getValue());
        }
      });
      for(Entry<String, Integer> value: list) {
         System.out.println(value);
     }
   }
}

The output is:

C=0
C++=1
Java=2
Python=3
JavaScript=4
Golang=5

How do I replace text in a selection?

  1. Select the item you want to replace (double-click it, or Ctrl - F to find it)...

  2. Then do a (Ctrl - Apple - G) on Mac (aka. "Quick Find All"), to HIGHLIGHT all occurrences of the string at once.

  3. Now just TYPE your replacement text directly... All selection occurrences will be replaced as you type (as if your cursor was in multiple places at once!)

Very handy...

Use a cell value in VBA function with a variable

VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.

Dim val1 As Integer, val2 As Integer, i As Integer

For i = 1 To 333

  Sheets("Feuil2").Activate
  ActiveSheet.Cells(i, 1).Select

    val1 = Cells(i, 1).Value
    val2 = Cells(i, 2).Value

Sheets("Classeur2.csv").Select
Cells(val1, val2).Select

ActiveCell.FormulaR1C1 = "1"

Next i

What is the difference between null and undefined in JavaScript?

null and undefined are both are used to represent the absence of some value.

var a = null;

a is initialized and defined.

typeof(a)
//object

null is an object in JavaScript

Object.prototype.toString.call(a) // [object Object]

var b;

b is undefined and uninitialized

undefined object properties are also undefined. For example "x" is not defined on object c and if you try to access c.x, it will return undefined.

Generally we assign null to variables not undefined.

Java :Add scroll into text area

My naive assumption was that the size of scroll pane will be determined automatically...

The only solution that actually worked for me was explicitly seeting bounds of JScrollPane:

import javax.swing.*;

public class MyFrame extends JFrame {

    public MyFrame()
    {
        setBounds(100, 100, 491, 310);
        getContentPane().setLayout(null);

        JTextArea textField = new JTextArea();
        textField.setEditable(false);

        String str = "";
        for (int i = 0; i < 50; ++i)
            str += "Some text\n";
        textField.setText(str);

        JScrollPane scroll = new JScrollPane(textField);
        scroll.setBounds(10, 11, 455, 249);                     // <-- THIS

        getContentPane().add(scroll);
        setLocationRelativeTo ( null );
    }
}

Maybe it will help some future visitors :)

Vim autocomplete for Python

Try Jedi! There's a Vim plugin at https://github.com/davidhalter/jedi-vim.

It works just much better than anything else for Python in Vim. It even has support for renaming, goto, etc. The best part is probably that it really tries to understand your code (decorators, generators, etc. Just look at the feature list).

How to display 3 buttons on the same line in css

This will serve the purpose. There is no need for any divs or paragraph. If you want the spaces between them to be specified, use margin-left or margin-right in the css classes.

<div style="width:500px;">
    <button type="submit" class="msgBtn" onClick="return false;" >Save</button>
    <button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
    <button class="msgBtnBack">Back</button>
</div> 

Maven: add a folder or jar file into current classpath

The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
  <compilerArgs>
     <arg>-cp</arg>
     <arg>${cp}:${basedir}/lib/bad.jar</arg>
  </compilerArgs>
</configuration>

I used the gmavenplus-plugin to read the path and create the property 'cp':

      <plugin>
    <!--
      Use Groovy to read classpath and store into
      file named value of property <cpfile>

      In second step use Groovy to read the contents of
      the file into a new property named <cp>

      In the compiler plugin this is used to create a
      valid classpath
    -->
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.12.0</version>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <!-- any version of Groovy \>= 1.5.0 should work here -->
        <version>3.0.6</version>
        <type>pom</type>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    <executions>
      <execution>
        <id>read-classpath</id>
        <phase>validate</phase>
        <goals>
          <goal>execute</goal>
        </goals>
      </execution>

    </executions>
    <configuration>
      <scripts>
        <script><![CDATA[
                def file = new File(project.properties.cpfile)
                /* create a new property named 'cp'*/
                project.properties.cp = file.getText()
                println '<<< Retrieving classpath into new property named <cp> >>>'
                println 'cp = ' + project.properties.cp
              ]]></script>
      </scripts>
    </configuration>
  </plugin>

Java Look and Feel (L&F)

Heres the code that creates a Dialog which allows the user of your application to change the Look And Feel based on the user's systems. Alternatively, if you can store the wanted Look And Feel's on your application, then they could be "portable", which is the desired result.

   public void changeLookAndFeel() {

        List<String> lookAndFeelsDisplay = new ArrayList<>();
        List<String> lookAndFeelsRealNames = new ArrayList<>();

        for (LookAndFeelInfo each : UIManager.getInstalledLookAndFeels()) {
            lookAndFeelsDisplay.add(each.getName());
            lookAndFeelsRealNames.add(each.getClassName());
        }

        String changeLook = (String) JOptionPane.showInputDialog(this, "Choose Look and Feel Here:", "Select Look and Feel", JOptionPane.QUESTION_MESSAGE, null, lookAndFeelsDisplay.toArray(), null);

        if (changeLook != null) {
            for (int i = 0; i < lookAndFeelsDisplay.size(); i++) {
                if (changeLook.equals(lookAndFeelsDisplay.get(i))) {
                    try {
                        UIManager.setLookAndFeel(lookAndFeelsRealNames.get(i));
                        break;
                    }
                    catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        err.println(ex);
                        ex.printStackTrace(System.err);
                    }
                }
            }
        }
    }

Android ADB stop application command like "force-stop" for non rooted device

The first way
Needs root

Use kill:

adb shell ps => Will list all running processes on the device and their process ids
adb shell kill <PID> => Instead of <PID> use process id of your application

The second way
In Eclipse open DDMS perspective.
In Devices view you will find all running processes.
Choose the process and click on Stop.

enter image description here

The third way
It will kill only background process of an application.

adb shell am kill [options] <PACKAGE> => Kill all processes associated with (the app's package name). This command kills only processes that are safe to kill and that will not impact the user experience.
Options are:

--user | all | current: Specify user whose processes to kill; all users if not specified.

The fourth way
Needs root

adb shell pm disable <PACKAGE> => Disable the given package or component (written as "package/class").

The fifth way
Note that run-as is only supported for apps that are signed with debug keys.

run-as <package-name> kill <pid>

The sixth way
Introduced in Honeycomb

adb shell am force-stop <PACKAGE> => Force stop everything associated with (the app's package name).

P.S.: I know that the sixth method didn't work for you, but I think that it's important to add this method to the list, so everyone will know it.

Convert NVARCHAR to DATETIME in SQL Server 2008

What you exactly wan't to do ?. To change Datatype of column you can simple use alter command as

ALTER TABLE table_name ALTER COLUMN LoginDate DateTime;

But remember there should valid Date only in this column however data-type is nvarchar.

If you wan't to convert data type while fetching data then you can use CONVERT function as,

CONVERT(data_type(length),expression,style)

eg:

SELECT CONVERT(DateTime, loginDate, 6)

This will return 29 AUG 13. For details about CONVERT function you can visit ,

http://www.w3schools.com/sql/func_convert.asp.

Remember, Always use DataTime data type for DateTime column.

Thank You

On a CSS hover event, can I change another div's styling?

A pure solution without jQuery:

Javascript (Head)

function chbg(color) {
    document.getElementById('b').style.backgroundColor = color;
}   

HTML (Body)

<div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">This is element a</div>
<div id="b">This is element b</div>

JSFiddle: http://jsfiddle.net/YShs2/

how can I login anonymously with ftp (/usr/bin/ftp)?

Anonymous ftp logins are usually the username 'anonymous' with the user's email address as the password. Some servers parse the password to ensure it looks like an email address.

User:  anonymous
Password:  [email protected]

REST API - Use the "Accept: application/json" HTTP Header

Here's a handy site to test out your headers. You can see your browser headers and also use cURL to reflect back whatever headers you send.

For example, you can validate the content negotiation like this.

This Accept header prefers plain text so returns in that format:-

$ curl -H "Accept: application/json;q=0.9,text/plain" http://gethttp.info/Accept
application/json;q=0.9,text/plain

Whereas this one prefers JSON and so returns in that format:-

$ curl -H "Accept: application/json,text/*;q=0.99" http://gethttp.info/Accept
{
   "Accept": "application/json,text/*;q=0.99"
}

Server returned HTTP response code: 401 for URL: https

401 means "Unauthorized", so there must be something with your credentials.

I think that java URL does not support the syntax you are showing. You could use an Authenticator instead.

Authenticator.setDefault(new Authenticator() {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {          
        return new PasswordAuthentication(login, password.toCharArray());
    }
});

and then simply invoking the regular url, without the credentials.

The other option is to provide the credentials in a Header:

String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);

PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

For whatever reason, TWO of my solutions have web projects that spontaneously uninstalled asp.net MVC somehow. I installed it from Nuget and now they both work again. This happened after a recent batch of windows updates that included .net framework updates for the version I was using (4.5.1).

Edit: From the .Net Web Development and Tools Blog:

Microsoft Asp.Net MVC Security Update MS14-059 broke my build!

Get the Selected value from the Drop down box in PHP

Posting it from my project.

<select name="parent" id="parent"><option value="0">None</option>
<?php
 $select="select=selected";
 $allparent=mysql_query("select * from tbl_page_content where parent='0'");
 while($parent=mysql_fetch_array($allparent))
   {?>
   <option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
  <?php 
   }
  ?></select>

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

Interface vs Abstract Class (general OO)

By implementing interfaces you are achieving composition ("has-a" relationships) instead of inheritance ("is-a" relationships). That is an important principle to remember when it comes to things like design patterns where you need to use interfaces to achieve a composition of behaviors instead of an inheritance.

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

Validating a Textbox field for only numeric input.

To check if the value is a double:

private void button1_Click(object sender, EventArgs e)
{

    if (!double.TryParse(textBox1.Text, out var x))
    {
        System.Console.WriteLine("it's not a double ");
        return;
    }
    System.Console.WriteLine("it's a double ");
}

How to retrieve the dimensions of a view?

CORRECTION: I found out that the above solution is terrible. Especially when your phone is slow. And here, I found another solution: calculate out the px value of the element, including the margins and paddings: dp to px: https://stackoverflow.com/a/6327095/1982712

or dimens.xml to px: https://stackoverflow.com/a/16276351/1982712

sp to px: https://stackoverflow.com/a/9219417/1982712 (reverse the solution)

or dimens to px: https://stackoverflow.com/a/16276351/1982712

and that's it.

Pytorch tensor to numpy array

Your question is very poorly worded. Your code (sort of) already does what you want. What exactly are you confused about? x.numpy() answer the original title of your question:

Pytorch tensor to numpy array

you need improve your question starting with your title.

Anyway, just in case this is useful to others. You might need to call detach for your code to work. e.g.

RuntimeError: Can't call numpy() on Variable that requires grad.

So call .detach(). Sample code:

# creating data and running through a nn and saving it

import torch
import torch.nn as nn

from pathlib import Path
from collections import OrderedDict

import numpy as np

path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)

num_samples = 3
Din, Dout = 1, 1
lb, ub = -1, 1

x = torch.torch.distributions.Uniform(low=lb, high=ub).sample((num_samples, Din))

f = nn.Sequential(OrderedDict([
    ('f1', nn.Linear(Din,Dout)),
    ('out', nn.SELU())
]))
y = f(x)

# save data
y.numpy()
x_np, y_np = x.detach().cpu().numpy(), y.detach().cpu().numpy()
np.savez(path / 'db', x=x_np, y=y_np)

print(x_np)

cpu goes after detach. See: https://discuss.pytorch.org/t/should-it-really-be-necessary-to-do-var-detach-cpu-numpy/35489/5


Also I won't make any comments on the slicking since that is off topic and that should not be the focus of your question. See this:

Understanding slice notation

Angular + Material - How to refresh a data source (mat-table)

There are two ways to do it because Angular Material is inconsistent, and this is very poorly documented. Angular material table won't update when a new row will arrive. Surprisingly it is told it is because performance issues. But it looks more like a by design issue, they can not change. It should be expected for the table to update when new row occurs. If this behavior should not be enabled by default there should be a switch to switch it off.

Anyways, we can not change Angular Material. But we can basically use a very poorly documented method to do it:

One - if you use an array directly as a source:

call table.renderRows()

where table is ViewChild of the mat-table

Second - if you use sorting and other features

table.renderRows() surprisingly won't work. Because mat-table is inconsistent here. You need to use a hack to tell the source changed. You do it with this method:

this.dataSource.data = yourDataSource;

where dataSource is MatTableDataSource wrapper used for sorting and other features.

How to add a WiX custom action that happens only on uninstall (via MSI)?

The biggest problem with a batch script is handling rollback when the user clicks cancel (or something goes wrong during your install). The correct way to handle this scenario is to create a CustomAction that adds temporary rows to the RemoveFiles table. That way the Windows Installer handles the rollback cases for you. It is insanely simpler when you see the solution.

Anyway, to have an action only execute during uninstall add a Condition element with:

REMOVE ~= "ALL"

the ~= says compare case insensitive (even though I think ALL is always uppercaesd). See the MSI SDK documentation about Conditions Syntax for more information.

PS: There has never been a case where I sat down and thought, "Oh, batch file would be a good solution in an installation package." Actually, finding an installation package that has a batch file in it would only encourage me to return the product for a refund.

Removing an activity from the history stack

I use this way.

Intent i = new Intent(MyOldActivity.this, MyNewActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(i);

How to add items to array in nodejs

Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:

var array = [];
calendars.forEach(function(item) {
    array.push(item.id);
});

console.log(array);

You can also use the map() method to generate an Array filled with the results of calling the specified function on each element. Something like:

var array = calendars.map(function(item) {
    return item.id;
});

console.log(array);

And, since ECMAScript 2015 has been released, you may start seeing examples using let or const instead of var and the => syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):

let array = calendars.map(item => item.id);
console.log(array);

jQuery Ajax simple call

You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
   var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    });
}

// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
    .success(function(data){
               // treat the READUSERS data returned
   })
    .fail(function(sender, message, details){
           alert("Sorry, something went wrong!");
  });

What is a 'multi-part identifier' and why can't it be bound?

I faced this problem and solved it but there is a difference between your and mine code. In spite of I think you can understand what is "the multi-part identifier could not be bound"

When I used this code

 select * from tbTest where email = [email protected]

I faced Multi-part identifier problem

but when I use single quotation for email address It solved

 select * from tbTest where email = '[email protected]'

Script for rebuilding and reindexing the fragmented index?

To rebuild use:

ALTER INDEX __NAME_OF_INDEX__ ON __NAME_OF_TABLE__ REBUILD

or to reorganize use:

ALTER INDEX __NAME_OF_INDEX__ ON __NAME_OF_TABLE__ REORGANIZE

Reorganizing should be used at lower (<30%) fragmentations but only rebuilding (which is heavier to the database) cuts the fragmentation down to 0%.
For further information see https://msdn.microsoft.com/en-us/library/ms189858.aspx

Check whether a path is valid

I haven't had any problems with the code below. (Relative paths must start with '/' or '\').

private bool IsValidPath(string path, bool allowRelativePaths = false)
{
    bool isValid = true;

    try
    {
        string fullPath = Path.GetFullPath(path);

        if (allowRelativePaths)
        {
            isValid = Path.IsPathRooted(path);
        }
        else
        {
            string root = Path.GetPathRoot(path);
            isValid = string.IsNullOrEmpty(root.Trim(new char[] { '\\', '/' })) == false;
        }
    }
    catch(Exception ex)
    {
        isValid = false;
    }

    return isValid;
}

For example these would return false:

IsValidPath("C:/abc*d");
IsValidPath("C:/abc?d");
IsValidPath("C:/abc\"d");
IsValidPath("C:/abc<d");
IsValidPath("C:/abc>d");
IsValidPath("C:/abc|d");
IsValidPath("C:/abc:d");
IsValidPath("");
IsValidPath("./abc");
IsValidPath("./abc", true);
IsValidPath("/abc");
IsValidPath("abc");
IsValidPath("abc", true);

And these would return true:

IsValidPath(@"C:\\abc");
IsValidPath(@"F:\FILES\");
IsValidPath(@"C:\\abc.docx\\defg.docx");
IsValidPath(@"C:/abc/defg");
IsValidPath(@"C:\\\//\/\\/\\\/abc/\/\/\/\///\\\//\defg");
IsValidPath(@"C:/abc/def~`!@#$%^&()_-+={[}];',.g");
IsValidPath(@"C:\\\\\abc////////defg");
IsValidPath(@"/abc", true);
IsValidPath(@"\abc", true);

Is there an easy way to convert jquery code to javascript?

Is there an easy way to convert jQuery code to regular javascript?

No, especially if:

understanding the examples of javascript solutions written in jQuery [is] hard.

JQuery and all the frameworks tend to make understanding the code easier. If that's difficult to understand, then vanilla javascript will be torture :)

Null & empty string comparison in Bash

fedorqui has a working solution but there is another way to do the same thing.

Chock if a variable is set

#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
    echo 'No, I am not!';
fi

Or to verify that a variable is empty

#!/bin/bash      
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
    echo 'Yes I am!';
fi

tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

If you are trying to loop over a cell array and apply something to each element in the cell, check out cellfun. There's also arrayfun, bsxfun, and structfun which may simplify your program.

Curl not recognized as an internal or external command, operable program or batch file

Method 1:\

add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables enter image description here

Method 2: (if method 1 not work then)

simple open command prompt with "run as administrator"

Java JDBC - How to connect to Oracle using Service Name instead of SID

You can also specify the TNS name in the JDBC URL as below

jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))

Disable html5 video autoplay

Try adding autostart="false" to your source tag.

<video width="640" height="480" controls="controls" type="video/mp4" preload="none">
<source src="http://example.com/mytestfile.mp4" autostart="false">
Your browser does not support the video tag.
</video>

JSFiddle example

How can I change the color of a Google Maps marker?

This relatively recent article provides a simple example with a limited Google Maps set of colored icons.

Getting The ASCII Value of a character in a C# string

This example might help you. by using simple casting you can get code behind urdu character.

string str = "?????";
        char ch = ' ';
        int number = 0;
        for (int i = 0; i < str.Length; i++)
        {
            ch = str[i];
            number = (int)ch;
            Console.WriteLine(number);
        }

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

If you need to both get the raw content from the request, but also need to use a bound model version of it in the controller, you will likely get this exception.

NotSupportedException: Specified method is not supported. 

For example, your controller might look like this, leaving you wondering why the solution above doesn't work for you:

public async Task<IActionResult> Index(WebhookRequest request)
{
    using var reader = new StreamReader(HttpContext.Request.Body);

    // this won't fix your string empty problems
    // because exception will be thrown
    reader.BaseStream.Seek(0, SeekOrigin.Begin); 
    var body = await reader.ReadToEndAsync();

    // Do stuff
}

You'll need to take your model binding out of the method parameters, and manually bind yourself:

public async Task<IActionResult> Index()
{
    using var reader = new StreamReader(HttpContext.Request.Body);

    // You shouldn't need this line anymore.
    // reader.BaseStream.Seek(0, SeekOrigin.Begin);

    // You now have the body string raw
    var body = await reader.ReadToEndAsync();

    // As well as a bound model
    var request = JsonConvert.DeserializeObject<WebhookRequest>(body);
}

It's easy to forget this, and I've solved this issue before in the past, but just now had to relearn the solution. Hopefully my answer here will be a good reminder for myself...

How to center a navigation bar with CSS or HTML?

Your nav div is actually centered correctly. But the ul inside is not. Give the ul a specific width and center that as well.

CSS: background-color only inside the margin

If your margin is set on the body, then setting the background color of the html tag should color the margin area

html { background-color: black; }
body { margin:50px; background-color: white; }

http://jsfiddle.net/m3zzb/

Or as dmackerman suggestions, set a margin of 0, but a border of the size you want the margin to be and set the border-color

Why does "npm install" rewrite package-lock.json?

Probably you should use something like this

npm ci

Instead of using npm install if you don't want to change the version of your package.

According to the official documentation, both npm install and npm ci install the dependencies which are needed for the project.

The main difference is, npm install does install the packages taking packge.json as a reference. Where in the case of npm ci, it does install the packages taking package-lock.json as a reference, making sure every time the exact package is installed.

git push rejected

If push request is shows Rejected, then try first pull from your github account and then try push.

Ex:

In my case it was giving an error-

 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/ashif8984/git-github.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

****So what I did was-****

$ git pull
$ git push

And the code was pushed successfully into my Github Account.

Sleep for milliseconds

#include <windows.h>

Syntax:

Sleep (  __in DWORD dwMilliseconds   );

Usage:

Sleep (1000); //Sleeps for 1000 ms or 1 sec

Problems with jQuery getJSON using local files in Chrome

Another way to do it is to start a local HTTP server on your directory. On Ubuntu and MacOs with Python installed, it's a one-liner.

Go to the directory containing your web files, and :

python -m SimpleHTTPServer

Then connect to http://localhost:8000/index.html with any web browser to test your page.

JQuery create a form and add elements to it programmatically

function setValToAssessment(id)
{

     $.getJSON("<?= URL.$param->module."/".$param->controller?>/setvalue",{id: id}, function(response)
     {
        var form = $('<form></form>').attr("id",'hiddenForm' ).attr("name", 'hiddenForm'); 
         $.each(response,function(key,value){
            $("<input type='text' value='"+value+"' >")
 .attr("id", key)
 .attr("name", key)
 .appendTo("form");


             });
              $('#hiddenForm').appendTo('body').submit();

        // window.location.href = "<?=URL.$param->module?>/assessment";
    });

}     

If Radio Button is selected, perform validation on Checkboxes

You must use the equals operator not the assignment like

if(document.form1.radio1[0].checked == true) {
    alert("You have selected Option 1");
}

Firefox and SSL: sec_error_unknown_issuer

Which version of Firefox on which platform is your client using?

The are people having the same problem as documented here in the Support Forum for Firefox. I hope you can find a solution there. Good luck!

Update:

Let your client check the settings in Firefox: On "Advanced" - "Encryption" there is a button "View Certificates". Look for "Comodo CA Limited" in the list. I saw that Comodo is the issuer of the certificate of that domain name/server. On two of my machines (FF 3.0.3 on Vista and Mac) the entry is in the list (by default/Mozilla).

alt text

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

what if you use

Map<String, ? extends Class<? extends Serializable>> expected = null;

How do you open an SDF file (SQL Server Compact Edition)?

Try the sql server management studio (version 2008 or earlier) from Microsoft. Download it from here. Not sure about the license, but it seems to be free if you download the EXPRESS EDITION.

You might also be able to use later editions of SSMS. For 2016, you will need to install an extension.

If you have the option you can copy the sdf file to a different machine which you are allowed to pollute with additional software.

Update: comment from Nick Westgate in nice formatting

The steps are not all that intuitive:

  1. Open SQL Server Management Studio, or if it's running select File -> Connect Object Explorer...
  2. In the Connect to Server dialog change Server type to SQL Server Compact Edition
  3. From the Database file dropdown select < Browse for more...>
  4. Open your SDF file.

What does the question mark and the colon (?: ternary operator) mean in objective-c?

Ternary operator example.If the value of isFemale boolean variable is YES, print "GENDER IS FEMALE" otherwise "GENDER IS MALE"

? means = execute the codes before the : if the condition is true. 
: means = execute the codes after the : if the condition is false.

Objective-C

BOOL isFemale = YES;
NSString *valueToPrint = (isFemale == YES) ? @"GENDER IS FEMALE" : @"GENDER IS MALE";
NSLog(valueToPrint); //Result will be "GENDER IS FEMALE" because the value of isFemale was set to YES.

For Swift

let isFemale = false
let valueToPrint:String = (isFemale == true) ? "GENDER IS FEMALE" : "GENDER IS MALE"
print(valueToPrint) //Result will be  "GENDER IS MALE" because the isFemale value was set to false.

Install windows service without InstallUtil.exe

This is a base service class (ServiceBase subclass) that can be subclassed to build a windows service that can be easily installed from the command line, without installutil.exe. This solution is derived from How to make a .NET Windows Service start right after the installation?, adding some code to get the service Type using the calling StackFrame

public abstract class InstallableServiceBase:ServiceBase
{

    /// <summary>
    /// returns Type of the calling service (subclass of InstallableServiceBase)
    /// </summary>
    /// <returns></returns>
    protected static Type getMyType()
    {
        Type t = typeof(InstallableServiceBase);
        MethodBase ret = MethodBase.GetCurrentMethod();
        Type retType = null;
        try
        {
            StackFrame[] frames = new StackTrace().GetFrames();
            foreach (StackFrame x in frames)
            {
                ret = x.GetMethod();

                Type t1 = ret.DeclaringType;

                if (t1 != null && !t1.Equals(t) &&   !t1.IsSubclassOf(t))
                {


                    break;
                }
                retType = t1;
            }
        }
        catch
        {

        }
        return retType;
    }
    /// <summary>
    /// returns AssemblyInstaller for the calling service (subclass of InstallableServiceBase)
    /// </summary>
    /// <returns></returns>
    protected static AssemblyInstaller GetInstaller()
    {
        Type t = getMyType();
        AssemblyInstaller installer = new AssemblyInstaller(
            t.Assembly, null);
        installer.UseNewContext = true;
        return installer;
    }

    private bool IsInstalled()
    {
        using (ServiceController controller =
            new ServiceController(this.ServiceName))
        {
            try
            {
                ServiceControllerStatus status = controller.Status;
            }
            catch
            {
                return false;
            }
            return true;
        }
    }

    private bool IsRunning()
    {
        using (ServiceController controller =
            new ServiceController(this.ServiceName))
        {
            if (!this.IsInstalled()) return false;
            return (controller.Status == ServiceControllerStatus.Running);
        }
    }
    /// <summary>
    /// protected method to be called by a public method within the real service
    /// ie: in the real service
    ///    new internal  void InstallService()
    ///    {
    ///        base.InstallService();
    ///    }
    /// </summary>
    protected void InstallService()
    {
        if (this.IsInstalled()) return;

        try
        {
            using (AssemblyInstaller installer = GetInstaller())
            {

                IDictionary state = new Hashtable();
                try
                {
                    installer.Install(state);
                    installer.Commit(state);
                }
                catch
                {
                    try
                    {
                        installer.Rollback(state);
                    }
                    catch { }
                    throw;
                }
            }
        }
        catch
        {
            throw;
        }
    }
    /// <summary>
    /// protected method to be called by a public method within the real service
    /// ie: in the real service
    ///    new internal  void UninstallService()
    ///    {
    ///        base.UninstallService();
    ///    }
    /// </summary>
    protected void UninstallService()
    {
        if (!this.IsInstalled()) return;

        if (this.IsRunning()) {
            this.StopService();
        }
        try
        {
            using (AssemblyInstaller installer = GetInstaller())
            {
                IDictionary state = new Hashtable();
                try
                {
                    installer.Uninstall(state);
                }
                catch
                {
                    throw;
                }
            }
        }
        catch
        {
            throw;
        }
    }

    private void StartService()
    {
        if (!this.IsInstalled()) return;

        using (ServiceController controller =
            new ServiceController(this.ServiceName))
        {
            try
            {
                if (controller.Status != ServiceControllerStatus.Running)
                {
                    controller.Start();
                    controller.WaitForStatus(ServiceControllerStatus.Running,
                        TimeSpan.FromSeconds(10));
                }
            }
            catch
            {
                throw;
            }
        }
    }

    private void StopService()
    {
        if (!this.IsInstalled()) return;
        using (ServiceController controller =
            new ServiceController(this.ServiceName))
        {
            try
            {
                if (controller.Status != ServiceControllerStatus.Stopped)
                {
                    controller.Stop();
                    controller.WaitForStatus(ServiceControllerStatus.Stopped,
                         TimeSpan.FromSeconds(10));
                }
            }
            catch
            {
                throw;
            }
        }
    }
}

All you have to do is to implement two public/internal methods in your real service:

    new internal  void InstallService()
    {
        base.InstallService();
    }
    new internal void UninstallService()
    {
        base.UninstallService();
    }

and then call them when you want to install the service:

    static void Main(string[] args)
    {
        if (Environment.UserInteractive)
        {
            MyService s1 = new MyService();
            if (args.Length == 1)
            {
                switch (args[0])
                {
                    case "-install":
                        s1.InstallService();

                        break;
                    case "-uninstall":

                        s1.UninstallService();
                        break;
                    default:
                        throw new NotImplementedException();
                }
            }


        }
        else {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new MyService() 
            };
            ServiceBase.Run(MyService);            
        }

    }

Can you use a trailing comma in a JSON object?

I usually loop over the array and attach a comma after every entry in the string. After the loop I delete the last comma again.

Maybe not the best way, but less expensive than checking every time if it's the last object in the loop I guess.

Writing a VLOOKUP function in vba

Have you tried:

Dim result As String 
Dim sheet As Worksheet 
Set sheet = ActiveWorkbook.Sheets("Data") 
result = Application.WorksheetFunction.VLookup(sheet.Range("AN2"), sheet.Range("AA9:AF20"), 5, False)

How do I format a string using a dictionary in python-3.x?

Is this good for you?

geopoint = {'latitude':41.123,'longitude':71.091}
print('{latitude} {longitude}'.format(**geopoint))

Sort array of objects by string property value

You may need to convert them to the lower case in order to prevent from confusion.

objs.sort(function (a,b) {

var nameA=a.last_nom.toLowerCase(), nameB=b.last_nom.toLowerCase()

if (nameA < nameB)
  return -1;
if (nameA > nameB)
  return 1;
return 0;  //no sorting

})

Sending emails through SMTP with PHPMailer

Try to send an e-mail through that SMTP server manually/from an interactive mailer (e.g. Mozilla Thunderbird). From the errors, it seems the server won't accept your credentials. Is that SMTP running on the port, or is it SSL+SMTP? You don't seem to be using secure connection in the code you've posted, and I'm not sure if PHPMailer actually supports SSL+SMTP.

(First result of googling your SMTP server's hostname: http://podpora.ebola.cz/idx.php/0/006/article/Strucny-technicky-popis-nastaveni-sluzeb.html seems to say "SMTPs mail sending: secure SSL connection,port: 465" . )

It looks like PHPMailer does support SSL; at least from this. So, you'll need to change this:

define('SMTP_SERVER', 'smtp.ebola.cz');

into this:

define('SMTP_SERVER', 'ssl://smtp.ebola.cz');

Passing an array as a function parameter in JavaScript

Note this

function FollowMouse() {
    for(var i=0; i< arguments.length; i++) {
        arguments[i].style.top = event.clientY+"px";
        arguments[i].style.left = event.clientX+"px";
    }

};

//---------------------------

html page

<body onmousemove="FollowMouse(d1,d2,d3)">

<p><div id="d1" style="position: absolute;">Follow1</div></p>
<div id="d2" style="position: absolute;"><p>Follow2</p></div>
<div id="d3" style="position: absolute;"><p>Follow3</p></div>


</body>

can call function with any Args

<body onmousemove="FollowMouse(d1,d2)">

or

<body onmousemove="FollowMouse(d1)">

Spring Security with roles and permissions

This is the simplest way to do it. Allows for group authorities, as well as user authorities.

-- Postgres syntax

create table users (
  user_id serial primary key,
  enabled boolean not null default true,
  password text not null,
  username citext not null unique
);

create index on users (username);

create table groups (
  group_id serial primary key,
  name citext not null unique
);

create table authorities (
  authority_id serial primary key,
  authority citext not null unique
);

create table user_authorities (
  user_id int references users,
  authority_id int references authorities,
  primary key (user_id, authority_id)
);

create table group_users (
  group_id int references groups,
  user_id int referenecs users,
  primary key (group_id, user_id)
);

create table group_authorities (
  group_id int references groups,
  authority_id int references authorities,
  primary key (group_id, authority_id)
);

Then in META-INF/applicationContext-security.xml

<beans:bean class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" id="passwordEncoder" />

<authentication-manager>
    <authentication-provider>

        <jdbc-user-service
                data-source-ref="dataSource"

                users-by-username-query="select username, password, enabled from users where username=?"

                authorities-by-username-query="select users.username, authorities.authority from users join user_authorities using(user_id) join authorities using(authority_id) where users.username=?"

                group-authorities-by-username-query="select groups.id, groups.name, authorities.authority from users join group_users using(user_id) join groups using(group_id) join group_authorities using(group_id) join authorities using(authority_id) where users.username=?"

                />

          <password-encoder ref="passwordEncoder" />

    </authentication-provider>
</authentication-manager>

Android XXHDPI resources

According to the post linked in the G+ resource:

The gorgeous screen on the Nexus 10 falls into the XHDPI density bucket. On tablets, Launcher uses icons from one density bucket up [0] to render them slightly larger. To ensure that your launcher icon (arguably your apps most important asset) is crisp you need to add a 144*144px icon in the drawable-xxhdpi or drawable-480dpi folder.

So it looks like the xxhdpi is set for 480dpi. According to that, tablets use the assets from one dpi bucket higher than the one they're in for the launcher. The Nexus 10 being in bucket xhdpi will pull the launcher icon from the xxhdpi.

Source

Also, was not aware that tablets take resources from the asset bucket above their level. Noted.

no module named zlib

Sounds like you need to install the devel package for zlib, probably want to do something like sudo apt-get install zlib1g-dev (I don't use ubuntu so you'll want to double-check the package). Instead of using python-brew you might want to consider just compiling by hand, it's not very hard. Just download the source, and configure, make, make install. You'll want to at least set --prefix to somewhere, so it'll get installed where you want.

./configure --prefix=/opt/python2.7 + other options
make
make install

You can check what configuration options are available with ./configure --help and see what your system python was compiled with by doing:

python -c "import sysconfig; print sysconfig.get_config_var('CONFIG_ARGS')"

The key is to make sure you have the development packages installed for your system, so that Python will be able to build the zlib, sqlite3, etc modules. The python docs cover the build process in more detail: http://docs.python.org/using/unix.html#building-python.

Two decimal places using printf( )

Use: "%.2f" or variations on that.

See the POSIX spec for an authoritative specification of the printf() format strings. Note that it separates POSIX extras from the core C99 specification. There are some C++ sites which show up in a Google search, but some at least have a dubious reputation, judging from comments seen elsewhere on SO.

Since you're coding in C++, you should probably be avoiding printf() and its relatives.

Python Web Crawlers and "getting" html source code

An Example with python3 and the requests library as mentioned by @leoluk:

pip install requests

Script req.py:

import requests

url='http://localhost'

# in case you need a session
cd = { 'sessionid': '123..'}

r = requests.get(url, cookies=cd)
# or without a session: r = requests.get(url)
r.content

Now,execute it and you will get the html source of localhost!

python3 req.py

Max size of URL parameters in _GET

Ok, it seems that some versions of PHP have a limitation of length of GET params:

Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.

To add support for long parameters with suhosin, add suhosin.get.max_value_length = <limit> in php.ini

Source: http://www.php.net/manual/en/reserved.variables.get.php#101469

Javascript reduce() on Object

What you actually want in this case are the Object.values. Here is a concise ES6 implementation with that in mind:

const add = {
  a: {value:1},
  b: {value:2},
  c: {value:3}
}

const total = Object.values(add).reduce((t, {value}) => t + value, 0)

console.log(total) // 6

or simply:

const add = {
  a: 1,
  b: 2,
  c: 3
}

const total = Object.values(add).reduce((t, n) => t + n)

console.log(total) // 6

Run CRON job everyday at specific time

you can write multiple lines in case of different minutes, for example you want to run at 10:01 AM and 2:30 PM

1 10 * * * php -f /var/www/package/index.php controller function

30 14 * * * php -f /var/www/package/index.php controller function

but the following is the best solution for running cron multiple times in a day as minutes are same, you can mention hours like 10,30 .

30 10,14 * * * php -f /var/www/package/index.php controller function

Rounding numbers to 2 digits after comma

EDIT 2:

Use the Number object's toFixed method like this:

var num = Number(0.005) // The Number() only visualizes the type and is not needed
var roundedString = num.toFixed(2);
var rounded = Number(roundedString); // toFixed() returns a string (often suitable for printing already)

It rounds 42.0054321 to 42.01

It rounds 0.005 to 0.01

It rounds -0.005 to -0.01 (So the absolute value increases on rounding at .5 border)

jsFiddle example

How can I alter a primary key constraint using SQL syntax?

PRIMARY KEY CONSTRAINT cannot be altered, you may only drop it and create again. For big datasets it can cause a long run time and thus - table inavailability.

How to get the range of occupied cells in excel sheet

These two lines on their own wasnt working for me:

xlWorkSheet.Columns.ClearFormats();
xlWorkSheet.Rows.ClearFormats();

You can test by hitting ctrl+end in the sheet and seeing which cell is selected.

I found that adding this line after the first two solved the problem in all instances I've encountered:

Excel.Range xlActiveRange = WorkSheet.UsedRange;

How can one run multiple versions of PHP 5.x on a development LAMP server?

Having multiple instances of apache + php never really tickled my fancy, but it probably the easiest way to do it. If you don't feel like KISS ... here's an idea.

Get your apache up and running, and try do configure it like debian and ubuntu do it, eg, have directories for loaded modules. Your apache conf can use lines like this:

Include /etc/apache2/mods-enabled/*.load
Include /etc/apache2/mods-enabled/*.conf

Then build your first version of php, and give it a prefix that has the version number explicitly contained, eg, /usr/local/php/5.2.8, /usr/local/php/5.2.6 ...

The conf/load would look something like this:

php5.2.6.load

LoadModule php5_module /usr/local/php/5.2.6/libphp5.so

php5.2.8.load

LoadModule php5_module /usr/local/php/5.2.8/libphp5.so

To switch versions, all you have to do is change the load and conf files from the directory apache does the include on for the ones for another version. You can automate that with a simple bash script (delete the actual file, copy the alternate versions file in place, and restart apache.

One advantage of this setup is the everything is consitent, so long you keep the php.ini's the same in terms of options and modules (which you would have to do with CGI anyway). They're all going through SAPI. Your applications won't need any changes whatsoever, nor need to use relative URLs.

I think this should work, but then again, i haven't tried it, nor am i likely to do so as i don't have the same requirements as you. Do comment if you ever do try though.

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

Be careful, in some cases clicking on a Form Control or Active X Control will give two different results for the same macro - which should not be the case. I find Active X more reliable.

How to copy folders to docker image from Dockerfile?

I don't completely understand the case of the original poster but I can proof that it's possible to copy directory structure using COPY in Dockerfile.

Suppose you have this folder structure:

folder1
  file1.html
  file2.html
folder2
  file3.html
  file4.html
  subfolder
    file5.html
    file6.html

To copy it to the destination image you can use such a Dockerfile content:

FROM nginx

COPY ./folder1/ /usr/share/nginx/html/folder1/
COPY ./folder2/ /usr/share/nginx/html/folder2/

RUN ls -laR /usr/share/nginx/html/*

The output of docker build . as follows:

$ docker build --no-cache .
Sending build context to Docker daemon  9.728kB
Step 1/4 : FROM nginx
 ---> 7042885a156a
Step 2/4 : COPY ./folder1/ /usr/share/nginx/html/folder1/
 ---> 6388fd58798b
Step 3/4 : COPY ./folder2/ /usr/share/nginx/html/folder2/
 ---> fb6c6eacf41e
Step 4/4 : RUN ls -laR /usr/share/nginx/html/*
 ---> Running in face3cbc0031
-rw-r--r-- 1 root root  494 Dec 25 09:56 /usr/share/nginx/html/50x.html
-rw-r--r-- 1 root root  612 Dec 25 09:56 /usr/share/nginx/html/index.html

/usr/share/nginx/html/folder1:
total 16
drwxr-xr-x 2 root root 4096 Jan 16 10:43 .
drwxr-xr-x 1 root root 4096 Jan 16 10:43 ..
-rwxr-xr-x 1 root root    7 Jan 16 10:32 file1.html
-rwxr-xr-x 1 root root    7 Jan 16 10:32 file2.html

/usr/share/nginx/html/folder2:
total 20
drwxr-xr-x 3 root root 4096 Jan 16 10:43 .
drwxr-xr-x 1 root root 4096 Jan 16 10:43 ..
-rwxr-xr-x 1 root root    7 Jan 16 10:32 file3.html
-rwxr-xr-x 1 root root    7 Jan 16 10:32 file4.html
drwxr-xr-x 2 root root 4096 Jan 16 10:33 subfolder

/usr/share/nginx/html/folder2/subfolder:
total 16
drwxr-xr-x 2 root root 4096 Jan 16 10:33 .
drwxr-xr-x 3 root root 4096 Jan 16 10:43 ..
-rwxr-xr-x 1 root root    7 Jan 16 10:32 file5.html
-rwxr-xr-x 1 root root    7 Jan 16 10:32 file6.html
Removing intermediate container face3cbc0031
 ---> 0e0062afab76
Successfully built 0e0062afab76

HTML5 input type range show range value

Try This :

 <input min="0" max="100" id="when_change_range" type="range">
 <input type="text" id="text_for_show_range">

and in jQuery section :

 $('#when_change_range').change(function(){
 document.getElementById('text_for_show_range').value=$(this).val();
  });

Different ways of adding to Dictionary

Given the, most than probable similarities in performance, use whatever feel more correct and readable to the piece of code you're using.

I feel an operation that describes an addition, being the presence of the key already a really rare exception is best represented with the add. Semantically it makes more sense.

The dict[key] = value represents better a substitution. If I see that code I half expect the key to already be in the dictionary anyway.

How can I create a dynamic button click event on a dynamic button?

You can create button in a simple way, such as:

Button button = new Button();
button.Click += new EventHandler(button_Click);

protected void button_Click (object sender, EventArgs e)
{
    Button button = sender as Button;
    // identify which button was clicked and perform necessary actions
}

But event probably will not fire, because the element/elements must be recreated at every postback or you will lose the event handler.

I tried this solution that verify that ViewState is already Generated and recreate elements at every postback,

for example, imagine you create your button on an event click:

    protected void Button_Click(object sender, EventArgs e)
    {
       if (Convert.ToString(ViewState["Generated"]) != "true")
        {
            CreateDynamicElements();
        }
    
    }

on postback, for example on page load, you should do this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Convert.ToString(ViewState["Generated"]) == "true") {
            CreateDynamicElements();
        }
    }

In CreateDynamicElements() you can put all the elements you need, such as your button.

This worked very well for me.

public void CreateDynamicElements(){

    Button button = new Button();
    button.Click += new EventHandler(button_Click);

}

What is the difference between the | and || or operators?

One is a "bitwise or".

10011b | 01000b => 11011b

The other is a logic or.

true or false => true

Creating a DateTime in a specific Time Zone in c#

I altered Jon Skeet answer a bit for the web with extension method. It also works on azure like a charm.

public static class DateTimeWithZone
{

private static readonly TimeZoneInfo timeZone;

static DateTimeWithZone()
{
//I added web.config <add key="CurrentTimeZoneId" value="Central Europe Standard Time" />
//You can add value directly into function.
    timeZone = TimeZoneInfo.FindSystemTimeZoneById(ConfigurationManager.AppSettings["CurrentTimeZoneId"]);
}


public static DateTime LocalTime(this DateTime t)
{
     return TimeZoneInfo.ConvertTime(t, timeZone);   
}
}

How to get the URL without any parameters in JavaScript?

You can concat origin and pathname, if theres present a port such as example.com:80, that will be included as well.

location.origin + location.pathname

Python Anaconda - How to Safely Uninstall

rm -rf ~/anaconda

It was pretty easy. It switched my pointer to Python: https://docs.continuum.io/anaconda/install#os-x-uninstall

Angular - Use pipes in services and components

You can use formatDate() to format the date in services or component ts. syntax:-

    formatDate(value: string | number | Date, format: string, locale: string, timezone?: string): string

import the formatDate() from common module like this,

    import { formatDate } from '@angular/common';

and just use it in the class like this ,

    formatDate(new Date(), 'MMMM dd yyyy', 'en');

You can also use the predefined format options provided by angular like this ,

    formatDate(new Date(), 'shortDate', 'en');

You can see all other predefined format options here ,

https://angular.io/api/common/DatePipe

How does internationalization work in JavaScript?

Mozilla recently released the awesome L20n or localization 2.0. In their own words L20n is

an open source, localization-specific scripting language used to process gender, plurals, conjugations, and most of the other quirky elements of natural language.

Their js implementation is on the github L20n repository.