Programs & Examples On #Word template

Microsoft.ACE.OLEDB.12.0 provider is not registered

I have a visual Basic program with Visual Studio 2008 that uses an Access 2007 database and was receiving the same error. I found some threads that advised changing the advanced compile configuration to x86 found in the programs properties if you're running a 64 bit system. So far I haven't had any problems with my program since.

Set transparent background of an imageview on Android

use RelativeLayout which has 2 imageViews in . and set transparency code on the top imageView.

transparency code :

<solid android:color="@color/white"/>
<gradient android:startColor="#40000000"   android:endColor="#FFFFFFFF" android:angle="270"/>

how to fix groovy.lang.MissingMethodException: No signature of method:

This may also be because you might have given classname with all letters in lowercase something which groovy (know of version 2.5.0) does not support.

class name - User is accepted but user is not.

Using true and false in C

There is no real speed difference. They are really all the same to the compiler. The difference is with the human beings trying to use and read your code.

For me that makes bool, true, and false the best choice in C++ code. In C code, there are some compilers around that don't support bool (I often have to work with old systems), so I might go with the defines in some circumstances.

How to compare two files in Notepad++ v6.6.8

Update:

  • for Notepad++ 7.5 and above use Compare v2.0.0
  • for Notepad++ 7.7 and above use Compare v2.0.0 for Notepad++ 7.7, if you need to install manually follow the description below, otherwise use "Plugin Admin".

I use Compare plugin 2 for notepad++ 7.5 and newer versions. Notepad++ 7.5 and newer versions does not have plugin manager. You have to download and install plugins manually. And YES it matters if you use 64bit or 32bit (86x).

So Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin, and the same valid for 32bit.

I wrote a guideline how to install it:

  1. Start your Notepad++ as administrator mode.
  2. Press F1 to find out if your Notepad++ is 64bit or 32bit (86x), hence you need to download the correct plugin version. Download Compare-plugin 2.
  3. Unzip Compare-plugin in temporary folder.
  4. Import plugin from the temporary folder.
  5. The plugin should appear under Plugins menu.

Note:
It is also possible to drag and drop the plugin .dll file directly in plugin folder.
64bit: %programfiles%\Notepad++\plugins
32bit: %programfiles(x86)%\Notepad++\plugins

Update Thanks to @TylerH with this update: Notepad++ Now has "Plugin Admin" as a replacement for the old Plugin Manager. But this method (answer) is still valid for adding plugins manually for almost any Notepad++ plugins.

Disclaimer: the link of this guideline refer to my personal web site.

How to make div follow scrolling smoothly with jQuery?

I wrote a relatively simple answer for this.

I have a table that's using one of the "sticky table header" plugins to stick right below a particular div on my page, but the menu to the left of the table didn't stick (as it's not part of the table.)

For my purposes, I knew the div that needed "stickiness" was always going to start at 385 pixels below the top of the window, so I created an empty div right above that:

<div id="stopMenu" class="stopMenu"></div>

Then ran this:

$(window).scroll(function(){   
   if ( $(window).scrollTop() > 385 ) {
    extraPadding = $(window).scrollTop() - 385;
    $('#stopMenu').css( "padding-top", extraPadding );
   } else {
     $('#stopMenu').css( "padding-top", "0" );
   }
});

As the user scrolls, it adds whatever the value of $(window).scrollTop() is to the integer 385, then adds that value to the stopMenu div that's above the thing I want to stay focused.

In the event the user scrolls all the way back up, I just set the extra padding to 0.

This doesn't require the user to do anything IN CSS particularly, but it's kind of a nice effect to make a small delay, so I put the class="stopMenu" in as well:

.stopMenu {
  .transition: all 0.1s;
}

Angular - res.json() is not a function

Had a similar problem where we wanted to update from deprecated Http module to HttpClient in Angular 7. But the application is large and need to change res.json() in a lot of places. So I did this to have the new module with back support.

return this.http.get(this.BASE_URL + url)
      .toPromise()
      .then(data=>{
        let res = {'results': JSON.stringify(data),
        'json': ()=>{return data;}
      };
       return res; 
      })
      .catch(error => {
        return Promise.reject(error);
      });

Adding a dummy "json" named function from the central place so that all other services can still execute successfully before updating them to accommodate a new way of response handling i.e. without "json" function.

Event system in Python

I found this small script on Valued Lessons. It seems to have just the right simplicity/power ratio I'm after. Peter Thatcher is the author of following code (no licensing is mentioned).

class Event:
    def __init__(self):
        self.handlers = set()

    def handle(self, handler):
        self.handlers.add(handler)
        return self

    def unhandle(self, handler):
        try:
            self.handlers.remove(handler)
        except:
            raise ValueError("Handler is not handling this event, so cannot unhandle it.")
        return self

    def fire(self, *args, **kargs):
        for handler in self.handlers:
            handler(*args, **kargs)

    def getHandlerCount(self):
        return len(self.handlers)

    __iadd__ = handle
    __isub__ = unhandle
    __call__ = fire
    __len__  = getHandlerCount

class MockFileWatcher:
    def __init__(self):
        self.fileChanged = Event()

    def watchFiles(self):
        source_path = "foo"
        self.fileChanged(source_path)

def log_file_change(source_path):
    print "%r changed." % (source_path,)

def log_file_change2(source_path):
    print "%r changed!" % (source_path,)

watcher              = MockFileWatcher()
watcher.fileChanged += log_file_change2
watcher.fileChanged += log_file_change
watcher.fileChanged -= log_file_change2
watcher.watchFiles()

Validate email with a regex in jQuery

You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:

var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i

if(!pattern.test(userinput))
{
  alert('not a valid e-mail address');
}?

How to include header files in GCC search path?

Using environment variable is sometimes more convenient when you do not control the build scripts / process.

For C includes use C_INCLUDE_PATH.

For C++ includes use CPLUS_INCLUDE_PATH.

See this link for other gcc environment variables.

Example usage in MacOS / Linux

# `pip install` will automatically run `gcc` using parameters
# specified in the `asyncpg` package (that I do not control)

C_INCLUDE_PATH=/home/scott/.pyenv/versions/3.7.9/include/python3.7m pip install asyncpg

Example usage in Windows

set C_INCLUDE_PATH="C:\Users\Scott\.pyenv\versions\3.7.9\include\python3.7m"

pip install asyncpg

# clear the environment variable so it doesn't affect other builds
set C_INCLUDE_PATH=

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

If you are connected via TFS, open your project.csproj.user file and check for

<UseIISExpress>false</UseIISExpress>

and change it to true.

<UseIISExpress>true</UseIISExpress>

How to get a shell environment variable in a makefile?

If you've exported the environment variable:

export demoPath=/usr/local/demo

you can simply refer to it by name in the makefile (make imports all the environment variables you have set):

DEMOPATH = ${demoPath}    # Or $(demoPath) if you prefer.

If you've not exported the environment variable, it is not accessible until you do export it, or unless you pass it explicitly on the command line:

make DEMOPATH="${demoPath}" …

If you are using a C shell derivative, substitute setenv demoPath /usr/local/demo for the export command.

Does SVG support embedding of bitmap images?

I posted a fiddle here, showing data, remote and local images embedded in SVG, inside an HTML page:

http://jsfiddle.net/MxHPq/

<!DOCTYPE html>
<html>
<head>
    <title>SVG embedded bitmaps in HTML</title>
    <style>

        body{
            background-color:#999;
            color:#666;
            padding:10px;
        }

        h1{
            font-weight:normal;
            font-size:24px;
            margin-top:20px;
            color:#000;
        }

        h2{
            font-weight:normal;
            font-size:20px;
            margin-top:20px;
        }

        p{
            color:#FFF;
            }

        svg{
            margin:20px;
            display:block;
            height:100px;
        }

    </style>
</head>

<body>
    <h1>SVG embedded bitmaps in HTML</h1>
    <p>The trick appears to be ensuring the image has the correct width and height atttributes</p>

    <h2>Example 1: Embedded data</h2>
    <svg id="example1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <image x="0" y="0" width="5" height="5" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>
    </svg>

    <h2>Example 2: Remote image</h2>
    <svg id="example2" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <image x="0" y="0" width="275" height="95" xlink:href="http://www.google.co.uk/images/srpr/logo3w.png" />
    </svg>

    <h2>Example 3: Local image</h2>
    <svg id="example3" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <image x="0" y="0" width="136" height="23" xlink:href="/img/logo.png" />
    </svg>


</body>
</html>

Select top 2 rows in Hive

select * from employee_list order by salary desc limit 2;

check if "it's a number" function in Oracle

Saish's answer using REGEXP_LIKE is the right idea but does not support floating numbers. This one will ...

Return values that are numeric

SELECT  foo 
FROM    bar
WHERE   REGEXP_LIKE (foo,'^-?\d+(\.\d+)?$');

Return values not numeric

SELECT  foo 
FROM    bar
WHERE   NOT REGEXP_LIKE (foo,'^-?\d+(\.\d+)?$');

You can test your regular expressions themselves till your heart is content at http://regexpal.com/ (but make sure you select the checkbox match at line breaks for this one).

How do I override nested NPM dependency versions?

You can use npm shrinkwrap functionality, in order to override any dependency or sub-dependency.

I've just done this in a grunt project of ours. We needed a newer version of connect, since 2.7.3. was causing trouble for us. So I created a file named npm-shrinkwrap.json:

{
  "dependencies": {
    "grunt-contrib-connect": {
      "version": "0.3.0",
      "from": "[email protected]",
      "dependencies": {
        "connect": {
          "version": "2.8.1",
          "from": "connect@~2.7.3"
        }
      }
    }
  }
}

npm should automatically pick it up while doing the install for the project.

(See: https://nodejs.org/en/blog/npm/managing-node-js-dependencies-with-shrinkwrap/)

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

MongoDB has a simple web based administrative port at 28017 by default.

There is no HTTP access at the default port of 27017 (which is what the error message is trying to suggest). The default port is used for native driver access, not HTTP traffic.

To access MongoDB, you'll need to use a driver like the MongoDB native driver for NodeJS. You won't "POST" to MongoDB directly (but you might create a RESTful API using express which uses the native drivers). Instead, you'll use a wrapper library that makes accessing MongoDB convenient. You might also consider using Mongoose (which uses the native driver) which adds an ORM-like model for MongoDB in NodeJS.

If you can't get to the web interface, it may be disabled. Normally, I wouldn't expect that you'd need it for doing development unless you're checking logs and such.

Best timestamp format for CSV/Excel?

As for timezones. I have to store the UTC offset as seconds from UTC that way formulas in Excel/OpenOffice can eventually localize datetimes. I found this to be easier than storing any number that has a 0 in front of it. -0900 didn't parse well in any spreadsheet system and importing it was nearly impossible to train people to do.

How to get element by innerText

You'll have to traverse by hand.

var aTags = document.getElementsByTagName("a");
var searchText = "SearchingText";
var found;

for (var i = 0; i < aTags.length; i++) {
  if (aTags[i].textContent == searchText) {
    found = aTags[i];
    break;
  }
}

// Use `found`.

Annotations from javax.validation.constraints not working

So @Valid at service interface would work for only that object. If you have any more validations within the hierarchy of ServiceRequest object then you might to have explicitly trigger validations. So this is how I have done it:

public class ServiceRequestValidator {

      private static Validator validator;

      @PostConstruct
      public void init(){
         validator = Validation.buildDefaultValidatorFactory().getValidator();
      }

      public static <T> void validate(T t){
        Set<ConstraintViolation<T>> errors = validator.validate(t);
        if(CollectionUtils.isNotEmpty(errors)){
          throw new ConstraintViolationException(errors);
        }
     }

}

You need to have following annotations at the object level if you want to trigger validation for that object.

@Valid
@NotNull

REST API - Bulk Create or Update in single request

In a project I worked at we solved this problem by implement something we called 'Batch' requests. We defined a path /batch where we accepted json in the following format:

[  
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 1,
         binder: 1
      }
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 5,
         binder: 8
      }
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 6,
         binder: 3
      }
   },
]

The response have the status code 207 (Multi-Status) and looks like this:

[  
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 1,
         binder: 1
      }
      status: 200
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         error: {
            msg: 'A document with doc_number 5 already exists'
            ...
         }
      },
      status: 409
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 6,
         binder: 3
      },
      status: 200
   },
]

You could also add support for headers in this structure. We implemented something that proved useful which was variables to use between requests in a batch, meaning we can use the response from one request as input to another.

Facebook and Google have similar implementations:
https://developers.google.com/gmail/api/guides/batch
https://developers.facebook.com/docs/graph-api/making-multiple-requests

When you want to create or update a resource with the same call I would use either POST or PUT depending on the case. If the document already exist, do you want the entire document to be:

  1. Replaced by the document you send in (i.e. missing properties in request will be removed and already existing overwritten)?
  2. Merged with the document you send in (i.e. missing properties in request will not be removed and already existing properties will be overwritten)?

In case you want the behavior from alternative 1 you should use a POST and in case you want the behavior from alternative 2 you should use PUT.

http://restcookbook.com/HTTP%20Methods/put-vs-post/

As people already suggested you could also go for PATCH, but I prefer to keep API's simple and not use extra verbs if they are not needed.

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

When merging topic branch "B" in "A" using git merge, I get some conflicts. I >know all the conflicts can be solved using the version in "B".

I am aware of git merge -s ours. But what I want is something like git merge >-s their.

I'm assuming that you created a branch off of master and now want to merge back into master, overriding any of the old stuff in master. That's exactly what I wanted to do when I came across this post.

Do exactly what it is you want to do, Except merge the one branch into the other first. I just did this, and it worked great.

git checkout Branch
git merge master -s ours

Then, checkout master and merge your branch in it (it will go smoothly now):

git checkout master
git merge Branch

Class has no initializers Swift

You have to use implicitly unwrapped optionals so that Swift can cope with circular dependencies (parent <-> child of the UI components in this case) during the initialization phase.

@IBOutlet var imgBook: UIImageView!
@IBOutlet var titleBook: UILabel!
@IBOutlet var pageBook: UILabel!

Read this doc, they explain it all nicely.

MySQL LEFT JOIN Multiple Conditions

Just move the extra condition into the JOIN ON criteria, this way the existence of b is not required to return a result

SELECT a.* FROM a 
    LEFT JOIN b ON a.group_id=b.group_id AND b.user_id!=$_SESSION{['user_id']} 
    WHERE a.keyword LIKE '%".$keyword."%' 
    GROUP BY group_id

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

Gradle project refresh failed after Android Studio update

This might be too late to answer. But this may help someone.

In my case there was problem of JDK path.

I just set proper JDK path for Android Studio 2.1

File -> Project Structure -> From Left Side Panel "SDK Location" -> JDK Location -> Click to select JDK Path

Check if object exists in JavaScript

I used to just do a if(maybeObject) as the null check in my javascripts.

if(maybeObject){
    alert("GOT HERE");
}

So only if maybeObject - is an object, the alert would be shown. I have an example in my site.

https://sites.google.com/site/javaerrorsandsolutions/home/javascript-dynamic-checkboxes

Select data from "show tables" MySQL query

Have you looked into querying INFORMATION_SCHEMA.Tables? As in

SELECT ic.Table_Name,
    ic.Column_Name,
    ic.data_Type,
    IFNULL(Character_Maximum_Length,'') AS `Max`,
    ic.Numeric_precision as `Precision`,
    ic.numeric_scale as Scale,
    ic.Character_Maximum_Length as VarCharSize,
    ic.is_nullable as Nulls, 
    ic.ordinal_position as OrdinalPos, 
    ic.column_default as ColDefault, 
    ku.ordinal_position as PK,
    kcu.constraint_name,
    kcu.ordinal_position,
    tc.constraint_type
FROM INFORMATION_SCHEMA.COLUMNS ic
    left outer join INFORMATION_SCHEMA.key_column_usage ku
        on ku.table_name = ic.table_name
        and ku.column_name = ic.column_name
    left outer join information_schema.key_column_usage kcu
        on kcu.column_name = ic.column_name
        and kcu.table_name = ic.table_name
    left outer join information_schema.table_constraints tc
        on kcu.constraint_name = tc.constraint_name
order by ic.table_name, ic.ordinal_position;

how to cancel/abort ajax request in axios

There is really nice package with few examples of usage called axios-cancel. I've found it very helpful. Here is the link: https://www.npmjs.com/package/axios-cancel

Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT

This error occurs when you suspend some functions. Like running the query below with incorrect foreign key.

set foreign_key_checks=0

Detect page change on DataTable

Try using delegate instead of live as here:

$('#link-wrapper').delegate('a', 'click', function() {
  // do something ..
}

Adding Apostrophe in every field in particular column for excel

More universal can be: for each v Selection : v.value = "'" & v.value : next and selecting range of cells before execution

Sending an HTTP POST request on iOS

Sending an HTTP POST request on iOS (Objective c):

-(NSString *)postexample{

// SEND POST
NSString *url = [NSString stringWithFormat:@"URL"];
NSString *post = [NSString stringWithFormat:@"param=value"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:url]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;

//RESPONDE DATA 
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200){
    NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
    return nil;
}

//SEE RESPONSE DATA
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Response" message:[[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];

return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

Follow the following steps,

  1. Update visual studio to latest version (it matters)
  2. Remove all binding redirects from web.config
  3. Add this to the .csproj file:

    <PropertyGroup>
      <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
      <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
    </PropertyGroup>
    
  4. Build the project
  5. In the bin folder there should be a (WebAppName).dll.config file
  6. It should have redirects in it, copy these to the web.config
  7. Remove the above snipped from the .csproj file

It should work

Reading an Excel file in python using pandas

Loading an excel file without explicitly naming a sheet but instead giving the number of the sheet order (often one will simply load the first sheet) goes like:

import pandas as pd
myexcel = pd.ExcelFile("C:/filename.xlsx")
myexcel = myexcel.parse(myexcel.sheet_names[0])

Since .sheet_names returns a list of sheet names, it is easy to load one or more sheets by simply calling the list element(s).

Convert Xml to DataTable

DataSet ds = new DataSet();
ds.ReadXml(fileNamePath);

Display a view from another controller in ASP.NET MVC

You can also call any controller from JavaScript/jQuery. Say you have a controller returning 404 or some other usercontrol/page. Then, on some action, from your client code, you can call some address that will fire your controller and return the result in HTML format your client code can take this returned result and put it wherever you want in you your page...

When to use Spring Security`s antMatcher()?

I'm updating my answer...

antMatcher() is a method of HttpSecurity, it doesn't have anything to do with authorizeRequests(). Basically, http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.

The authorizeRequests().antMatchers() is then used to apply authorization to one or more paths you specify in antMatchers(). Such as permitAll() or hasRole('USER3'). These only get applied if the first http.antMatcher() is matched.

Choose File Dialog

You just need to override onCreateDialog in an Activity.

//In an Activity
private String[] mFileList;
private File mPath = new File(Environment.getExternalStorageDirectory() + "//yourdir//");
private String mChosenFile;
private static final String FTYPE = ".txt";    
private static final int DIALOG_LOAD_FILE = 1000;

private void loadFileList() {
    try {
        mPath.mkdirs();
    }
    catch(SecurityException e) {
        Log.e(TAG, "unable to write on the sd card " + e.toString());
    }
    if(mPath.exists()) {
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String filename) {
                File sel = new File(dir, filename);
                return filename.contains(FTYPE) || sel.isDirectory();
            }

        };
        mFileList = mPath.list(filter);
    }
    else {
        mFileList= new String[0];
    }
}

protected Dialog onCreateDialog(int id) {
    Dialog dialog = null;
    AlertDialog.Builder builder = new Builder(this);

    switch(id) {
        case DIALOG_LOAD_FILE:
            builder.setTitle("Choose your file");
            if(mFileList == null) {
                Log.e(TAG, "Showing file picker before loading the file list");
                dialog = builder.create();
                return dialog;
            }
            builder.setItems(mFileList, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    mChosenFile = mFileList[which];
                    //you can do stuff with the file here too
                }
            });
            break;
    }
    dialog = builder.show();
    return dialog;
}

"error: assignment to expression with array type error" when I assign a struct field (C)

typedef struct{
     char name[30];
     char surname[30];
     int age;
} data;

defines that data should be a block of memory that fits 60 chars plus 4 for the int (see note)

[----------------------------,------------------------------,----]
 ^ this is name              ^ this is surname              ^ this is age

This allocates the memory on the stack.

data s1;

Assignments just copies numbers, sometimes pointers.

This fails

s1.name = "Paulo";

because the compiler knows that s1.name is the start of a struct 64 bytes long, and "Paulo" is a char[] 6 bytes long (6 because of the trailing \0 in C strings)
Thus, trying to assign a pointer to a string into a string.

To copy "Paulo" into the struct at the point name and "Rossi" into the struct at point surname.

memcpy(s1.name,    "Paulo", 6);
memcpy(s1.surname, "Rossi", 6);
s1.age = 1;

You end up with

[Paulo0----------------------,Rossi0-------------------------,0001]

strcpy does the same thing but it knows about \0 termination so does not need the length hardcoded.

Alternatively you can define a struct which points to char arrays of any length.

typedef struct {
  char *name;
  char *surname;
  int age;
} data;

This will create

[----,----,----]

This will now work because you are filling the struct with pointers.

s1.name = "Paulo";
s1.surname = "Rossi";
s1.age = 1;

Something like this

[---4,--10,---1]

Where 4 and 10 are pointers.

Note: the ints and pointers can be different sizes, the sizes 4 above are 32bit as an example.

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

[SOLVED] Neos/swiftmailer: Address in mailbox given [] does not comply with RFC 2822, 3.6.2

Exception in line 261 of /var/www/html/vendor/Packages/Libraries/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php: Address in mailbox given [] does not comply with RFC 2822, 3.6.2.

private function _assertValidAddress($address)
{
    if (!preg_match('/^'.$this->getGrammar()->getDefinition('addr-spec').'$/D',
        $address)) {
        throw new Swift_RfcComplianceException(
            'Address in mailbox given ['.$address.
            '] does not comply with RFC 2822, 3.6.2.'
            );
    }
}

https://discuss.neos.io/t/solved-neos-swiftmailer-address-in-mailbox-given-does-not-comply-with-rfc-2822-3-6-2/3012

How do I print output in new line in PL/SQL?

dbms_output.put_line('Hi,');
dbms_output.put_line('good');
dbms_output.put_line('morning');
dbms_output.put_line('friends');

or

DBMS_OUTPUT.PUT_LINE('Hi, ' || CHR(13) || CHR(10) || 
                     'good' || CHR(13) || CHR(10) ||
                     'morning' || CHR(13) || CHR(10) ||
                     'friends' || CHR(13) || CHR(10) ||);

try it.

What is a NullReferenceException, and how do I fix it?

Another general case where one might receive this exception involves mocking classes during unit testing. Regardless of the mocking framework being used, you must ensure that all appropriate levels of the class hierarchy are properly mocked. In particular, all properties of HttpContext which are referenced by the code under test must be mocked.

See "NullReferenceException thrown when testing custom AuthorizationAttribute" for a somewhat verbose example.

How to set initial value and auto increment in MySQL?

Also , in PHPMyAdmin , you can select table from left side(list of tables) then do this by going there.
Operations Tab->Table Options->AUTO_INCREMENT.

Now, Set your values and then press Go under the Table Options Box.

size of NumPy array

This is called the "shape" in NumPy, and can be requested via the .shape attribute:

>>> a = zeros((2, 5))
>>> a.shape
(2, 5)

If you prefer a function, you could also use numpy.shape(a).

Open popup and refresh parent page on close popup

The pop-up window does not have any close event that you can listen to.

On the other hand, there is a closed property that is set to true when the window gets closed.

You can set a timer to check that closed property and do it like this:

var win = window.open('foo.html', 'windowName',"width=200,height=200,scrollbars=no");   
var timer = setInterval(function() {   
    if(win.closed) {  
        clearInterval(timer);  
        alert('closed');  
    }  
}, 1000); 

See this working Fiddle example!

Programmatically trigger "select file" dialog box

The best solution, works in all browsers.. even on mobile.

<div class="btn" id="s_photo">Upload</div>

<input type="file" name="s_file" id="s_file" style="opacity: 0;">';

<!--jquery-->

<script>
    $("#s_photo").click(function() {
        $("#s_file").trigger("click");
    });
</script>

Hiding the input file type causes problems with browsers, opacity is the best solution because it isn't hiding, just not showing. :)

What is the Difference Between Mercurial and Git?

There are quite significant differences when it comes to working with branches (especially short-term ones).

It is explained in this article (BranchingExplained) which compares Mercurial with Git.

PHP get domain name

Similar question has been asked in stackoverflow before.

See here: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Also see this article: http://shiflett.org/blog/2006/mar/server-name-versus-http-host

Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:

  • no DNS support
  • misconfigured
  • behind load balancing software

Source: http://discussion.dreamhost.com/thread-4388.html

What's the meaning of exception code "EXC_I386_GPFLT"?

In my case EXC_I386_GPFLT was caused by missing return value in the property getter. Like this:

- (CppStructure)cppStructure
{
    CppStructure data;
    data.a = self.alpha;
    data.b = self.beta;

    return data; // this line was missing
}

Xcode 12.2

Difference between javacore, thread dump and heap dump in Websphere

Heap dumps anytime you wish to see what is being held in memory Out-of-memory errors Heap dumps - picture of in memory objects - used for memory analysis Java cores - also known as thread dumps or java dumps, used for viewing the thread activity inside the JVM at a given time. IBM javacores should a lot of additional information besides just the threads and stacks -- used to determine hangs, deadlocks, and reasons for performance degredation System cores

Maven Modules + Building a Single Specific Module

Take a look at my answer Maven and dependent modules.

The Maven Reactor plugin is designed to deal with building part of a project.

The particular goal you'll want to use it reactor:make.

C# Equivalent of SQL Server DataTypes

SQL Server and the .NET Framework are based on different type systems. For example, the .NET Framework Decimal structure has a maximum scale of 28, whereas the SQL Server decimal and numeric data types have a maximum scale of 38. Click Here's a link! for detail

https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx

How to pass boolean values to a PowerShell script from a command prompt

Try setting the type of your parameter to [bool]:

param
(
    [int]$Turn = 0
    [bool]$Unity = $false
)

switch ($Unity)
{
    $true { "That was true."; break }
    default { "Whatever it was, it wasn't true."; break }
}

This example defaults $Unity to $false if no input is provided.

Usage

.\RunScript.ps1 -Turn 1 -Unity $false

Can't create project on Netbeans 8.2

I had the same issue,

  • Quit Netbeans.
  • Delete the JDK9 file in : /Library/Java/JavaVirtualMachines
  • Install the JDK8 : Download link

Good luck :)

What's the difference between compiled and interpreted language?

What’s the difference between compiled and interpreted language?

The difference is not in the language; it is in the implementation.

Having got that out of my system, here's an answer:

  • In a compiled implementation, the original program is translated into native machine instructions, which are executed directly by the hardware.

  • In an interpreted implementation, the original program is translated into something else. Another program, called "the interpreter", then examines "something else" and performs whatever actions are called for. Depending on the language and its implementation, there are a variety of forms of "something else". From more popular to less popular, "something else" might be

    • Binary instructions for a virtual machine, often called bytecode, as is done in Lua, Python, Ruby, Smalltalk, and many other systems (the approach was popularized in the 1970s by the UCSD P-system and UCSD Pascal)

    • A tree-like representation of the original program, such as an abstract-syntax tree, as is done for many prototype or educational interpreters

    • A tokenized representation of the source program, similar to Tcl

    • The characters of the source program, as was done in MINT and TRAC

One thing that complicates the issue is that it is possible to translate (compile) bytecode into native machine instructions. Thus, a successful intepreted implementation might eventually acquire a compiler. If the compiler runs dynamically, behind the scenes, it is often called a just-in-time compiler or JIT compiler. JITs have been developed for Java, JavaScript, Lua, and I daresay many other languages. At that point you can have a hybrid implementation in which some code is interpreted and some code is compiled.

What are the git concepts of HEAD, master, origin?

HEAD is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.

master is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).

origin is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.

Find Java classes implementing an interface

You could also use the Extensible Component Scanner (extcos: http://sf.net/projects/extcos) and search all classes implementing an interface like so:

Set<Class<? extends MyInterface>> classes = new HashSet<Class<? extends MyInterface>>();

ComponentScanner scanner = new ComponentScanner();
scanner.getClasses(new ComponentQuery() {
    @Override
    protected void query() {
        select().
        from("my.package1", "my.package2").
        andStore(thoseImplementing(MyInterface.class).into(classes)).
        returning(none());
    }
});

This works for classes on the file system, within jars and even for those on the JBoss virtual file system. It's further designed to work within standalone applications as well as within any web or application container.

sh: 0: getcwd() failed: No such file or directory on cited drive

This can happen with symlinks sometimes. If you experience this issue and you know you are in an existing directory, but your symlink may have changed, you can use this command:

cd $(pwd)

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

psql: command not found Mac

If someone used homebrew with Mojave or later:

export PATH=/usr/local/opt/[email protected]/bin:$PATH

change version if you need!

Get timezone from DateTime

There is a public domain TimeZone library for .NET. Really useful. It will answer your needs.

Solving the general-case timezone problem is harder than you think.

Responding with a JSON object in Node.js (converting object/array to JSON string)

const http = require('http');
const url = require('url');

http.createServer((req,res)=>{

    const parseObj =  url.parse(req.url,true);
    const users = [{id:1,name:'soura'},{id:2,name:'soumya'}]

    if(parseObj.pathname == '/user-details' && req.method == "GET") {
        let Id = parseObj.query.id;
        let user_details = {};
        users.forEach((data,index)=>{
            if(data.id == Id){
                user_details = data;
            }
        })
        res.writeHead(200,{'x-auth-token':'Auth Token'})
        res.write(JSON.stringify(user_details)) // Json to String Convert
        res.end();
    }
}).listen(8000);

I have used the above code in my existing project.

Detect changed input text box

In my case, I had a textbox that was attached to a datepicker. The only solution that worked for me was to handle it inside the onSelect event of the datepicker.

<input type="text"  id="bookdate">

$("#bookdate").datepicker({            
     onSelect: function (selected) {
         //handle change event here
     }
});

How to check if an appSettings key exists?

I liked codebender's answer, but needed it to work in C++/CLI. This is what I ended up with. There's no LINQ usage, but works.

generic <typename T> T MyClass::ReadAppSetting(String^ searchKey, T defaultValue) {
  for each (String^ setting in ConfigurationManager::AppSettings->AllKeys) {
    if (setting->Equals(searchKey)) { //  if the key is in the app.config
      try {                           // see if it can be converted
        auto converter = TypeDescriptor::GetConverter((Type^)(T::typeid)); 
        if (converter != nullptr) { return (T)converter->ConvertFromString(ConfigurationManager::AppSettings[searchKey]); }
      } catch (Exception^ ex) {} // nothing to do
    }
  }
  return defaultValue;
}

Convert True/False value read from file to boolean

Use ast.literal_eval:

>>> import ast
>>> ast.literal_eval('True')
True
>>> ast.literal_eval('False')
False

Why is flag always converting to True?

Non-empty strings are always True in Python.

Related: Truth Value Testing


If NumPy is an option, then:

>>> import StringIO
>>> import numpy as np
>>> s = 'True - False - True'
>>> c = StringIO.StringIO(s)
>>> np.genfromtxt(c, delimiter='-', autostrip=True, dtype=None) #or dtype=bool
array([ True, False,  True], dtype=bool)

XSLT equivalent for JSON

As yet another new answer to an old question, I'd suggest a look at DefiantJS. It's not an XSLT equivalent for JSON, it is XSLT for JSON. The "Templating" section of the documentation includes this example:

<!-- Defiant template -->
<script type="defiant/xsl-template">
    <xsl:template name="books_template">
        <xsl:for-each select="//movie">
            <xsl:value-of select="title"/><br/>
        </xsl:for-each>
    </xsl:template>
</script>

<script type="text/javascript">

var data = {
        "movie": [
            {"title": "The Usual Suspects"},
            {"title": "Pulp Fiction"},
            {"title": "Independence Day"}
        ]
    },
    htm = Defiant.render('books_template', data);

console.log(htm);
// The Usual Suspects<br>
// Pulp Fiction<br>
// Independence Day<br>

Create a Date with a set timezone without using a string representation

using .setUTCHours() it would be possible to actually set dates in UTC-time, which would allow you to use UTC-times throughout the system.

You cannot set it using UTC in the constructor though, unless you specify a date-string.

Using new Date(Date.UTC(year, month, day, hour, minute, second)) you can create a Date-object from a specific UTC time.

How do I clone into a non-empty directory?

this is work for me ,but you should merge remote repository files to the local files:

git init
git remote add origin url-to-git
git branch --set-upstream-to=origin/master master
git fetch
git status

Best way to retrieve variable values from a text file?

What you want appear to want is the following, but this is NOT RECOMMENDED:

>>> for line in open('dangerous.txt'):
...     exec('%s = %s' % tuple(line.split(':', 1)))
... 
>>> var_a
'home'

This creates somewhat similar behavior to PHP's register_globals and hence has the same security issues. Additionally, the use of exec that I showed allows arbitrary code execution. Only use this if you are absolutely sure that the contents of the text file can be trusted under all circumstances.

You should really consider binding the variables not to the local scope, but to an object, and use a library that parses the file contents such that no code is executed. So: go with any of the other solutions provided here.

(Please note: I added this answer not as a solution, but as an explicit non-solution.)

Android Device not recognized by adb

Try use PdaNet. you can download it from here

It installs missing drivers when you plugin your device.

Obviously make sure you "debug usb" option in "developers options" is on.

Another thing, it's important to uninstall any device's installed driver before using it.

How to extract one column of a csv file

You could use awk for this. Change '$2' to the nth column you want.

awk -F "\"*,\"*" '{print $2}' textfile.csv

addClass and removeClass in jQuery - not removing class

Whenever I see addClass and removeClass I think why not just use toggleClass. In this case we can remove the .clickable class to avoid event bubbling, and to avoid the event from being fired on everything we click inside of the .clickable div.

$(document).on("click", ".close_button", function () { 
    $(this).closest(".grown").toggleClass("spot grown clickable");
});  

$(document).on("click", ".clickable", function () {
    $(this).toggleClass("spot grown clickable");
}); 

I also recommend a parent wrapper for your .clickable divs instead of using the document. I am not sure how you are adding them dynamically so didn't want to assume your layout for you.

http://jsfiddle.net/bplumb/ECQg5/2/

Happy Coding :)

jQuery append text inside of an existing paragraph tag

Try this

$('#add_here').text('new-dynamic-text');

Removing display of row names from data frame

You have successfully removed the row names. The print.data.frame method just shows the row numbers if no row names are present.

df1 <- data.frame(values = rnorm(3), group = letters[1:3],
                  row.names = paste0("RowName", 1:3))
print(df1)
#            values group
#RowName1 -1.469809     a
#RowName2 -1.164943     b
#RowName3  0.899430     c

rownames(df1) <- NULL
print(df1)
#     values group
#1 -1.469809     a
#2 -1.164943     b
#3  0.899430     c

You can suppress printing the row names and numbers in print.data.frame with the argument row.names as FALSE.

print(df1, row.names = FALSE)
#     values group
# -1.4345829     d
#  0.2182768     e
# -0.2855440     f

Edit: As written in the comments, you want to convert this to HTML. From the xtable and print.xtable documentation, you can see that the argument include.rownames will do the trick.

library("xtable")
print(xtable(df1), type="html", include.rownames = FALSE)
#<!-- html table generated in R 3.1.0 by xtable 1.7-3 package -->
#<!-- Thu Jun 26 12:50:17 2014 -->
#<TABLE border=1>
#<TR> <TH> values </TH> <TH> group </TH>  </TR>
#<TR> <TD align="right"> -0.34 </TD> <TD> a </TD> </TR>
#<TR> <TD align="right"> -1.04 </TD> <TD> b </TD> </TR>
#<TR> <TD align="right"> -0.48 </TD> <TD> c </TD> </TR>
#</TABLE>

How to run SQL script in MySQL?

If you’re at the MySQL command line mysql> you have to declare the SQL file as source.

mysql> source \home\user\Desktop\test.sql;

How can I use tabs for indentation in IntelliJ IDEA?

IntelliJ IDEA 15

Only for the current file

You have the following options:

  1. Ctrl + Shift + A > write "tabs" > double click on "To Tabs"

    To Tabs

    If you want to convert tabs to spaces, you can write "spaces", then choose "To Spaces".

  2. Edit > Convert Indents > To Tabs

    To convert tabs to spaces, you can chose "To Spaces" from the same place.

For all files

The paths in the other answers were changed a little:

  • File > Settings... > Editor > Code Style > Java > Tabs and Indents > Use tab character Use tab character
  • File > Other Settings > Default Settings... > Editor > Code Style > Java > Tabs and Indents > Use tab character
  • File > Settings... > Editor > Code Style > Detect and use existing file indents for editing
  • File > Other Settings > Default Settings... > Editor > Code Style > Detect and use existing file indents for editing

It seems that it doesn't matter if you check/uncheck the box from Settings... or from Other Settings > Default Settings..., because the change from one window will be available in the other window.

The changes above will be applied for the new files, but if you want to change spaces to tabs in an existing file, then you should format the file by pressing Ctrl + Alt + L.

How to check iOS version?

New way to check the system version using the swift Forget [[UIDevice currentDevice] systemVersion] and NSFoundationVersionNumber.

We can use NSProcessInfo -isOperatingSystemAtLeastVersion

     import Foundation

     let yosemite = NSOperatingSystemVersion(majorVersion: 10, minorVersion: 10, patchVersion: 0)
     NSProcessInfo().isOperatingSystemAtLeastVersion(yosemite) // false

Using cut command to remove multiple columns

The same could be done with Perl
Because it uses 0-based-indexing instead of 1-based-indexing, the field values are offset by 1

perl -F, -lane 'print join ",", @F[1..3,5..9,11..19]'    

is equivalent to:

cut -d, -f2-4,6-10,12-20

If the commas are not needed in the output:

perl -F, -lane 'print "@F[1..3,5..9,11..19]"'

Add CSS to <head> with JavaScript?

As you are trying to add a string of CSS to <head> with JavaScript? injecting a string of CSS into a page it is easier to do this with the <link> element than the <style> element.

The following adds p { color: green; } rule to the page.

<link rel="stylesheet" type="text/css" href="data:text/css;charset=UTF-8,p%20%7B%20color%3A%20green%3B%20%7D" />

You can create this in JavaScript simply by URL encoding your string of CSS and adding it the HREF attribute. Much simpler than all the quirks of <style> elements or directly accessing stylesheets.

var linkElement = this.document.createElement('link');
linkElement.setAttribute('rel', 'stylesheet');
linkElement.setAttribute('type', 'text/css');
linkElement.setAttribute('href', 'data:text/css;charset=UTF-8,' + encodeURIComponent(myStringOfstyles));

This will work in IE 5.5 upwards

The solution you have marked will work but this solution requires fewer dom operations and only a single element.

How to access a RowDataPacket object

I really don't see what is the big deal with this I mean look if a run my sp which is CALL ps_get_roles();. Yes I get back an ugly ass response from DB and stuff. Which is this one:


[
  [
    RowDataPacket {
      id: 1,
      role: 'Admin',
      created_at: '2019-12-19 16:03:46'
    },
    RowDataPacket {
      id: 2,
      role: 'Recruiter',
      created_at: '2019-12-19 16:03:46'
    },
    RowDataPacket {
      id: 3,
      role: 'Regular',
      created_at: '2019-12-19 16:03:46'
    }
  ],
  OkPacket {
    fieldCount: 0,
    affectedRows: 0,
    insertId: 0,
    serverStatus: 35,
    warningCount: 0,
    message: '',
    protocol41: true,
    changedRows: 0
  }
]

it is an array that kind of look like this:


rows[0] = [
    RowDataPacket {/* them table rows*/ },
    RowDataPacket { },
    RowDataPacket { }
];

rows[1] = OkPacket {
   /* them props */
}

but if I do an http response to index [0] of rows at the client I get:

[
  {"id":1,"role":"Admin","created_at":"2019-12-19 16:03:46"}, 
  {"id":2,"role":"Recruiter","created_at":"2019-12-19 16:03:46"},
  {"id":3,"role":"Regular","created_at":"2019-12-19 16:03:46"}
]

and I didnt have to do none of yow things

rows[0].map(row => {
   return console.log("row: ", {...row});
});

the output gets some like this:

row:  { id: 1, role: 'Admin', created_at: '2019-12-19 16:03:46' }
row:  { id: 2, role: 'Recruiter', created_at: '2019-12-19 16:03:46' }
row:  { id: 3, role: 'Regular', created_at: '2019-12-19 16:03:46' }

So you all is tripping for no reason. Or it also could be the fact that I'm running store procedures instead of regular querys, the response from query and sp is not the same.

The most efficient way to implement an integer based power function pow(int, int)

In addition to the answer by Elias, which causes Undefined Behaviour when implemented with signed integers, and incorrect values for high input when implemented with unsigned integers,

here is a modified version of the Exponentiation by Squaring that also works with signed integer types, and doesn't give incorrect values:

#include <stdint.h>

#define SQRT_INT64_MAX (INT64_C(0xB504F333))

int64_t alx_pow_s64 (int64_t base, uint8_t exp)
{
    int_fast64_t    base_;
    int_fast64_t    result;

    base_   = base;

    if (base_ == 1)
        return  1;
    if (!exp)
        return  1;
    if (!base_)
        return  0;

    result  = 1;
    if (exp & 1)
        result *= base_;
    exp >>= 1;
    while (exp) {
        if (base_ > SQRT_INT64_MAX)
            return  0;
        base_ *= base_;
        if (exp & 1)
            result *= base_;
        exp >>= 1;
    }

    return  result;
}

Considerations for this function:

(1 ** N) == 1
(N ** 0) == 1
(0 ** 0) == 1
(0 ** N) == 0

If any overflow or wrapping is going to take place, return 0;

I used int64_t, but any width (signed or unsigned) can be used with little modification. However, if you need to use a non-fixed-width integer type, you will need to change SQRT_INT64_MAX by (int)sqrt(INT_MAX) (in the case of using int) or something similar, which should be optimized, but it is uglier, and not a C constant expression. Also casting the result of sqrt() to an int is not very good because of floating point precission in case of a perfect square, but as I don't know of any implementation where INT_MAX -or the maximum of any type- is a perfect square, you can live with that.

Error: fix the version conflict (google-services plugin)

Same error gets thrown when

apply plugin: 'com.google.gms.google-services'

is not added to bottom of the module build.gradle file.

What is the maximum length of a URL in different browsers?

The URI RFC (of which URLs are a subset) doesn't define a maximum length, however, it does recommend that the hostname part of the URI (if applicable) not exceed 255 characters in length:

URI producers should use names that conform to the DNS syntax, even when use of DNS is not immediately apparent, and should limit these names to no more than 255 characters in length.

As noted in other posts though, some browsers have a practical limitation on the length of a URL.

JOptionPane Yes or No window

You are always checking for a true condition, hence your message will always show.

You should replace your if (true) statement with if ( n == JOptionPane.YES_OPTION)

When one of the showXxxDialog methods returns an integer, the possible values are:

YES_OPTION NO_OPTION CANCEL_OPTION OK_OPTION CLOSED_OPTION

From here

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

for Laravel 5.4
for gmail


in .env file

MAIL_DRIVER=mail
MAIL_HOST=mail.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<username>@gmail.com
MAIL_PASSWORD=<password>
MAIL_ENCRYPTION=tls

in config/mail.php

'driver' => env('MAIL_DRIVER', 'mail'),

'from' => [
    'address' => env(
        'MAIL_FROM_ADDRESS', '<username>@gmail.com'
    ),
    'name' => env(
        'MAIL_FROM_NAME', '<from_name>'
    ),
],

How to choose between Hudson and Jenkins?

Jenkins is the new Hudson. It really is more like a rename, not a fork, since the whole development community moved to Jenkins. (Oracle is left sitting in a corner holding their old ball "Hudson", but it's just a soul-less project now.)

C.f. Ethereal -> WireShark

Counting array elements in Perl

It sounds like you want a sparse array. A normal array would have 24 items in it, but a sparse array would have 3. In Perl we emulate sparse arrays with hashes:

#!/usr/bin/perl

use strict;
use warnings;

my %sparse;

@sparse{0, 5, 23} = (1 .. 3);

print "there are ", scalar keys %sparse, " items in the sparse array\n",
    map { "\t$sparse{$_}\n" } sort { $a <=> $b } keys %sparse;

The keys function in scalar context will return the number of items in the sparse array. The only downside to using a hash to emulate a sparse array is that you must sort the keys before iterating over them if their order is important.

You must also remember to use the delete function to remove items from the sparse array (just setting their value to undef is not enough).

How to manually force a commit in a @Transactional method?

I had a similar use case during testing hibernate event listeners which are only called on commit.

The solution was to wrap the code to be persistent into another method annotated with REQUIRES_NEW. (In another class) This way a new transaction is spawned and a flush/commit is issued once the method returns.

Tx prop REQUIRES_NEW

Keep in mind that this might influence all the other tests! So write them accordingly or you need to ensure that you can clean up after the test ran.

Test if string is URL encoded in PHP

What about:

if (urldecode(trim($url)) == trim($url)) { $url_form = 'decoded'; }
  else { $url_form = 'encoded'; }

Will not work with double encoding but this is out of scope anyway I suppose?

Way to read first few lines for pandas dataframe

I think you can use the nrows parameter. From the docs:

nrows : int, default None

    Number of rows of file to read. Useful for reading pieces of large files

which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

In [1]: import pandas as pd

In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s

In [3]: len(z)
Out[3]: 20

In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

The error is down to an "inappropriate use" of the double colon operator:

return $cnf::getConfig($key);

as by using the :: you're attempting to call a static method of the class itself. In your example you want to call a non-static method on an instantiated object.

I think what you want is:

return $cnf->getConfig($key);

What does it mean to bind a multicast (UDP) socket?

Correction for What does it mean to bind a multicast (udp) socket? as long as it partially true at the following quote:

The "bind" operation is basically saying, "use this local UDP port for sending and receiving data. In other words, it allocates that UDP port for exclusive use for your application

There is one exception. Multiple applications can share the same port for listening (usually it has practical value for multicast datagrams), if the SO_REUSEADDR option applied. For example

int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // create UDP socket somehow
...
int set_option_on = 1;
// it is important to do "reuse address" before bind, not after
int res = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on, 
    sizeof(set_option_on));
res = bind(sock, src_addr, len);

If several processes did such "reuse binding", then every UDP datagram received on that shared port will be delivered to each of the processes (providing natural joint with multicasts traffic).

Here are further details regarding what happens in a few cases:

  1. attempt of any bind ("exclusive" or "reuse") to free port will be successful

  2. attempt to "exclusive binding" will fail if the port is already "reuse-binded"

  3. attempt to "reuse binding" will fail if some process keeps "exclusive binding"

docker unauthorized: authentication required - upon push with successful login

I have received similar error for sudo docker push /sudo docker pull on ecr repository.This is because aws cli installed in my user(abc) and docker installed in root user.I have tried to run sudo docker push on my user(abc)

Fixed this by installed aws cli in root , configured aws using aws configure in root and run sudo docker push to ecr on root user

ORA-00979 not a group by expression

If you do grouping by virtue of including GROUP BY clause, any expression in SELECT, which is not group function (or aggregate function or aggregated column) such as COUNT, AVG, MIN, MAX, SUM and so on (List of Aggregate functions) should be present in GROUP BY clause.

Example (correct way) (here employee_id is not group function (non-aggregated column), so it must appear in GROUP BY. By contrast, sum(salary) is a group function (aggregated column), so it is not required to appear in the GROUP BYclause.

   SELECT employee_id, sum(salary) 
   FROM employees
   GROUP BY employee_id; 

Example (wrong way) (here employee_id is not group function and it does not appear in GROUP BY clause, which will lead to the ORA-00979 Error .

   SELECT employee_id, sum(salary) 
   FROM employees;

To correct you need to do one of the following :

  • Include all non-aggregated expressions listed in SELECT clause in the GROUP BY clause
  • Remove group (aggregate) function from SELECT clause.

com.jcraft.jsch.JSchException: UnknownHostKey

It is a security risk to avoid host key checking.

JSch uses HostKeyRepository interface and its default implementation KnownHosts class to manage this. You can provide an alternate implementation that allows specific keys by implementing HostKeyRepository. Or you could keep the keys that you want to allow in a file in the known_hosts format and call

jsch.setKnownHosts(knownHostsFileName);

Or with a public key String as below.

String knownHostPublicKey = "mysite.com ecdsa-sha2-nistp256 AAAAE............/3vplY";
jsch.setKnownHosts(new ByteArrayInputStream(knownHostPublicKey.getBytes()));

see Javadoc for more details.

This would be a more secure solution.

Jsch is open source and you can download the source from here. In the examples folder, look for KnownHosts.java to know more details.

How to create a jar with external libraries included in Eclipse?

Personally,

None of the answers above worked for me, I still kept getting NoClassDefFound errors (I am using Maven for dependencies). My solution was to build using "mvn clean install" and use the "[project]-jar-with-dependencies.jar" that that command creates. Similarly in Eclipse you can right click the project -> Run As -> Maven Install and it will place the jars in the target folder.

JavaScript function in href vs. onclick

Putting the onclick within the href would offend those who believe strongly in separation of content from behavior/action. The argument is that your html content should remain focused solely on content, not on presentation or behavior.

The typical path these days is to use a javascript library (eg. jquery) and create an event handler using that library. It would look something like:

$('a').click( function(e) {e.preventDefault(); /*your_code_here;*/ return false; } );

two divs the same line, one dynamic width, one fixed

So left div style depends on the presence of right div. I can't think of a CSS selector allowing that kind of behavior yet.

Thus it seems to me that you'll need to programmatically add a class server side (or in JS) on parent div or left div to do that.

<div id="parent twocols">
  <div class="left"></div>
  <div class="right"></div>
</div>

or

<div id="parent">
  <div class="left"></div>
</div>

So right style is always :

.right {
    float: right;
    width: 200px; /* or whatever value you need */
    /* margin and padding at your discretion */
}

and left style is :

.parent.twocols .left {
    margin-right: 200px; /* according to right div width + margin + padding*/
}

What's the best way to determine the location of the current PowerShell script?

I always use this little snippet which works for PowerShell and ISE the same way:

# Set active path to script-location:
$path = $MyInvocation.MyCommand.Path
if (!$path) {
    $path = $psISE.CurrentFile.Fullpath
}
if ($path) {
    $path = Split-Path $path -Parent
}
Set-Location $path

Setting width as a percentage using jQuery

Here is an alternative that worked for me:

$('div#somediv').css({'width': '70%'});

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

Apparently YouTube constantly polls for Google Cast scripts even if the extension isn't installed.

From one commenter:

... it appears that Chrome attempts to get cast_sender.js on pages that have YouTube content. I'm guessing when Chrome sees media that it can stream it attempts to access the Chromecast extension. When the extension isn't present, the error is thrown.

Read more

The only solution I've come across is to install the Google Cast extension, whether you need it or not. You may then hide the toolbar button.

For more information and updates, see this SO question. Here's the official issue.

Invoking Java main method with parameters from Eclipse

If have spaces within your string argument, do the following:

Run > Run Configurations > Java Application > Arguments > Program arguments

  1. Enclose your string argument with quotes
  2. Separate each argument by space or new line

Preventing an image from being draggable or selectable without using JS

Set the following CSS properties to the image:

user-drag: none; 
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;

How can I connect to MySQL in Python 3 on Windows?

PyMySQL gives MySQLDb like interface as well. You could try in your initialization:

import pymysql
pymysql.install_as_MySQLdb()

Also there is a port of mysql-python on github for python3.

https://github.com/davispuh/MySQL-for-Python-3

cannot make a static reference to the non-static field

you can keep your withdraw and deposit methods static if you want however you'd have to write it like the code below. sb = starting balance and eB = ending balance.

Account account = new Account(1122, 20000, 4.5);

    double sB = Account.withdraw(account.getBalance(), 2500);
    double eB = Account.deposit(sB, 3000);
    System.out.println("Balance is " + eB);
    System.out.println("Monthly interest is " + (account.getAnnualInterestRate()/12));
    account.setDateCreated(new Date());
    System.out.println("The account was created " + account.getDateCreated());

What is the correct way to read a serial port using .NET framework?

    using System;
    using System.IO.Ports;
    using System.Threading;

    namespace SerialReadTest
    {
        class SerialRead
        {
            static void Main(string[] args)
            {
        Console.WriteLine("Serial read init");
        SerialPort port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
        port.Open();
        while(true){
          Console.WriteLine(port.ReadLine());
        }

    }
}
}

Why can't I find SQL Server Management Studio after installation?

It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

and the one for 64 bit WITH the management tools (management studio) is here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.

Java: Static vs inner class

Discussing nested classes...

The difference is that a nested class declaration that is also static can be instantiated outside of the enclosing class.

When you have a nested class declaration that is not static, Java won't let you instantiate it except via the enclosing class. The object created out of the inner class is linked to the object created from the outer class, so the inner class can reference the fields of the outer.

But if it's static, then the link does not exist, the outer fields cannot be accessed (except via an ordinary reference like any other object) and you can therefore instantiate the nested class by itself.

How to set a single, main title above all the subplots with Pyplot?

If your subplots also have titles, you may need to adjust the main title size:

plt.suptitle("Main Title", size=16)

How to loop through all the files in a directory in c # .net?

try below code

Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)

Java creating .jar file

Put all the 6 classes to 6 different projects. Then create jar files of all the 6 projects. In this manner you will get 6 executable jar files.

Change <select>'s option and trigger events with JavaScript

Unfortunately, you need to manually fire the change event. And using the Event Constructor will be the best solution.

_x000D_
_x000D_
var select = document.querySelector('#sel'),_x000D_
    input = document.querySelector('input[type="button"]');_x000D_
select.addEventListener('change',function(){_x000D_
    alert('changed');_x000D_
});_x000D_
input.addEventListener('click',function(){_x000D_
    select.value = 2;_x000D_
    select.dispatchEvent(new Event('change'));_x000D_
});
_x000D_
<select id="sel" onchange='alert("changed")'>_x000D_
  <option value='1'>One</option>_x000D_
  <option value='2'>Two</option>_x000D_
  <option value='3' selected>Three</option>_x000D_
</select>_x000D_
<input type="button" value="Change option to 2" />
_x000D_
_x000D_
_x000D_

And, of course, the Event constructor is not supported in IE. So you may need to polyfill with this:

function Event( event, params ) {
    params = params || { bubbles: false, cancelable: false, detail: undefined };
    var evt = document.createEvent( 'CustomEvent' );
    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
    return evt;
}

Can I pass parameters by reference in Java?

Can I pass parameters by reference in Java?

No.

Why ? Java has only one mode of passing arguments to methods: by value.

Note:

For primitives this is easy to understand: you get a copy of the value.

For all other you get a copy of the reference and this is called also passing by value.

It is all in this picture:

enter image description here

Excel Looping through rows and copy cell values to another worksheet

Private Sub CommandButton1_Click() 

Dim Z As Long 
Dim Cellidx As Range 
Dim NextRow As Long 
Dim Rng As Range 
Dim SrcWks As Worksheet 
Dim DataWks As Worksheet 
Z = 1 
Set SrcWks = Worksheets("Sheet1") 
Set DataWks = Worksheets("Sheet2") 
Set Rng = EntryWks.Range("B6:ad6") 

NextRow = DataWks.UsedRange.Rows.Count 
NextRow = IIf(NextRow = 1, 1, NextRow + 1) 

For Each RA In Rng.Areas 
    For Each Cellidx In RA 
        Z = Z + 1 
        DataWks.Cells(NextRow, Z) = Cellidx 
    Next Cellidx 
Next RA 
End Sub

Alternatively

Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10") 

This is a CopynPaste - Method

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean

On Error GoTo Err_Execute

'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value

Sheets("Plan").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

  'Encountered blank cell in row 2, terminate search
  If Len(Cells(2, LColumn)) = 0 Then
     MsgBox "No matching date was found."
     Exit Sub

  'Found match in row 2
  ElseIf Cells(2, LColumn) = LDate Then

     'Select values to copy from "Rolling Plan" sheet
     Sheets("Rolling Plan").Select
     Range("B5:H6").Select
     Selection.Copy

     'Paste onto "Plan" sheet
     Sheets("Plan").Select
     Cells(3, LColumn).Select
     Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
     False, Transpose:=False

     LFound = True
     MsgBox "The data has been successfully copied."

     'Continue searching
      Else
         LColumn = LColumn + 1
      End If

   Wend

   Exit Sub

Err_Execute:
  MsgBox "An error occurred."

End Sub

And there might be some methods doing that in Excel.

How to create and use resources in .NET

Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.

How to create a resource:

In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.

  • Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list.
  • Click the "Resources" tab.
  • The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options.
  • Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose.
  • At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective.

How to use a resource:

Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.

There is a static class called Properties.Resources that gives you access to all your resources, so my code ended up being as simple as:

paused = !paused;
if (paused)
    notifyIcon.Icon = Properties.Resources.RedIcon;
else
    notifyIcon.Icon = Properties.Resources.GreenIcon;

Done! Finished! Everything is simple when you know how, isn't it?

REST / SOAP endpoints for a WCF service

We must define the behavior configuration to REST endpoint

<endpointBehaviors>
  <behavior name="restfulBehavior">
   <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
  </behavior>
</endpointBehaviors>

and also to a service

<serviceBehaviors>
   <behavior>
     <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
   </behavior>
</serviceBehaviors>

After the behaviors, next step is the bindings. For example basicHttpBinding to SOAP endpoint and webHttpBinding to REST.

<bindings>
   <basicHttpBinding>
     <binding name="soapService" />
   </basicHttpBinding>
   <webHttpBinding>
     <binding name="jsonp" crossDomainScriptAccessEnabled="true" />
   </webHttpBinding>
</bindings>

Finally we must define the 2 endpoint in the service definition. Attention for the address="" of endpoint, where to REST service is not necessary nothing.

<services>
  <service name="ComposerWcf.ComposerService">
    <endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="ComposerWcf.Interface.IComposerService" />
    <endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="ComposerWcf.Interface.IComposerService" />
    <endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />
  </service>
</services>

In Interface of the service we define the operation with its attributes.

namespace ComposerWcf.Interface
{
    [ServiceContract]
    public interface IComposerService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "/autenticationInfo/{app_id}/{access_token}", ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
        Task<UserCacheComplexType_RootObject> autenticationInfo(string app_id, string access_token);
    }
}

Joining all parties, this will be our WCF system.serviceModel definition.

<system.serviceModel>

  <behaviors>
    <endpointBehaviors>
      <behavior name="restfulBehavior">
        <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
      </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />
      </behavior>
    </serviceBehaviors>
  </behaviors>

  <bindings>
    <basicHttpBinding>
      <binding name="soapService" />
    </basicHttpBinding>
    <webHttpBinding>
      <binding name="jsonp" crossDomainScriptAccessEnabled="true" />
    </webHttpBinding>
  </bindings>

  <protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
  </protocolMapping>

  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

  <services>
    <service name="ComposerWcf.ComposerService">
      <endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="ComposerWcf.Interface.IComposerService" />
      <endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="ComposerWcf.Interface.IComposerService" />
      <endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />
    </service>
  </services>

</system.serviceModel>

To test the both endpoint, we can use WCFClient to SOAP and PostMan to REST.

Can I convert long to int?

A possible way is to use the modulo operator to only let the values stay in the int32 range, and then cast it to int.

var intValue= (int)(longValue % Int32.MaxValue);

Enabling refreshing for specific html elements only

Try this in your script:

$("#YourElement").html(htmlData);

I do this in my table refreshment.

Angularjs dynamic ng-pattern validation

This is an interesting problem, complex Angular validation. The following fiddle implements what you want:

http://jsfiddle.net/2G8gA/1/

Details

I created a new directive, rpattern, that is a mix of Angular's ng-required and the ng-pattern code from input[type=text]. What it does is watch the required attribute of the field and take that into account when validating with regexp, i.e. if not required mark field as valid-pattern.

Notes

  • Most of the code is from Angular, tailored to the needs of this.
  • When the checkbox is checked, the field is required.
  • The field is not hidden when the required checkbox is false.
  • The regular expression is simplified for the demo (valid is 3 digits).

A dirty (but smaller) solution, if you do not want a new directive, would be something like:

$scope.phoneNumberPattern = (function() {
    var regexp = /^\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})$/;
    return {
        test: function(value) {
            if( $scope.requireTel === false ) {
                return true;
            }
            return regexp.test(value);
        }
    };
})();

And in HTML no changes would be required:

<input type="text" ng-model="..." ng-required="requireTel"
    ng-pattern="phoneNumberPattern" />

This actually tricks angular into calling our test() method, instead of RegExp.test(), that takes the required into account.

sql try/catch rollback/commit - preventing erroneous commit after rollback

I used below ms sql script pattern several times successfully which uses Try-Catch,Commit Transaction- Rollback Transaction,Error Tracking.

Your TRY block will be as follows

 BEGIN TRY
 BEGIN TRANSACTION T
 ----
 //your script block
 ----
 COMMIT TRANSACTION T 
 END TRY

Your CATCH block will be as follows

BEGIN CATCH
DECLARE @ErrMsg NVarChar(4000), 
        @ErrNum Int, 
        @ErrSeverity Int, 
        @ErrState Int, 
        @ErrLine Int, 
        @ErrProc NVarChar(200)
 SELECT @ErrNum = Error_Number(), 
       @ErrSeverity = Error_Severity(), 
       @ErrState = Error_State(), 
       @ErrLine = Error_Line(), 
       @ErrProc = IsNull(Error_Procedure(), '-')
 SET @ErrMsg = N'ErrLine: ' + rtrim(@ErrLine) + ', proc: ' + RTRIM(@ErrProc) + ', 
       Message: '+ Error_Message()

Your ROLLBACK script will be part of CATCH block as follows

IF (@@TRANCOUNT) > 0 
BEGIN
PRINT 'ROLLBACK: ' + SUBSTRING(@ErrMsg,1,4000)
ROLLBACK TRANSACTION T
END
ELSE
BEGIN
PRINT SUBSTRING(@ErrMsg,1,4000);   
END

END CATCH

Above different script blocks you need to use as one block. If any error happens in the TRY block it will go the the CATCH block. There it is setting various details about the error number,error severity,error line ..etc. At last all these details will get append to @ErrMsg parameter. Then it will check for the count of transaction (@@TRANCOUNT >0) , ie if anything is there in the transaction for rollback. If it is there then show the error message and ROLLBACK TRANSACTION. Otherwise simply print the error message.

We have kept our COMMIT TRANSACTION T script towards the last line of TRY block in order to make sure that it should commit the transaction(final change in the database) only after all the code in the TRY block has run successfully.

How to generate random number with the specific length in python

To get a random 3-digit number:

from random import randint
randint(100, 999)  # randint is inclusive at both ends

(assuming you really meant three digits, rather than "up to three digits".)

To use an arbitrary number of digits:

from random import randint

def random_with_N_digits(n):
    range_start = 10**(n-1)
    range_end = (10**n)-1
    return randint(range_start, range_end)

print random_with_N_digits(2)
print random_with_N_digits(3)
print random_with_N_digits(4)

Output:

33
124
5127

document.getElementById().value doesn't set the value

Try using ,

$('#points').val(request.responseText);

Combine multiple results in a subquery into a single comma-separated value

Even this will serve the purpose

Sample data

declare @t table(id int, name varchar(20),somecolumn varchar(MAX))
insert into @t
    select 1,'ABC','X' union all
    select 1,'ABC','Y' union all
    select 1,'ABC','Z' union all
    select 2,'MNO','R' union all
    select 2,'MNO','S'

Query:

SELECT ID,Name,
    STUFF((SELECT ',' + CAST(T2.SomeColumn AS VARCHAR(MAX))
     FROM @T T2 WHERE T1.id = T2.id AND T1.name = T2.name
     FOR XML PATH('')),1,1,'') SOMECOLUMN
FROM @T T1
GROUP BY id,Name

Output:

ID  Name    SomeColumn
1   ABC     X,Y,Z
2   MNO     R,S

insert datetime value in sql database with c#

INSERT INTO <table> (<date_column>) VALUES ('1/1/2010 12:00')

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

What's the difference between "git reset" and "git checkout"?

One simple use case when reverting change:
1. Use reset if you want to undo staging of a modified file.
2. Use checkout if you want to discard changes to unstaged file/s.

How many spaces will Java String.trim() remove?

From java docs(String class source),

/**
 * Returns a copy of the string, with leading and trailing whitespace
 * omitted.
 * <p>
 * If this <code>String</code> object represents an empty character
 * sequence, or the first and last characters of character sequence
 * represented by this <code>String</code> object both have codes
 * greater than <code>'&#92;u0020'</code> (the space character), then a
 * reference to this <code>String</code> object is returned.
 * <p>
 * Otherwise, if there is no character with a code greater than
 * <code>'&#92;u0020'</code> in the string, then a new
 * <code>String</code> object representing an empty string is created
 * and returned.
 * <p>
 * Otherwise, let <i>k</i> be the index of the first character in the
 * string whose code is greater than <code>'&#92;u0020'</code>, and let
 * <i>m</i> be the index of the last character in the string whose code
 * is greater than <code>'&#92;u0020'</code>. A new <code>String</code>
 * object is created, representing the substring of this string that
 * begins with the character at index <i>k</i> and ends with the
 * character at index <i>m</i>-that is, the result of
 * <code>this.substring(<i>k</i>,&nbsp;<i>m</i>+1)</code>.
 * <p>
 * This method may be used to trim whitespace (as defined above) from
 * the beginning and end of a string.
 *
 * @return  A copy of this string with leading and trailing white
 *          space removed, or this string if it has no leading or
 *          trailing white space.
 */
public String trim() {
int len = count;
int st = 0;
int off = offset;      /* avoid getfield opcode */
char[] val = value;    /* avoid getfield opcode */

while ((st < len) && (val[off + st] <= ' ')) {
    st++;
}
while ((st < len) && (val[off + len - 1] <= ' ')) {
    len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}

Note that after getting start and length it calls the substring method of String class.

How to overcome the CORS issue in ReactJS

You can have your React development server proxy your requests to that server. Simply send your requests to your local server like this: url: "/" And add the following line to your package.json file

"proxy": "https://awww.api.com"

Though if you are sending CORS requests to multiple sources, you'll have to manually configure the proxy yourself This link will help you set that up Create React App Proxying API requests

How do I share variables between different .c files?

if the variable is :

int foo;

in the 2nd C file you declare:

extern int foo;

Parsing JSON object in PHP using json_decode

Seems like you forgot the ["value"] or ->value:

echo $data[0]->weather->weatherIconUrl[0]->value;

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Prompt Dialog in Windows Forms

It's generally not a real good idea to import the VisualBasic libraries into C# programs (not because they won't work, but just for compatibility, style, and ability to upgrade), but you can call Microsoft.VisualBasic.Interaction.InputBox() to display the kind of box you're looking for.

If you can create a Windows.Forms object, that would be best, but you say you cannot do that.

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

Oracle will try to recompile invalid objects as they are referred to. Here the trigger is invalid, and every time you try to insert a row it will try to recompile the trigger, and fail, which leads to the ORA-04098 error.

You can select * from user_errors where type = 'TRIGGER' and name = 'NEWALERT' to see what error(s) the trigger actually gets and why it won't compile. In this case it appears you're missing a semicolon at the end of the insert line:

INSERT INTO Users (userID, firstName, lastName, password)
VALUES ('how', 'im', 'testing', 'this trigger')

So make it:

CREATE OR REPLACE TRIGGER newAlert
AFTER INSERT OR UPDATE ON Alerts
  BEGIN
        INSERT INTO Users (userID, firstName, lastName, password)
        VALUES ('how', 'im', 'testing', 'this trigger');
  END;           
/

If you get a compilation warning when you do that you can do show errors if you're in SQL*Plus or SQL Developer, or query user_errors again.

Of course, this assumes your Users tables does have those column names, and they are all varchar2... but presumably you'll be doing something more interesting with the trigger really.

What is the ultimate postal code and zip regex?

The problem is going to be that you probably have no good means of keeping up with the changing postal code requirements of countries on the other side of the globe and which you share no common languages. Unless you have a large enough budget to track this, you are almost certainly better off giving the responsibility of validating addresses to google or yahoo.

Both companies provide address lookup facuilities through a programmable API.

Standardize data columns in R

@BBKim pretty much gave the best answer, but it can just be done shorter. I'm surprised noone came up with it yet.

dat <- data.frame(x = rnorm(10, 30, .2), y = runif(10, 3, 5)) dat <- apply(dat, 2, function(x) (x - mean(x)) / sd(x))

Proper use of 'yield return'

This is kinda besides the point, but since the question is tagged best-practices I'll go ahead and throw in my two cents. For this type of thing I greatly prefer to make it into a property:

public static IEnumerable<Product> AllProducts
{
    get {
        using (AdventureWorksEntities db = new AdventureWorksEntities()) {
            var products = from product in db.Product
                           select product;

            return products;
        }
    }
}

Sure, it's a little more boiler-plate, but the code that uses this will look much cleaner:

prices = Whatever.AllProducts.Select (product => product.price);

vs

prices = Whatever.GetAllProducts().Select (product => product.price);

Note: I wouldn't do this for any methods that may take a while to do their work.

To get total number of columns in a table in sql

SELECT COUNT(COLUMN_NAME) 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'table'     

Extract Data from PDF and Add to Worksheet

You can open the PDF file and extract its contents using the Adobe library (which I believe you can download from Adobe as part of the SDK, but it comes with certain versions of Acrobat as well)

Make sure to add the Library to your references too (On my machine it is the Adobe Acrobat 10.0 Type Library, but not sure if that is the newest version)

Even with the Adobe library it is not trivial (you'll need to add your own error-trapping etc):

Function getTextFromPDF(ByVal strFilename As String) As String
   Dim objAVDoc As New AcroAVDoc
   Dim objPDDoc As New AcroPDDoc
   Dim objPage As AcroPDPage
   Dim objSelection As AcroPDTextSelect
   Dim objHighlight As AcroHiliteList
   Dim pageNum As Long
   Dim strText As String

   strText = ""
   If (objAvDoc.Open(strFilename, "") Then
      Set objPDDoc = objAVDoc.GetPDDoc
      For pageNum = 0 To objPDDoc.GetNumPages() - 1
         Set objPage = objPDDoc.AcquirePage(pageNum)
         Set objHighlight = New AcroHiliteList
         objHighlight.Add 0, 10000 ' Adjust this up if it's not getting all the text on the page
         Set objSelection = objPage.CreatePageHilite(objHighlight)

         If Not objSelection Is Nothing Then
            For tCount = 0 To objSelection.GetNumText - 1
               strText = strText & objSelection.GetText(tCount)
            Next tCount
         End If
      Next pageNum
      objAVDoc.Close 1
   End If

   getTextFromPDF = strText

End Function

What this does is essentially the same thing you are trying to do - only using Adobe's own library. It's going through the PDF one page at a time, highlighting all of the text on the page, then dropping it (one text element at a time) into a string.

Keep in mind what you get from this could be full of all kinds of non-printing characters (line feeds, newlines, etc) that could even end up in the middle of what look like contiguous blocks of text, so you may need additional code to clean it up before you can use it.

Hope that helps!

Is Python interpreted, or compiled, or both?

Yes, it is both compiled and interpreted language. Then why we generally call it as interpreted language?

see how it is both- compiled and interpreted?

First of all I want to tell that you will like my answer more if you are from the Java world.

In the Java the source code first gets converted to the byte code through javac compiler then directed to the JVM(responsible for generating the native code for execution purpose). Now I want to show you that we call the Java as compiled language because we can see that it really compiles the source code and gives the .class file(nothing but bytecode) through:

javac Hello.java -------> produces Hello.class file

java Hello -------->Directing bytecode to JVM for execution purpose

The same thing happens with python i.e. first the source code gets converted to the bytecode through the compiler then directed to the PVM(responsible for generating the native code for execution purpose). Now I want to show you that we usually call the Python as an interpreted language because the compilation happens behind the scene and when we run the python code through:

python Hello.py -------> directly excutes the code and we can see the output provied that code is syntactically correct

@ python Hello.py it looks like it directly executes but really it first generates the bytecode that is interpreted by the interpreter to produce the native code for the execution purpose.

CPython- Takes the responsibility of both compilation and interpretation.

Look into the below lines if you need more detail:

As I mentioned that CPython compiles the source code but actual compilation happens with the help of cython then interpretation happens with the help of CPython

Now let's talk a little bit about the role of Just-In-Time compiler in Java and Python

In JVM the Java Interpreter exists which interprets the bytecode line by line to get the native machine code for execution purpose but when Java bytecode is executed by an interpreter, the execution will always be slower. So what is the solution? the solution is Just-In-Time compiler which produces the native code which can be executed much more quickly than that could be interpreted. Some JVM vendors use Java Interpreter and some use Just-In-Time compiler. Reference: click here

In python to get around the interpreter to achieve the fast execution use another python implementation(PyPy) instead of CPython. click here for other implementation of python including PyPy.

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

Following points really helped me a lot. There might be other points too, but these are very crucial:

  1. Use application context(instead of activity.this) where ever possible.
  2. Stop and release your threads in onPause() method of activity
  3. Release your views / callbacks in onDestroy() method of activity

How to force Chrome's script debugger to reload javascript?

If the files which you are loading are cached and if the changes you have made does not reflect in the code then there are 2 ways you can deal with this

  1. Clear the Cache as everyone told

  2. If u want Cache and only the files have to be reloaded , you can go to network tab of the dev tool and clear whatever was loaded. next time it will not load it from cache. you will have your latest changes.

What's the best way to detect a 'touch screen' device using JavaScript?

I used pieces of the code above to detect whether touch, so my fancybox iframes would show up on desktop computers and not on touch. I noticed that Opera Mini for Android 4.0 was still registering as a non-touch device when using blmstr's code alone. (Does anyone know why?)

I ended up using:

<script>
$(document).ready(function() {
    var ua = navigator.userAgent;
    function is_touch_device() { 
        try {  
            document.createEvent("TouchEvent");  
            return true;  
        } catch (e) {  
            return false;  
        }  
    }

    if ((is_touch_device()) || ua.match(/(iPhone|iPod|iPad)/) 
    || ua.match(/BlackBerry/) || ua.match(/Android/)) {
        // Touch browser
    } else {
        // Lightbox code
    }
});
</script>

Print values for multiple variables on the same line from within a for-loop

As an additional note, there is no need for the for loop because of R's vectorization.

This:

P <- 243.51
t <- 31 / 365
n <- 365

for (r in seq(0.15, 0.22, by = 0.01))    
     A <- P * ((1 + (r/ n))^ (n * t))
     interest <- A - P
}

is equivalent to:

P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P

Because r is a vector, the expression above containing it is performed for all values of the vector.

Angular 5 Service to read local .json file

Assumes, you have a data.json file in the src/app folder of your project with the following values:

[
    {
        "id": 1,
        "name": "Licensed Frozen Hat",
        "description": "Incidunt et magni est ut.",
        "price": "170.00",
        "imageUrl": "https://source.unsplash.com/1600x900/?product",
        "quantity": 56840
    },
    ...
]

3 Methods for Reading Local JSON Files

Method 1: Reading Local JSON Files Using TypeScript 2.9+ import Statement

import { Component, OnInit } from '@angular/core';
import * as data from './data.json';

@Component({
  selector: 'app-root',
  template: `<ul>
      <li *ngFor="let product of products">

      </li>
  </ul>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Angular Example';

  products: any = (data as any).default;

  constructor(){}
  ngOnInit(){
    console.log(data);
  }
}

Method 2: Reading Local JSON Files Using Angular HttpClient

import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http";


@Component({
  selector: 'app-root',
  template: `<ul>
      <li *ngFor="let product of products">

      </li>
  </ul>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Angular Example';
  products: any = [];

  constructor(private httpClient: HttpClient){}
  ngOnInit(){
    this.httpClient.get("assets/data.json").subscribe(data =>{
      console.log(data);
      this.products = data;
    })
  }
}

Method 3: Reading Local JSON Files in Offline Angular Apps Using ES6+ import Statement

If your Angular application goes offline, reading the JSON file with HttpClient will fail. In this case, we have one more method to import local JSON files using the ES6+ import statement which supports importing JSON files.

But first we need to add a typing file as follows:

declare module "*.json" {
  const value: any;
  export default value;
}

Add this inside a new file json-typings.d.ts file in the src/app folder.

Now, you can import JSON files just like TypeScript 2.9+.

import * as data from "data.json";

Setting focus to a textbox control

Quite simple :

For the tab control, you need to handle the _SelectedIndexChanged event:

Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As System.EventArgs) _
  Handles TabControl1.SelectedIndexChanged

If TabControl1.SelectedTab.Name = "TabPage1" Then
    TextBox2.Focus()
End If
If TabControl1.SelectedTab.Name = "TabPage2" Then
    TextBox4.Focus()
End If

Iterating over a 2 dimensional python list

This is the correct way.

>>> x = [ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ]
>>> for i in range(len(x)):
        for j in range(len(x[i])):
                print(x[i][j])


0,0
0,1
1,0
1,1
2,0
2,1
>>> 

Make column fixed position in bootstrap

With bootstrap 4 just use col-auto

<div class="container-fluid">
    <div class="row">
        <div class="col-sm-auto">
            Fixed content
        </div>
        <div class="col-sm">
            Normal scrollable content
        </div>
    </div>
</div>

Ajax success event not working

Add 'error' callback (just like 'success') this way:

$.ajax({
   type: 'POST',
   url: 'submit1.php',
   data: $("#regist").serialize(),
   dataType: 'json',
   success: function() {
      $("#loading").append("<h2>you are here</h2>");
   },
   error: function(jqXhr, textStatus, errorMessage){
      console.log("Error: ", errorMessage);
   }
});

So, in my case I saw in console:

Error:  SyntaxError: Unexpected end of JSON input
  at parse (<anonymous>), ..., etc.

Callback to a Fragment from a DialogFragment

Maybe a bit late, but may help other people with the same question like I did.

You can use setTargetFragment on Dialog before showing, and in dialog you can call getTargetFragment to get the reference.

Check if a given time lies between two times regardless of date

Logically if you do the following you should always be ok granted we use military time...

if start time is greater than end time add 24 to end time else use times as is

compare current time to be inbetween start and end time.

How to escape "&" in XML?

use &amp; in place of &

change to

<string name="magazine">Newspaper &amp; Magazines</string>

How to delete duplicate rows in SQL Server?

After trying the suggested solution above, that works for small medium tables. I can suggest that solution for very large tables. since it runs in iterations.

  1. Drop all dependency views of the LargeSourceTable
  2. you can find the dependecies by using sql managment studio, right click on the table and click "View Dependencies"
  3. Rename the table:
  4. sp_rename 'LargeSourceTable', 'LargeSourceTable_Temp'; GO
  5. Create the LargeSourceTable again, but now, add a primary key with all the columns that define the duplications add WITH (IGNORE_DUP_KEY = ON)
  6. For example:

    CREATE TABLE [dbo].[LargeSourceTable] ( ID int IDENTITY(1,1), [CreateDate] DATETIME CONSTRAINT [DF_LargeSourceTable_CreateDate] DEFAULT (getdate()) NOT NULL, [Column1] CHAR (36) NOT NULL, [Column2] NVARCHAR (100) NOT NULL, [Column3] CHAR (36) NOT NULL, PRIMARY KEY (Column1, Column2) WITH (IGNORE_DUP_KEY = ON) ); GO

  7. Create again the views that you dropped in the first place for the new created table

  8. Now, Run the following sql script, you will see the results in 1,000,000 rows per page, you can change the row number per page to see the results more often.

  9. Note, that I set the IDENTITY_INSERT on and off because one the columns contains auto incremental id, which I'm also copying

SET IDENTITY_INSERT LargeSourceTable ON DECLARE @PageNumber AS INT, @RowspPage AS INT DECLARE @TotalRows AS INT declare @dt varchar(19) SET @PageNumber = 0 SET @RowspPage = 1000000 select @TotalRows = count (*) from LargeSourceTable_TEMP

While ((@PageNumber - 1) * @RowspPage < @TotalRows )
Begin
    begin transaction tran_inner
        ; with cte as
        (
            SELECT * FROM LargeSourceTable_TEMP ORDER BY ID
            OFFSET ((@PageNumber) * @RowspPage) ROWS
            FETCH NEXT @RowspPage ROWS ONLY
        )

        INSERT INTO LargeSourceTable 
        (
             ID                     
            ,[CreateDate]       
            ,[Column1]   
            ,[Column2] 
            ,[Column3]       
        )       
        select 
             ID                     
            ,[CreateDate]       
            ,[Column1]   
            ,[Column2] 
            ,[Column3]       
        from cte

    commit transaction tran_inner

    PRINT 'Page: ' + convert(varchar(10), @PageNumber)
    PRINT 'Transfered: ' + convert(varchar(20), @PageNumber * @RowspPage)
    PRINT 'Of: ' + convert(varchar(20), @TotalRows)

    SELECT @dt = convert(varchar(19), getdate(), 121)
    RAISERROR('Inserted on: %s', 0, 1, @dt) WITH NOWAIT
    SET @PageNumber = @PageNumber + 1
End

SET IDENTITY_INSERT LargeSourceTable OFF

How to have css3 animation to loop forever

Whilst Elad's solution will work, you can also do it inline:

   -moz-animation: fadeinphoto 7s 20s infinite;
-webkit-animation: fadeinphoto 7s 20s infinite;
     -o-animation: fadeinphoto 7s 20s infinite;
        animation: fadeinphoto 7s 20s infinite;

How to install a private NPM module without my own registry?

I had this same problem, and after some searching around, I found Reggie (https://github.com/mbrevoort/node-reggie). It looks pretty solid. It allows for lightweight publishing of NPM modules to private servers. Not perfect (no authentication upon installation), and it's still really young, but I tested it locally, and it seems to do what it says it should do.

That is... (and this just from their docs)

npm install -g reggie
reggie-server -d ~/.reggie

then cd into your module directory and...

reggie -u http://<host:port> publish 
reggie -u http://127.0.0.1:8080 publish 

finally, you can install packages from reggie just by using that url either in a direct npm install command, or from within a package.json... like so

npm install http://<host:port>/package/<name>/<version>
npm install http://<host:port>/package/foo/1.0.0

or..

dependencies: {
    "foo": "http://<host:port>/package/foo/1.0.0"
}

Enums in Javascript with ES6

Check how TypeScript does it. Basically they do the following:

const MAP = {};

MAP[MAP[1] = 'A'] = 1;
MAP[MAP[2] = 'B'] = 2;

MAP['A'] // 1
MAP[1] // A

Use symbols, freeze object, whatever you want.

clear table jquery

$("#employeeTable td").parent().remove();

This will remove all tr having td as child. i.e all rows except the header will be deleted.

How to apply color in Markdown?

When you want to use pure Markdown (without nested HTML), you can use Emojis to draw attention to some fragment of the file, i.e. ??WARNING??, IMPORTANT? or NEW.

Setting Custom ActionBar Title from Fragment

What you're doing is correct. Fragments don't have access to the ActionBar APIs, so you have to call getActivity. Unless your Fragment is a static inner class, in which case you should create a WeakReference to the parent and call Activity.getActionBar from there.

To set the title for your ActionBar, while using a custom layout, in your Fragment you'll need to call getActivity().setTitle(YOUR_TITLE).

The reason you call setTitle is because you're calling getTitle as the title of your ActionBar. getTitle returns the title for that Activity.

If you don't want to get call getTitle, then you'll need to create a public method that sets the text of your TextView in the Activity that hosts the Fragment.

In your Activity:

public void setActionBarTitle(String title){
    YOUR_CUSTOM_ACTION_BAR_TITLE.setText(title);
}

In your Fragment:

((MainFragmentActivity) getActivity()).setActionBarTitle(YOUR_TITLE);

Docs:

Activity.getTitle

Activity.setTitle

Also, you don't need to call this.whatever in the code you provided, just a tip.

Increase number of axis ticks

Additionally,

ggplot(dat, aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = seq(min(dat$x), max(dat$x), by = 0.05))

Works for binned or discrete scaled x-axis data (I.e., rounding not necessary).

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

You can generate many types of barcodes, namely 1D or 2D. Add the required library:

require_once('class/BCGcode39.barcode.php');

Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:

Example

Since several have asked for an example here is what I was able to do to get it done

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

require_once('class/BCGcode128.barcode.php');

header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();
$code->parse('HELLO');

$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);

$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);

to

$drawing = new BCGDrawing('image.png', $color_white);

SQL recursive query on self referencing table (Oracle)

What about using PRIOR,

so

SELECT id, parent_id, PRIOR name
   FROM tbl 
START WITH id = 1 
CONNECT BY PRIOR id = parent_id`

or if you want to get the root name

SELECT id, parent_id, CONNECT_BY_ROOT name
   FROM tbl 
START WITH id = 1 
CONNECT BY PRIOR id = parent_id

How to implement endless list with RecyclerView?

I have created LoadMoreRecyclerView using Abdulaziz Noor Answer

LoadMoreRecyclerView

public class LoadMoreRecyclerView extends RecyclerView  {

    private boolean loading = true;
    int pastVisiblesItems, visibleItemCount, totalItemCount;
    //WrapperLinearLayout is for handling crash in RecyclerView
    private WrapperLinearLayout mLayoutManager;
    private Context mContext;
    private OnLoadMoreListener onLoadMoreListener;

    public LoadMoreRecyclerView(Context context) {
        super(context);
        mContext = context;
        init();
    }

    public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }

    public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        init();
    }

    private void init(){
        mLayoutManager = new WrapperLinearLayout(mContext,LinearLayoutManager.VERTICAL,false);
        this.setLayoutManager(mLayoutManager);
        this.setItemAnimator(new DefaultItemAnimator());
        this.setHasFixedSize(true);
    }

    @Override
    public void onScrolled(int dx, int dy) {
        super.onScrolled(dx, dy);

        if(dy > 0) //check for scroll down
        {
            visibleItemCount = mLayoutManager.getChildCount();
            totalItemCount = mLayoutManager.getItemCount();
            pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

            if (loading)
            {
                if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount)
                {
                    loading = false;
                    Log.v("...", "Call Load More !");
                    if(onLoadMoreListener != null){
                        onLoadMoreListener.onLoadMore();
                    }
                    //Do pagination.. i.e. fetch new data
                }
            }
        }
    }

    @Override
    public void onScrollStateChanged(int state) {
        super.onScrollStateChanged(state);
    }

    public void onLoadMoreCompleted(){
        loading = true;
    }

    public void setMoreLoading(boolean moreLoading){
        loading = moreLoading;
    }

    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
    }
}

WrapperLinearLayout

public class WrapperLinearLayout extends LinearLayoutManager
{
    public WrapperLinearLayout(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        try {
            super.onLayoutChildren(recycler, state);
        } catch (IndexOutOfBoundsException e) {
            Log.e("probe", "meet a IOOBE in RecyclerView");
        }
    }
}

//Add it in xml like

<your.package.LoadMoreRecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</your.package.LoadMoreRecyclerView>

OnCreate or onViewCreated

mLoadMoreRecyclerView = (LoadMoreRecyclerView) view.findViewById(R.id.recycler_view);
mLoadMoreRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                callYourService(StartIndex);
            }
        });

callYourService

private void callYourService(){
    //callyour Service and get response in any List

    List<AnyModelClass> newDataFromServer = getDataFromServerService();
    //Enable Load More
    mLoadMoreRecyclerView.onLoadMoreCompleted();

    if(newDataFromServer != null && newDataFromServer.size() > 0){
            StartIndex += newDataFromServer.size();

            if (newDataFromServer.size() < Integer.valueOf(MAX_ROWS)) {
                    //StopLoading..
                   mLoadMoreRecyclerView.setMoreLoading(false);
            }
    }
    else{
            mLoadMoreRecyclerView.setMoreLoading(false);
            mAdapter.notifyDataSetChanged();
    }
}

What is the dual table in Oracle?

It is a dummy table with one element in it. It is useful because Oracle doesn't allow statements like

 SELECT 3+4

You can work around this restriction by writing

 SELECT 3+4 FROM DUAL

instead.

How do I erase an element from std::vector<> by index?

Erase an element with index :

vec.erase(vec.begin() + index);

Erase an element with value:

vec.erase(find(vec.begin(),vec.end(),value));

How can I make grep print the lines below and above each matching line?

grep's -A 1 option will give you one line after; -B 1 will give you one line before; and -C 1 combines both to give you one line both before and after, -1 does the same.

How to check if an element does NOT have a specific class?

reading through this 6yrs later and thought I'd also take a hack at it, also in the TIMTOWTDI vein...:D, hoping it isn't incorrect 'JS etiquette'.

I usually set up a var with the condition and then refer to it later on..i.e;

// var set up globally OR locally depending on your requirements
var hC;

function(el) {
  var $this = el;
  hC = $this.hasClass("test");

  // use the variable in the conditional statement
  if (!hC) {
    //
  }
}

Although I should mention that I do this because I mainly use the conditional ternary operator and want clean code. So in this case, all i'd have is this:

hC ? '' : foo(x, n) ;
   // OR -----------
!hC ? foo(x, n) : '' ;

...instead of this:

$this.hasClass("test") ? '' : foo(x, n) ;
   // OR -----------
(!$this.hasClass("test")) ? foo(x, n) : '' ;

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

How to get all elements inside "div" that starts with a known text

Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :

var elements = document.getElementById('parentContainer').children;

Option 2: Likely slowest :

var elements = document.getElementById('parentContainer').getElementsByTagName('*');

Option 3: Requires change to code (wrap a form instead of a div around it) :

// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;

var matches = [];

for (var i = 0; i < elements.length; i++)
    if (elements[i].value.indexOf('q17_') == 0)
        matches.push(elements[i]);

How to get instance variables in Python?

Use vars()

class Foo(object):
    def __init__(self):
        self.a = 1
        self.b = 2

vars(Foo()) #==> {'a': 1, 'b': 2}
vars(Foo()).keys() #==> ['a', 'b']

A good Sorted List for Java

Generally you can't have constant time look up and log time deletions/insertions, but if you're happy with log time look ups then you can use a SortedList.

Not sure if you'll trust my coding but I recently wrote a SortedList implementation in Java, which you can download from http://www.scottlogic.co.uk/2010/12/sorted_lists_in_java/. This implementation allows you to look up the i-th element of the list in log time.

How to call same method for a list of objects?

It seems like there would be a more Pythonic way of doing this, but I haven't found it yet.

I use "map" sometimes if I'm calling the same function (not a method) on a bunch of objects:

map(do_something, a_list_of_objects)

This replaces a bunch of code that looks like this:

 do_something(a)
 do_something(b)
 do_something(c)
 ...

But can also be achieved with a pedestrian "for" loop:

  for obj in a_list_of_objects:
       do_something(obj)

The downside is that a) you're creating a list as a return value from "map" that's just being throw out and b) it might be more confusing that just the simple loop variant.

You could also use a list comprehension, but that's a bit abusive as well (once again, creating a throw-away list):

  [ do_something(x) for x in a_list_of_objects ]

For methods, I suppose either of these would work (with the same reservations):

map(lambda x: x.method_call(), a_list_of_objects)

or

[ x.method_call() for x in a_list_of_objects ]

So, in reality, I think the pedestrian (yet effective) "for" loop is probably your best bet.

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

Is header('Content-Type:text/plain'); necessary at all?

Define "necessary".

It is necessary if you want the browser to know what the type of the file is. PHP automatically sets the Content-Type header to text/html if you don't override it so your browser is treating it as an HTML file that doesn't contain any HTML. If your output contained any HTML you'd see very different outcomes. If you were to send:

<b><i>test</i></b>

a Content-Type: text/html would output:

test

whereas Content-Type: text/plain would output:

<b><i>test</i></b>

TLDR Version: If you really are only outputing text then it doesn't really matter, but it IS wrong.

Switch on ranges of integers in JavaScript

If you need check ranges you are probably better off with if and else if statements, like so:

if (range > 0 && range < 5)
{
    // ..
}
else if (range > 5 && range < 9)
{
    // ..
}
else
{
    // Fall through
}

A switch could get large on bigger ranges.

SQL Server String or binary data would be truncated

You will need to post the table definitions for the source and destination tables for us to figure out where the issue is but the bottom line is that one of your columns in the source table is bigger than your destination columns. It could be that you are changing formats in a way you were not aware of. The database model you are moving from is important in figuring that out as well.

How to get image width and height in OpenCV?

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 

Centering a Twitter Bootstrap button

Since you want to center the button, and not the text, what I've done in the past is add a class, then use that class to center the button:

<button class="btn btn-large btn-primary newclass" type="button">Submit</button>

and the CSS would be:

.btn.newclass {width:25%; display:block; margin: 0 auto;}

The "width" value is up to you, and you can play with that to get the right look.

Steve

How can I apply a function to every row/column of a matrix in MATLAB?

For completeness/interest I'd like to add that matlab does have a function that allows you to operate on data per-row rather than per-element. It is called rowfun (http://www.mathworks.se/help/matlab/ref/rowfun.html), but the only "problem" is that it operates on tables (http://www.mathworks.se/help/matlab/ref/table.html) rather than matrices.

How to trim a file extension from a String in JavaScript?

I like this one because it is a one liner which isn't too hard to read:

filename.substring(0, filename.lastIndexOf('.')) || filename

How to use an array list in Java?

You could either get your strings by index (System.out.println(S.get(0));) or iterate through it:

for (String s : S) {
  System.out.println(s);
}

For other ways to iterate through a list (and their implications) see traditional for loop vs Iterator in Java.

Additionally:

  • you shouldn't use variable names starting with upper-case letters
  • you should parametrize your array list: ArrayList<String> list = new ArrayList<String>();
  • you should get familiar with Java's extensive API documentation (aka Javadoc), e.g. Java 5, Java 6

How to find the length of an array in shell?

in tcsh or csh:

~> set a = ( 1 2 3 4 5 )
~> echo $#a
5

How to fix syntax error, unexpected T_IF error in php?

Here is the issue

  $total_result = $result->num_rows;

try this

<?php
if ($result = $mysqli->query("SELECT * FROM players ORDER BY id"))
{
    if ($result->num_rows > 0)
    {
        $total_result = $result->num_rows;
        $total_pages = ceil($total_result / $per_page);

        if(isset($_GET['page']) && is_numeric($_GET['page']))
        {
            $show_page = $_GET['page'];

            if ($show_page > 0 && $show_page <= $total_pages)
            {
                $start = ($show_page - 1) * $per_page;
                $end = $start + $per_page;
            }
            else
            {
                $start = 0;
                $end = $per_page;
            }               

        }
        else
        {
            $start = 0;
            $end = $per_page;
        }


        //display paginations
        echo "<p> View pages: ";
        for ($i=1; $i < $total_pages; $i++)
        { 
            if (isset($_GET['page']) && $_GET['page'] == $i)
            {
                echo  $i . " ";
            }
            else
            {
                echo "<a href='view-pag.php?$i'>" . $i . "</a> | ";
            }

        }
        echo "</p>";

    }
    else
    {
        echo "No result to display.";
    }

}
else
{
    echo "Error: " . $mysqli->error;
}


?>

ssh connection refused on Raspberry Pi

Apparently, the SSH server on Raspbian is now disabled by default. If there is no server listening for connections, it will not accept them. You can manually enable the SSH server according to this raspberrypi.org tutorial :

As of the November 2016 release, Raspbian has the SSH server disabled by default.

There are now multiple ways to enable it. Choose one:

From the desktop

  1. Launch Raspberry Pi Configuration from the Preferences menu
  2. Navigate to the Interfaces tab
  3. Select Enabled next to SSH
  4. Click OK

From the terminal with raspi-config

  1. Enter sudo raspi-config in a terminal window
  2. Select Interfacing Options
  3. Navigate to and select SSH
  4. Choose Yes
  5. Select Ok
  6. Choose Finish

Start the SSH service with systemctl

sudo systemctl enable ssh
sudo systemctl start ssh

On a headless Raspberry Pi

For headless setup, SSH can be enabled by placing a file named ssh, without any extension, onto the boot partition of the SD card. When the Pi boots, it looks for the ssh file. If it is found, SSH is enabled, and the file is deleted. The content of the file does not matter: it could contain text, or nothing at all.

How to pass multiple parameters in a querystring

I use the AbsoluteUri and you can get it like this:

string myURI = Request.Url.AbsoluteUri;
 if (!WebSecurity.IsAuthenticated) {
        Response.Redirect("~/Login?returnUrl="
            + Request.Url.AbsoluteUri );

Then after you login:

var returnUrl = Request.QueryString["returnUrl"];
 if(WebSecurity.Login(username,password,true)){
                Context.RedirectLocal(returnUrl);

It works well for me.

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

str.split() without any arguments splits on runs of whitespace characters:

>>> s = 'I am having a very nice day.'
>>> 
>>> len(s.split())
7

From the linked documentation:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

how to get the last part of a string before a certain character?

You are looking for str.rsplit(), with a limit:

print x.rsplit('-', 1)[0]

.rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.

Another option is to use str.rpartition(), which will only ever split just once:

print x.rpartition('-')[0]

For splitting just once, str.rpartition() is the faster method as well; if you need to split more than once you can only use str.rsplit().

Demo:

>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'

and the same with str.rpartition()

>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'

How to make a div have a fixed size?

you can give it a max-height and max-width in your .css

.fontpixel{max-width:200px; max-height:200px;}

in addition to your height and width properties

WPF ListView turn off selection

Use the code below:

<ListView.ItemContainerStyle>
    <Style TargetType="{x:Type ListViewItem}">
        <Setter Property="Background" Value="Transparent" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListViewItem}">
                    <ContentPresenter />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ListView.ItemContainerStyle>

How can I modify the size of column in a MySQL table?

ALTER TABLE <tablename> CHANGE COLUMN <colname> <colname> VARCHAR(65536);

You have to list the column name twice, even if you aren't changing its name.

Note that after you make this change, the data type of the column will be MEDIUMTEXT.


Miky D is correct, the MODIFY command can do this more concisely.


Re the MEDIUMTEXT thing: a MySQL row can be only 65535 bytes (not counting BLOB/TEXT columns). If you try to change a column to be too large, making the total size of the row 65536 or greater, you may get an error. If you try to declare a column of VARCHAR(65536) then it's too large even if it's the only column in that table, so MySQL automatically converts it to a MEDIUMTEXT data type.

mysql> create table foo (str varchar(300));
mysql> alter table foo modify str varchar(65536);
mysql> show create table foo;
CREATE TABLE `foo` (
  `str` mediumtext
) ENGINE=MyISAM DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

I misread your original question, you want VARCHAR(65353), which MySQL can do, as long as that column size summed with the other columns in the table doesn't exceed 65535.

mysql> create table foo (str1 varchar(300), str2 varchar(300));
mysql> alter table foo modify str2 varchar(65353);
ERROR 1118 (42000): Row size too large. 
The maximum row size for the used table type, not counting BLOBs, is 65535. 
You have to change some columns to TEXT or BLOBs

How do I install cURL on cygwin?

I just ran into this.

If you're not seeing curl in the list (see ibaralf's screenshot), then you may have out-of-date cygwin sources. In one of the screens in cygwin's setup.exe wizard, you have the option to "Install from Internet" or "Install from Local Directory". If you have the "Install from Local Directory" option enabled, then you may not see curl in the list. Switch to "Install from Internet" and select a mirror and then you should see curl.

Merging 2 branches together in GIT

If you want to merge changes in SubBranch to MainBranch

  1. you should be on MainBranch git checkout MainBranch
  2. then run merge command git merge SubBranch

Best data type to store money values in MySQL

It depends on your need.

Using DECIMAL(10,2) usually is enough but if you need a little bit more precise values you can set DECIMAL(10,4).

If you work with big values replace 10 with 19.

Testing if a checkbox is checked with jQuery

Use:

$("#ans option:selected").val()

Debugging iframes with Chrome developer tools

Currently evaluation in the console is performed in the context of the main frame in the page and it adheres to the same cross-origin policy as the main frame itself. This means that you cannot access elements in the iframe unless the main frame can. You can still set breakpoints in and debug your code using Scripts panel though.

Update: This is no longer true. See Metagrapher's answer.

Read lines from a file into a Bash array

One alternate way if file contains strings without spaces with 1string each line:

fileItemString=$(cat  filename |tr "\n" " ")

fileItemArray=($fileItemString)

Check:

Print whole Array:

${fileItemArray[*]}

Length=${#fileItemArray[@]}

Creating a Plot Window of a Particular Size

Use dev.new(). (See this related question.)

plot(1:10)
dev.new(width=5, height=4)
plot(1:20)

To be more specific which units are used:

dev.new(width=5, height=4, unit="in")
plot(1:20)
dev.new(width = 550, height = 330, unit = "px")
plot(1:15)

edit additional argument for Rstudio (May 2020), (thanks user Soren Havelund Welling)

For Rstudio, add dev.new(width=5,height=4,noRStudioGD = TRUE)

.htaccess not working on localhost with XAMPP

Try

<IfModule mod_rewrite.so>
...
...
...
</IfModule>

instead of <IfModule mod_rewrite.c>