Programs & Examples On #Installshield 2011

Spring-Security-Oauth2: Full authentication is required to access this resource

I had the same problem, but I solve this with the following class:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class OAuthSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}

Notepad++ cached files location

I have discovered that NotePad++ now also creates a subfolder at the file location, called nppBackup. So if your file lived in a folder called c:/thisfolder have a look to see if there's a folder called c:/thisfolder/nppBackup.

Occasionally I couldn't find the backup in AppData\Roaming\Notepad++\backup, but I found it in nppBackup.

Calendar Recurring/Repeating Events - Best Storage Method

@Rogue Coder

This is great!

You could simply use the modulo operation (MOD or % in mysql) to make your code simple at the end:

Instead of:

AND (
    ( CASE ( 1299132000 - EM1.`meta_value` )
        WHEN 0
          THEN 1
        ELSE ( 1299132000 - EM1.`meta_value` )
      END
    ) / EM2.`meta_value`
) = 1

Do:

$current_timestamp = 1299132000 ;

AND ( ('$current_timestamp' - EM1.`meta_value` ) MOD EM2.`meta_value`) = 1")

To take this further, one could include events that do not recur for ever.

Something like "repeat_interval_1_end" to denote the date of the last "repeat_interval_1" could be added. This however, makes the query more complicated and I can't really figure out how to do this ...

Maybe someone could help!

Find all files in a directory with extension .txt in Python

This code makes my life simpler.

import os
fnames = ([file for root, dirs, files in os.walk(dir)
    for file in files
    if file.endswith('.txt') #or file.endswith('.png') or file.endswith('.pdf')
    ])
for fname in fnames: print(fname)

Extract the first (or last) n characters of a string

You can easily obtain Right() and Left() functions starting from the Rbase package:

  • right function

    right = function (string, char) {
        substr(string,nchar(string)-(char-1),nchar(string))
    }
    
  • left function

    left = function (string,char) {
        substr(string,1,char)
    }
    

you can use those two custom-functions exactly as left() and right() in excel. Hope you will find it useful

How to add hyperlink in JLabel?

You can do this using a JLabel, but an alternative would be to style a JButton. That way, you don't have to worry about accessibility and can just fire events using an ActionListener.

  public static void main(String[] args) throws URISyntaxException {
    final URI uri = new URI("http://java.sun.com");
    class OpenUrlAction implements ActionListener {
      @Override public void actionPerformed(ActionEvent e) {
        open(uri);
      }
    }
    JFrame frame = new JFrame("Links");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(100, 400);
    Container container = frame.getContentPane();
    container.setLayout(new GridBagLayout());
    JButton button = new JButton();
    button.setText("<HTML>Click the <FONT color=\"#000099\"><U>link</U></FONT>"
        + " to go to the Java website.</HTML>");
    button.setHorizontalAlignment(SwingConstants.LEFT);
    button.setBorderPainted(false);
    button.setOpaque(false);
    button.setBackground(Color.WHITE);
    button.setToolTipText(uri.toString());
    button.addActionListener(new OpenUrlAction());
    container.add(button);
    frame.setVisible(true);
  }

  private static void open(URI uri) {
    if (Desktop.isDesktopSupported()) {
      try {
        Desktop.getDesktop().browse(uri);
      } catch (IOException e) { /* TODO: error handling */ }
    } else { /* TODO: error handling */ }
  }

How do I calculate someone's age in Java?

import java.io.*;

class AgeCalculator
{
    public static void main(String args[])
    {
        InputStreamReader ins=new InputStreamReader(System.in);
        BufferedReader hey=new BufferedReader(ins);

        try
        {
            System.out.println("Please enter your name: ");
            String name=hey.readLine();

            System.out.println("Please enter your birth date: ");
            String date=hey.readLine();

            System.out.println("please enter your birth month:");
            String month=hey.readLine();

            System.out.println("please enter your birth year:");
            String year=hey.readLine();

            System.out.println("please enter current year:");
            String cYear=hey.readLine();

            int bDate = Integer.parseInt(date);
            int bMonth = Integer.parseInt(month);
            int bYear = Integer.parseInt(year);
            int ccYear=Integer.parseInt(cYear);

            int age;

            age = ccYear-bYear;
            int totalMonth=12;
            int yourMonth=totalMonth-bMonth;

            System.out.println(" Hi " + name + " your are " + age + " years " + yourMonth + " months old ");
        }
        catch(IOException err)
        {
            System.out.println("");
        }
    }
}

Can constructors be async?

Constructor acts very similarly to a method returning the constructed type. And async method can't return just any type, it has to be either “fire and forget” void, or Task.

If the constructor of type T actually returned Task<T>, that would be very confusing, I think.

If the async constructor behaved the same way as an async void method, that kind of breaks what constructor is meant to be. After constructor returns, you should get a fully initialized object. Not an object that will be actually properly initialized at some undefined point in the future. That is, if you're lucky and the async initialization doesn't fail.

All this is just a guess. But it seems to me that having the possibility of an async constructor brings more trouble than it's worth.

If you actually want the “fire and forget” semantics of async void methods (which should be avoided, if possible), you can easily encapsulate all the code in an async void method and call that from your constructor, as you mentioned in the question.

Best way to work with dates in Android SQLite

"SELECT  "+_ID+" ,  "+_DESCRIPTION +","+_CREATED_DATE +","+_DATE_TIME+" FROM "+TBL_NOTIFICATION+" ORDER BY "+"strftime(%s,"+_DATE_TIME+") DESC";

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

I had the same requirement and solved it using these components:

The table component ng-grid is capable of displaying hundreds of rows in a scrollable grid. If you have to deal with thousands of entries you are better off using ng-grid's paginator. The documentation of ng-grid is excellent and contains many examples. Sorting and searching are supported even in combination with pagination.

Here is a screenshot from a current project to give you an impression how it looks like:

enter image description here

[UPDATE July 2017]

After having ng-grid in production for a couple of years, I can still tell that there are no major issues with this component. Yes, plenty of minor bugs, but no show stoppers (at least in my use cases). Having said that, I would strongly advice against using this component if you start a project from the scratch. This component is a good option only if you are bound to AngularJS 1.0.x. If you are free to choose the Angular version, go for a newer component. A list of table components for Angular 4 was compiled by Sam Deering in this blog.

Show a div with Fancybox

I use approach with appending "singleton" link for element you want to show in fancybox. This is code, what I use with some minor edits:

function showElementInPopUp(elementId) {
    var fancyboxAnchorElementId = "fancyboxTriggerFor_" + elementId;
    if ($("#"+fancyboxAnchorElementId).length == 0) {
        $("body").append("<a id='" + fancyboxAnchorElementId + "' href='#" + elementId+ "' style='display:none;'></a>");
        $("#"+fancyboxAnchorElementId).fancybox();
    }

    $("#" + fancyboxAnchorElementId).click();
}

Additional explanation: If you show fancybox with "content" option, it will duplicate DOM, which is inside elements. Sometimes this is not OK. In my case I needed to have the same elements, because they were used in form.

combining two data frames of different lengths

It's not clear to me at all what the OP is actually after, given the follow-up comments. It's possible they are actually looking for a way to write the data to file.

But let's assume that we're really after a way to cbind multiple data frames of differing lengths.

cbind will eventually call data.frame, whose help files says:

Objects passed to data.frame should have the same number of rows, but atomic vectors, factors and character vectors protected by I will be recycled a whole number of times if necessary (including as from R 2.9.0, elements of list arguments).

so in the OP's actual example, there shouldn't be an error, as R ought to recycle the shorter vectors to be of length 50. Indeed, when I run the following:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
cbind(dat1,dat2)

I get no errors and the shorter data frame is recycled as expected. However, when I run this:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(9), e = runif(9))
cbind(dat1,dat2)

I get the following error:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 50, 9

But the wonderful thing about R is that you can make it do almost anything you want, even if you shouldn't. For example, here's a simple function that will cbind data frames of uneven length and automatically pad the shorter ones with NAs:

cbindPad <- function(...){
args <- list(...)
n <- sapply(args,nrow)
mx <- max(n)
pad <- function(x, mx){
    if (nrow(x) < mx){
        nms <- colnames(x)
        padTemp <- matrix(NA, mx - nrow(x), ncol(x))
        colnames(padTemp) <- nms
        if (ncol(x)==0) {
          return(padTemp)
        } else {
        return(rbind(x,padTemp))
          }
    }
    else{
        return(x)
    }
}
rs <- lapply(args,pad,mx)
return(do.call(cbind,rs))
}

which can be used like this:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
dat3 <- data.frame(d = runif(9), e = runif(9))
cbindPad(dat1,dat2,dat3)

I make no guarantees that this function works in all cases; it is meant as an example only.

EDIT

If the primary goal is to create a csv or text file, all you need to do it alter the function to pad using "" rather than NA and then do something like this:

dat <- cbindPad(dat1,dat2,dat3)
rs <- as.data.frame(apply(dat,1,function(x){paste(as.character(x),collapse=",")}))

and then use write.table on rs.

Generate Java classes from .XSD files...?

the easiest way is using command line. Just type in directory of your .xsd file:

xjc myFile.xsd.

So, the java will generate all Pojos.

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

I am answering the question - as I didn't find any of them complete. As nowadays Unknown character set: 'utf8mb4' is quite prevalent as lot of deployments have MySQL less then 5.5.3 (version in which utf8mb4 was added).


The error clearly states that you don't have utf8mb4 supported on your stage db server.

Cause: probably locally you have MySQL version 5.5.3 or greater, and on stage/hosted VPS you have MySQL server version less then 5.5.3

The utf8mb4 character sets was added in MySQL 5.5.3.

utf8mb4 was added because of a bug in MySQL's utf8 character set. MySQL's handling of the utf8 character set only allows a maximum of 3 bytes for a single codepoint, which isn't enough to represent the entirety of Unicode (Maximum codepoint = 0x10FFFF). Because they didn't want to potentially break any stuff that relied on this buggy behaviour, utf8mb4 was added. Documentation here.

From SO answer:


Verification: To verify you can check the current character set and collation for the DB you're importing the dump from - How do I see what character set a MySQL database / table / column is?


Solution 1: Simply upgrade your MySQL server to 5.5.3 (at-least) - for next time be conscious about the version you use locally, for stage, and for prod, all must have to be same. A suggestion - in present the default character set should be utf8mb4.

Solution 2 (not recommended): Convert the current character set to utf8, and then export the data - it'll load ok.

How to get the mouse position without events (without moving the mouse)?

Edit 2020: This does not work any more. It seems so, that the browser vendors patched this out. Because the most browsers rely on chromium, it might be in its core.

Old answer: You can also hook mouseenter (this event is fired after page reload, when the mousecursor is inside the page). Extending Corrupted's code should do the trick:

_x000D_
_x000D_
var x = null;_x000D_
var y = null;_x000D_
    _x000D_
document.addEventListener('mousemove', onMouseUpdate, false);_x000D_
document.addEventListener('mouseenter', onMouseUpdate, false);_x000D_
    _x000D_
function onMouseUpdate(e) {_x000D_
  x = e.pageX;_x000D_
  y = e.pageY;_x000D_
  console.log(x, y);_x000D_
}_x000D_
_x000D_
function getMouseX() {_x000D_
  return x;_x000D_
}_x000D_
_x000D_
function getMouseY() {_x000D_
  return y;_x000D_
}
_x000D_
_x000D_
_x000D_

You can also set x and y to null on mouseleave-event. So you can check if the user is on your page with it's cursor.

Index (zero based) must be greater than or equal to zero

This can also happen when trying to throw an ArgumentException where you inadvertently call the ArgumentException constructor overload

public static void Dostuff(Foo bar)
{

   // this works
   throw new ArgumentException(String.Format("Could not find {0}", bar.SomeStringProperty));

   //this gives the error
   throw new ArgumentException(String.Format("Could not find {0}"), bar.SomeStringProperty);

}

How do I create a table based on another table

select * into newtable from oldtable

Batch file to run a command in cmd within a directory

CMD.EXE will not execute internal commands contained inside the string. Only actual files can be launched with that string.

You will need to actually call a batch file to do what you want.

BAT1.bat

start cmd.exe /k bat2.bat

BAT2.bat

cd C:\activiti-5.9\setup
ant demo.start

You may want to create a folder called BAT, and add it's location to your path. So if you create C:\BAT, add C:\BAT\; to the path. The path is located at:

    click -> Start -> right-click Computer -> Properties ->
    click -> Avanced System Settings -> Environment Variables
   select -> Path (From either list. User Variables are specific to 
                   your profile, System Variables are, duh, system-wide.)
    Click -> Edit
Press the -> the [END] or [HOME] key.
     Type -> C:\BAT\;
    Click -> OK -> OK

Now place all your batch files in C:\BAT and they will be found, regardless of the current directory.

Sorting an Array of int using BubbleSort

Bubble sort nested loops should be written like this:

int n = intArray.length;
int temp = 0;

for(int i=0; i < n; i++){
   for(int j=1; j < (n-i); j++){                        
       if(intArray[j-1] > intArray[j]){
            //swap the elements!
            temp = intArray[j-1];
            intArray[j-1] = intArray[j];
            intArray[j] = temp;
       }                    
   }
}

How to get data out of a Node.js http get request

Simple Working Example of Http request using node.

const http = require('https')

httprequest().then((data) => {
        const response = {
            statusCode: 200,
            body: JSON.stringify(data),
        };
    return response;
});
function httprequest() {
     return new Promise((resolve, reject) => {
        const options = {
            host: 'jsonplaceholder.typicode.com',
            path: '/todos',
            port: 443,
            method: 'GET'
        };
        const req = http.request(options, (res) => {
          if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            var body = [];
            res.on('data', function(chunk) {
                body.push(chunk);
            });
            res.on('end', function() {
                try {
                    body = JSON.parse(Buffer.concat(body).toString());
                } catch(e) {
                    reject(e);
                }
                resolve(body);
            });
        });
        req.on('error', (e) => {
          reject(e.message);
        });
        // send the request
       req.end();
    });
}

Why am I getting a NoClassDefFoundError in Java?

I have had an interesting issue wiht NoClassDefFoundError in JavaEE working with Liberty server. I was using IMS resource adapters and my server.xml had already resource adapter for imsudbJXA.rar. When I added new adapter for imsudbXA.rar, I would start getting this error for instance objects for DLIException, IMSConnectionSpec or SQLInteractionSpec. I could not figure why but I resolved it by creating new server.xml for my work using only imsudbXA.rar. I am sure using multiple resource adapters in server.xml is fine, I just had no time to look into that.

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

Had same problem. Caused by self issued certificate authority. Solved it by adding .pem file to /usr/local/share/ca-certificates/ and calling

sudo update-ca-certificates

PS: pem file in folder ./share/ca-certificates MUST have extension .crt

rawQuery(query, selectionArgs)

Maybe this can help you

Cursor c = db.rawQuery("query",null);
int id[] = new int[c.getCount()];
int i = 0;
if (c.getCount() > 0) 
{               
    c.moveToFirst();
    do {
        id[i] = c.getInt(c.getColumnIndex("field_name"));
        i++;
    } while (c.moveToNext());
    c.close();
}

How can I resolve the error: "The command [...] exited with code 1"?

I had the same issue. Tried all the above answers. It was actually complained about a .dll file. I clean the project in Visual Studio but the .dll file still remains, so I deleted in manually from the bin folder and it worked.

ARM compilation error, VFP registers used by executable, not object file

In my particular case -g -march=armv7-a -mfloat-abi=hard -mfpu=neon -marm -mthumb-interwork worked.

Find character position and update file name

The string is a .NET string so you can use .NET methods. In your case:

$index = "The string".IndexOf(" ")

will return 3, which is the first occurrence of space in the string. For more information see: http://msdn.microsoft.com/en-us/library/system.string.aspx

For your need try something like:

$s.SubString($s.IndexOf("_") + 1, $s.LastIndexOf(".") - $s.IndexOf("_") - 1)

Or you could use regexps:

if ($s -Match '(_)(.*)(\.)[^.]*$') {  $matches[2] }

(has to be adjusted depending on exactly what you need).

Can't find the 'libpq-fe.h header when trying to install pg gem

On Mac OS X run like this:

gem install pg -- --with-pg-config=***/path/to/pg_config***

***/path/to/pg_config*** is path to pg_config

how to toggle (hide/show) a table onClick of <a> tag in java script

You are always passing in true to the toggleMethod, so it will always "show" the table. I would create a global variable that you can flip inside the toggle method instead.

Alternatively you can check the visibility state of the table instead of an explicit variable

Remove space above and below <p> tag HTML

There are two ways:

The best way is to remove the <p> altogether. It is acting according to specification when it adds space.

Alternately, use CSS to style the <p>. Something like:

ul li p {
    padding: 0;
    margin: 0;
    display: inline;
}

How to validate phone numbers using regex

Here's one that works well in JavaScript. It's in a string because that's what the Dojo widget was expecting.

It matches a 10 digit North America NANP number with optional extension. Spaces, dashes and periods are accepted delimiters.

"^(\\(?\\d\\d\\d\\)?)( |-|\\.)?\\d\\d\\d( |-|\\.)?\\d{4,4}(( |-|\\.)?[ext\\.]+ ?\\d+)?$"

How can I run multiple npm scripts in parallel?

Quick Solution

In this case, I'd say the best bet If this script is for a private module intended to run only on *nix-based machines, you can use the control operator for forking processes, which looks like this: &

An example of doing this in a partial package.json file:

{
  "name": "npm-scripts-forking-example",
  "scripts": {
    "bundle": "watchify -vd -p browserify-hmr index.js -o bundle.js",
    "serve":  "http-server -c 1 -a localhost",
    "serve-bundle": "npm run bundle & npm run serve &"
  }

You'd then execute them both in parallel via npm run serve-bundle. You can enhance the scripts to output the pids of the forked process to a file like so:

"serve-bundle": "npm run bundle & echo \"$!\" > build/bundle.pid && npm run serve & echo \"$!\" > build/serve.pid && npm run open-browser",

Google something like bash control operator for forking to learn more on how it works. I've also provided some further context regarding leveraging Unix techniques in Node projects below:

Further Context RE: Unix Tools & Node.js

If you're not on Windows, Unix tools/techniques often work well to achieve something with Node scripts because:

  1. Much of Node.js lovingly imitates Unix principles
  2. You're on *nix (incl. OS X) and NPM is using a shell anyway

Modules for system tasks in Nodeland are also often abstractions or approximations of Unix tools, from fs to streams.

source of historical stock data

Unfortunately historical ticker data that is free is hard to come by. Now that opentick is dead, I dont know of any other provider.

In a previous lifetime I worked for a hedgefund that had an automated trading system, and we used historical data profusely.

We used TickData for our source. Their prices were reasonable, and the data had sub second resolution.

Configuring Hibernate logging using Log4j XML config file?

From http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html#configuration-logging

Here's the list of logger categories:

Category                    Function

org.hibernate.SQL           Log all SQL DML statements as they are executed
org.hibernate.type          Log all JDBC parameters
org.hibernate.tool.hbm2ddl  Log all SQL DDL statements as they are executed
org.hibernate.pretty        Log the state of all entities (max 20 entities) associated with the session at flush time
org.hibernate.cache         Log all second-level cache activity
org.hibernate.transaction   Log transaction related activity
org.hibernate.jdbc          Log all JDBC resource acquisition
org.hibernate.hql.ast.AST   Log HQL and SQL ASTs during query parsing
org.hibernate.secure        Log all JAAS authorization requests
org.hibernate               Log everything (a lot of information, but very useful for troubleshooting) 

Formatted for pasting into a log4j XML configuration file:

<!-- Log all SQL DML statements as they are executed -->
<Logger name="org.hibernate.SQL" level="debug" />
<!-- Log all JDBC parameters -->
<Logger name="org.hibernate.type" level="debug" />
<!-- Log all SQL DDL statements as they are executed -->
<Logger name="org.hibernate.tool.hbm2ddl" level="debug" />
<!-- Log the state of all entities (max 20 entities) associated with the session at flush time -->
<Logger name="org.hibernate.pretty" level="debug" />
<!-- Log all second-level cache activity -->
<Logger name="org.hibernate.cache" level="debug" />
<!-- Log transaction related activity -->
<Logger name="org.hibernate.transaction" level="debug" />
<!-- Log all JDBC resource acquisition -->
<Logger name="org.hibernate.jdbc" level="debug" />
<!-- Log HQL and SQL ASTs during query parsing -->
<Logger name="org.hibernate.hql.ast.AST" level="debug" />
<!-- Log all JAAS authorization requests -->
<Logger name="org.hibernate.secure" level="debug" />
<!-- Log everything (a lot of information, but very useful for troubleshooting) -->
<Logger name="org.hibernate" level="debug" />

NB: Most of the loggers use the DEBUG level, however org.hibernate.type uses TRACE. In previous versions of Hibernate org.hibernate.type also used DEBUG, but as of Hibernate 3 you must set the level to TRACE (or ALL) in order to see the JDBC parameter binding logging.

And a category is specified as such:

<logger name="org.hibernate">
    <level value="ALL" />
    <appender-ref ref="FILE"/>
</logger>

It must be placed before the root element.

How do you set the Content-Type header for an HttpClient request?

Some extra information about .NET Core (after reading erdomke's post about setting a private field to supply the content-type on a request that doesn't have content)...

After debugging my code, I can't see the private field to set via reflection - so I thought I'd try to recreate the problem.

I have tried the following code using .Net 4.6:

HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, @"myUrl");
httpRequest.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

HttpClient client = new HttpClient();
Task<HttpResponseMessage> response =  client.SendAsync(httpRequest);  //I know I should have used async/await here!
var result = response.Result;

And, as expected, I get an aggregate exception with the content "Cannot send a content-body with this verb-type."

However, if i do the same thing with .NET Core (1.1) - I don't get an exception. My request was quite happily answered by my server application, and the content-type was picked up.

I was pleasantly surprised about that, and I hope it helps someone!

What is the documents directory (NSDocumentDirectory)?

It can be cleaner to add an extension to FileManager for this kind of awkward call, for tidiness if nothing else. Something like:

extension FileManager {
    static var documentDir : URL {
        return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    }
}

correct quoting for cmd.exe for multiple arguments

Spaces are horrible in filenames or directory names.

The correct syntax for this is to include every directory name that includes spaces, in double quotes

cmd /c C:\"Program Files"\"Microsoft Visual Studio 9.0"\Common7\IDE\devenv.com mysolution.sln /build "release|win32"

What is the difference between Integrated Security = True and Integrated Security = SSPI?

In my point of view,

If you dont use Integrated security=SSPI,then you need to hardcode the username and password in the connection string which means "relatively insecure" why because, all the employees have the access even ex-employee could use the information maliciously.

How do I get the classes of all columns in a data frame?

One option is to use lapply and class. For example:

> foo <- data.frame(c("a", "b"), c(1, 2))
> names(foo) <- c("SomeFactor", "SomeNumeric")
> lapply(foo, class)
$SomeFactor
[1] "factor"

$SomeNumeric
[1] "numeric"

Another option is str:

> str(foo)
'data.frame':   2 obs. of  2 variables:
 $ SomeFactor : Factor w/ 2 levels "a","b": 1 2
 $ SomeNumeric: num  1 2

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

Here is my attempt:

Function RegParse(ByVal pattern As String, ByVal html As String)
    Dim regex   As RegExp
    Set regex = New RegExp

    With regex
        .IgnoreCase = True  'ignoring cases while regex engine performs the search.
        .pattern = pattern  'declaring regex pattern.
        .Global = False     'restricting regex to find only first match.

        If .Test(html) Then         'Testing if the pattern matches or not
            mStr = .Execute(html)(0)        '.Execute(html)(0) will provide the String which matches with Regex
            RegParse = .Replace(mStr, "$1") '.Replace function will replace the String with whatever is in the first set of braces - $1.
        Else
            RegParse = "#N/A"
        End If

    End With
End Function

Python: count repeated elements in the list

This works for Python 2.6.6

a = ["a", "b", "a"]
result = dict((i, a.count(i)) for i in a)
print result

prints

{'a': 2, 'b': 1}

How to get a variable name as a string in PHP?

why we have to use globals to get variable name... we can use simply like below.

    $variableName = "ajaxmint";

    echo getVarName('$variableName');

    function getVarName($name) {
        return str_replace('$','',$name);
    }

How to get a file or blob from an object URL?

If you show the file in a canvas anyway you can also convert the canvas content to a blob object.

canvas.toBlob(function(my_file){
  //.toBlob is only implemented in > FF18 but there is a polyfill 
  //for other browsers https://github.com/blueimp/JavaScript-Canvas-to-Blob
  var myBlob = (my_file);
})

Java: Static vs inner class

An inner class cannot be static, so I am going to recast your question as "What is the difference between static and non-static nested classes?".

as u said here inner class cannot be static... i found the below code which is being given static....reason? or which is correct....

Yes, there is nothing in the semantics of a static nested type that would stop you from doing that. This snippet runs fine.

    public class MultipleInner {
        static class Inner {
        }   
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Inner();
        }
    }
}

this is a code posted in this website...

for the question---> Can a Static Nested Class be Instantiated Multiple Times?

answer was--->

Now, of course the nested type can do its own instance control (e.g. private constructors, singleton pattern, etc) but that has nothing to do with the fact that it's a nested type. Also, if the nested type is a static enum, of course you can't instantiate it at all.

But in general, yes, a static nested type can be instantiated multiple times.

Note that technically, a static nested type is not an "inner" type.

How do I force make/GCC to show me the commands?

To invoke a dry run:

make -n

This will show what make is attempting to do.

How to loop through all elements of a form jQuery

$('#new_user_form :input') should be your way forward. Note the omission of the > selector. A valid HTML form wouldn't allow for a input tag being a direct child of a form tag.

What are queues in jQuery?

To understand queue method, you have to understand how jQuery does animation. If you write multiple animate method calls one after the other, jQuery creates an 'internal' queue and adds these method calls to it. Then it runs those animate calls one by one.

Consider following code.

function nonStopAnimation()
{
    //These multiple animate calls are queued to run one after
    //the other by jQuery.
    //This is the reason that nonStopAnimation method will return immeidately
    //after queuing these calls. 
    $('#box').animate({ left: '+=500'}, 4000);
    $('#box').animate({ top: '+=500'}, 4000);
    $('#box').animate({ left: '-=500'}, 4000);

    //By calling the same function at the end of last animation, we can
    //create non stop animation. 
    $('#box').animate({ top: '-=500'}, 4000 , nonStopAnimation);
}

The 'queue'/'dequeue' method gives you control over this 'animation queue'.

By default the animation queue is named 'fx'. I have created a sample page here which has various examples which will illustrate how the queue method could be used.

http://jsbin.com/zoluge/1/edit?html,output

Code for above sample page:

$(document).ready(function() {
    $('#nonStopAnimation').click(nonStopAnimation);

    $('#stopAnimationQueue').click(function() {
        //By default all animation for particular 'selector'
        //are queued in queue named 'fx'.
        //By clearning that queue, you can stop the animation.
        $('#box').queue('fx', []);
    });

    $('#addAnimation').click(function() {
        $('#box').queue(function() {
            $(this).animate({ height : '-=25'}, 2000);
            //De-queue our newly queued function so that queues
            //can keep running.
            $(this).dequeue();
        });
    });

    $('#stopAnimation').click(function() {
        $('#box').stop();
    });

    setInterval(function() {
        $('#currentQueueLength').html(
         'Current Animation Queue Length for #box ' + 
          $('#box').queue('fx').length
        );
    }, 2000);
});

function nonStopAnimation()
{
    //These multiple animate calls are queued to run one after
    //the other by jQuery.
    $('#box').animate({ left: '+=500'}, 4000);
    $('#box').animate({ top: '+=500'}, 4000);
    $('#box').animate({ left: '-=500'}, 4000);
    $('#box').animate({ top: '-=500'}, 4000, nonStopAnimation);
}

Now you may ask, why should I bother with this queue? Normally, you wont. But if you have a complicated animation sequence which you want to control, then queue/dequeue methods are your friend.

Also see this interesting conversation on jQuery group about creating a complicated animation sequence.

http://groups.google.com/group/jquery-en/browse_thread/thread/b398ad505a9b0512/f4f3e841eab5f5a2?lnk=gst

Demo of the animation:

http://www.exfer.net/test/jquery/tabslide/

Let me know if you still have questions.

How to assign the output of a Bash command to a variable?

In shell you assign to a variable without the dollar-sign:

TEST=`pwd`
echo $TEST

that's better (and can be nested) but is not as portable as the backtics:

TEST=$(pwd)
echo $TEST

Always remember: the dollar-sign is only used when reading a variable.

How can I style a PHP echo text?

echo '<span style="Your CSS Styles">' . $ip['cityName'] . '</span>';

Commenting multiple lines in DOS batch file

Just want to mention that pdub's GOTO solution is not fully correct in case :comment label appear in multiple times. I modify the code from this question as the example.

@ECHO OFF
SET FLAG=1
IF [%FLAG%]==[1] (
    ECHO IN THE FIRST IF...
    GOTO comment
    ECHO "COMMENT PART 1"
:comment
    ECHO HERE AT TD_NEXT IN THE FIRST BLOCK
)

IF [%FLAG%]==[1] (
    ECHO IN THE SECOND IF...
    GOTO comment
    ECHO "COMMENT PART"
:comment
    ECHO HERE AT TD_NEXT IN THE SECOND BLOCK
)

The output will be

IN THE FIRST IF...
HERE AT TD_NEXT IN THE SECOND BLOCK

The command ECHO HERE AT TD_NEXT IN THE FIRST BLOCK is skipped.

How do you do dynamic / dependent drop downs in Google Sheets?

Here you have another solution based on the one provided by @tarheel

function onEdit() {
    var sheetWithNestedSelectsName = "Sitemap";
    var columnWithNestedSelectsRoot = 1;
    var sheetWithOptionPossibleValuesSuffix = "TabSections";

    var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var activeSheet = SpreadsheetApp.getActiveSheet();

    // If we're not in the sheet with nested selects, exit!
    if ( activeSheet.getName() != sheetWithNestedSelectsName ) {
        return;
    }

    var activeCell = SpreadsheetApp.getActiveRange();

    // If we're not in the root column or a content row, exit!
    if ( activeCell.getColumn() != columnWithNestedSelectsRoot || activeCell.getRow() < 2 ) {
        return;
    }

    var sheetWithActiveOptionPossibleValues = activeSpreadsheet.getSheetByName( activeCell.getValue() + sheetWithOptionPossibleValuesSuffix );

    // Get all possible values
    var activeOptionPossibleValues = sheetWithActiveOptionPossibleValues.getSheetValues( 1, 1, -1, 1 );

    var possibleValuesValidation = SpreadsheetApp.newDataValidation();
    possibleValuesValidation.setAllowInvalid( false );
    possibleValuesValidation.requireValueInList( activeOptionPossibleValues, true );

    activeSheet.getRange( activeCell.getRow(), activeCell.getColumn() + 1 ).setDataValidation( possibleValuesValidation.build() );
}

It has some benefits over the other approach:

  • You don't need to edit the script every time you add a "root option". You only have to create a new sheet with the nested options of this root option.
  • I've refactored the script providing more semantic names for the variables and so on. Furthermore, I've extracted some parameters to variables in order to make it easier to adapt to your specific case. You only have to set the first 3 values.
  • There's no limit of nested option values (I've used the getSheetValues method with the -1 value).

So, how to use it:

  1. Create the sheet where you'll have the nested selectors
  2. Go to the "Tools" > "Script Editor…" and select the "Blank project" option
  3. Paste the code attached to this answer
  4. Modify the first 3 variables of the script setting up your values and save it
  5. Create one sheet within this same document for each possible value of the "root selector". They must be named as the value + the specified suffix.

Enjoy!

The remote end hung up unexpectedly while git cloning

use ssh instead of http, it's not a good answer for this question but at least it works for me

How do I set the classpath in NetBeans?

Maven

The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.

Dependency

Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.

Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.

Repository

Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).

Easy to Use

Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.

enter image description here

How Stuff and 'For Xml Path' work in SQL Server?

STUFF((SELECT distinct ',' + CAST(T.ID) FROM Table T where T.ID= 1 FOR XML PATH('')),1,1,'') AS Name

Path.Combine for URLs?

Path.Combine does not work for me because there can be characters like "|" in QueryString arguments and therefore the URL, which will result in an ArgumentException.

I first tried the new Uri(Uri baseUri, string relativeUri) approach, which failed for me because of URIs like http://www.mediawiki.org/wiki/Special:SpecialPages:

new Uri(new Uri("http://www.mediawiki.org/wiki/"), "Special:SpecialPages")

will result in Special:SpecialPages, because of the colon after Special that denotes a scheme.

So I finally had to take mdsharpe/Brian MacKays route and developed it a bit further to work with multiple URI parts:

public static string CombineUri(params string[] uriParts)
{
    string uri = string.Empty;
    if (uriParts != null && uriParts.Length > 0)
    {
        char[] trims = new char[] { '\\', '/' };
        uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);
        for (int i = 1; i < uriParts.Length; i++)
        {
            uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
        }
    }
    return uri;
}

Usage: CombineUri("http://www.mediawiki.org/", "wiki", "Special:SpecialPages")

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

How to tell a Mockito mock object to return something different the next time it is called?

First of all don't make the mock static. Make it a private field. Just put your setUp class in the @Before not @BeforeClass. It might be run a bunch, but it's cheap.

Secondly, the way you have it right now is the correct way to get a mock to return something different depending on the test.

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

If you are running server already, don't forget to use http:// in the API call. This might cause a serious trouble.

Numpy first occurrence of value greater than existing value

I'd like to propose

np.min(np.append(np.where(aa>5)[0],np.inf))

This will return the smallest index where the condition is met, while returning infinity if the condition is never met (and where returns an empty array).

How to delete row based on cell value

The easiest way to do this would be to use a filter.

You can either filter for any cells in column A that don't have a "-" and copy / paste, or (my more preferred method) filter for all cells that do have a "-" and then select all and delete - Once you remove the filter, you're left with what you need.

Hope this helps.

Circle-Rectangle collision detection (intersection)

Improving a little bit the answer of e.James:

double dx = abs(circle.x - rect.x) - rect.w / 2,
       dy = abs(circle.y - rect.y) - rect.h / 2;

if (dx > circle.r || dy > circle.r) { return false; }
if (dx <= 0 || dy <= 0) { return true; }

return (dx * dx + dy * dy <= circle.r * circle.r);

This subtracts rect.w / 2 and rect.h / 2 once instead of up to three times.

Why does git revert complain about a missing -m option?

I had this problem, the solution was to look at the commit graph (using gitk) and see that I had the following:

*   commit I want to cherry-pick (x)
|\  
| * branch I want to cherry-pick to (y)
* | 
|/  
* common parent (x)

I understand now that I want to do

git cherry-pick -m 2 mycommitsha

This is because -m 1 would merge based on the common parent where as -m 2 merges based on branch y, that is the one I want to cherry-pick to.

Send values from one form to another form

In this code, you pass a text to Form2. Form2 shows that text in textBox1. User types new text into textBox1 and presses the submit button. Form1 grabs that text and shows it in a textbox on Form1.

public class Form2 : Form
{
    private string oldText;

    public Form2(string newText):this()
    {
        oldText = newText;
        btnSubmit.DialogResult = DialogResult.OK;
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        textBox1.Text = oldText;
    }

    public string getText()
    {
        return textBox1.Text;
    }

    private void textBox1_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }
    }
}

And this is Form1 code:

public class Form1:Form
{
    using (Form2 dialogForm = new Form2("old text to show in Form2"))
    {
        DialogResult dr = dialogForm.ShowDialog(this);
        if (dr == DialogResult.OK)
        {
            tbSubmittedText = dialogForm.getText();
        }
        dialogForm.Close();
    }
}

proper hibernate annotation for byte[]

Thanks Justin, Pascal for guiding me to the right direction. I was also facing the same issue with Hibernate 3.5.3. Your research and pointers to the right classes had helped me identify the issue and do a fix.

For the benefit for those who are still stuck with Hibernate 3.5 and using oid + byte[] + @LoB combination, following is what I have done to fix the issue.

  1. I created a custom BlobType extending MaterializedBlobType and overriding the set and the get methods with the oid style access.

    public class CustomBlobType extends MaterializedBlobType {
    
    private static final String POSTGRESQL_DIALECT = PostgreSQLDialect.class.getName();
    
    /**
     * Currently set dialect.
     */
    private String dialect = hibernateConfiguration.getProperty(Environment.DIALECT);
    
    /*
     * (non-Javadoc)
     * @see org.hibernate.type.AbstractBynaryType#set(java.sql.PreparedStatement, java.lang.Object, int)
     */
    @Override
    public void set(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
        byte[] internalValue = toInternalFormat(value);
    
        if (POSTGRESQL_DIALECT.equals(dialect)) {
            try {
    
    //I had access to sessionFactory through a custom sessionFactory wrapper.
    st.setBlob(index, Hibernate.createBlob(internalValue, sessionFactory.getCurrentSession()));
                } catch (SystemException e) {
                    throw new HibernateException(e);
                }
            } else {
                st.setBytes(index, internalValue);
            }
        }
    
    /*
     * (non-Javadoc)
     * @see org.hibernate.type.AbstractBynaryType#get(java.sql.ResultSet, java.lang.String)
     */
    @Override
    public Object get(ResultSet rs, String name) throws HibernateException, SQLException {
        Blob blob = rs.getBlob(name);
        if (rs.wasNull()) {
            return null;
        }
        int length = (int) blob.length();
        return toExternalFormat(blob.getBytes(1, length));
      }
    }
    
    1. Register the CustomBlobType with Hibernate. Following is what i did to achieve that.

      hibernateConfiguration= new AnnotationConfiguration();
      Mappings mappings = hibernateConfiguration.createMappings();
      mappings.addTypeDef("materialized_blob", "x.y.z.BlobType", null);
      

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

Your entity may not listed in hibernate configuration file.

How can I make a link from a <td> table cell

Yes, that's possible, albeit not literally the <td>, but what's in it. The simple trick is, to make sure that the content extends to the borders of the cell (it won't include the borders itself though).

As already explained, this isn't semantically correct. An a element is an inline element and should not be used as block-level element. However, here's an example (but JavaScript plus a td:hover CSS style will be much neater) that works in most browsers:

<td>
  <a href="http://example.com">
    <div style="height:100%;width:100%">
      hello world
    </div>
  </a>
</td>

PS: it's actually neater to change a in a block-level element using CSS as explained in another solution in this thread. it won't work well in IE6 though, but that's no news ;)

Alternative (non-advised) solution

If your world is only Internet Explorer (rare, nowadays), you can violate the HTML standard and write this, it will work as expected, but will be highly frowned upon and be considered ill-advised (you haven't heard this from me). Any other browser than IE will not render the link, but will show the table correctly.

<table>
    <tr>
        <a href="http://example.com"><td  width="200">hello world</td></a>
    </tr>
</table>

Check if element at position [x] exists in the list

if (list.Count > desiredIndex && list[desiredIndex] != null)
{
    // logic
}

How to center a label text in WPF?

The Control class has HorizontalContentAlignment and VerticalContentAlignment properties. These properties determine how a control’s content fills the space within the control.
Set HorizontalContentAlignment and VerticalContentAlignment to Center.

Rails: Using greater than/less than with a where statement

A better usage is to create a scope in the user model where(arel_table[:id].gt(id))

Get last 5 characters in a string

The accepted answer of this post will cause error in the case when the string length is lest than 5. So i have a better solution. We can use this simple code :

If(str.Length <= 5, str, str.Substring(str.Length - 5))

You can test it with variable length string.

    Dim str, result As String
    str = "11!"
    result = If(str.Length <= 5, str, str.Substring(str.Length - 5))
    MessageBox.Show(result)
    str = "I will be going to school in 2011!"
    result = If(str.Length <= 5, str, str.Substring(str.Length - 5))
    MessageBox.Show(result)

Another simple but efficient solution i found :

str.Substring(str.Length - Math.Min(5, str.Length))

Getting Current time to display in Label. VB.net

There are several problems here:

  • Your assignment is the wrong way round; you're trying to assign a value to DateTime.Now instead of Start
  • DateTime.Now is a value of type DateTime, not Integer, so the assignment wouldn't work anyway
  • There's no need to have the Start variable anyway; it's doing no good
  • total.Text is a property of type String - not DateTime or Integer

(Some of these would only show up at execution time unless you have Option Strict on, which you really should.)

You should use:

total.Text = DateTime.Now.ToString()

... possibly specifying a culture and/or format specifier if you want the result in a particular format.

Converting String to Int with Swift

An Int in Swift contains an initializer that accepts a String. It returns an optional Int? as the conversion can fail if the string contains not a number.

By using an if let statement you can validate whether the conversion succeeded.

So your code become something like this:

@IBOutlet var txtBox1 : UITextField
@IBOutlet var txtBox2 : UITextField
@IBOutlet var txtBox3 : UITextField
@IBOutlet var lblAnswer : UILabel

@IBAction func btn1(sender : AnyObject) {

    let answer1 = "The acceleration is"
    var answer2 = txtBox1
    var answer3 = txtBox2
    var answer4 = txtBox3

    if let intAnswer = Int(txtBox1.text) {
      // Correctly converted
    }
}

What in layman's terms is a Recursive Function using PHP

An example would be to print every file in any subdirectories of a given directory (if you have no symlinks inside these directories which may break the function somehow). A pseudo-code of printing all files looks like this:

function printAllFiles($dir) {
    foreach (getAllDirectories($dir) as $f) {
        printAllFiles($f); // here is the recursive call
    }
    foreach (getAllFiles($dir) as $f) {
        echo $f;
    }
}

The idea is to print all sub directories first and then the files of the current directory. This idea get applied to all sub directories, and thats the reason for calling this function recursively for all sub directories.

If you want to try this example you have to check for the special directories . and .., otherwise you get stuck in calling printAllFiles(".") all the time. Additionally you must check what to print and what your current working directory is (see opendir(), getcwd(), ...).

git add only modified changes and ignore untracked files

I happened to try this so I could see the list of files first:

git status | grep "modified:" | awk '{print "git add  " $2}' > file.sh

cat ./file.sh

execute:

chmod a+x file.sh
./file.sh 

Edit: (see comments) This could be achieved in one step:

git status | grep "modified:" | awk '{print $2}' | xargs git add && git status

How to SUM parts of a column which have same text value in different column in the same row

This can be done by using SUMPRODUCT as well. Update the ranges as you see fit

=SUMPRODUCT(($A$2:$A$7=A2)*($B$2:$B$7=B2)*$C$2:$C$7)

A2:A7 = First name range

B2:B7 = Last Name Range

C2:C7 = Numbers Range

This will find all the names with the same first and last name and sum the numbers in your numbers column

How can I stop a While loop?

The is operator in Python probably doesn't do what you expect. Instead of this:

    if numpy.array_equal(tmp,universe_array) is True:
        break

I would write it like this:

    if numpy.array_equal(tmp,universe_array):
        break

The is operator tests object identity, which is something quite different from equality.

AngularJS - How to use $routeParams in generating the templateUrl?

Router:-

...
.when('/enquiry/:page', {
    template: '<div ng-include src="templateUrl" onload="onLoad()"></div>',
    controller: 'enquiryCtrl'
})
...

Controller:-

...
// template onload event
$scope.onLoad = function() {
    console.log('onLoad()');
    f_tcalInit();  // or other onload stuff
}

// initialize
$scope.templateUrl = 'ci_index.php/adminctrl/enquiry/'+$routeParams.page;
...

I believe it is a weakness in angularjs that $routeParams is NOT visible inside the router. A tiny enhancement would make a world of difference during implementation.

How do I set up HttpContent for my HttpClient PostAsync second parameter?

    public async Task<ActionResult> Index()
    {
        apiTable table = new apiTable();
        table.Name = "Asma Nadeem";
        table.Roll = "6655";

        string str = "";
        string str2 = "";

        HttpClient client = new HttpClient();

        string json = JsonConvert.SerializeObject(table);

        StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);

        str = "" + response.Content + " : " + response.StatusCode;

        if (response.IsSuccessStatusCode)
        {       
            str2 = "Data Posted";
        }

        return View();
    }

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

I had the same issue. When I checked my config file I noticed that 'fetch = +refs/heads/:refs/remotes/origin/' was on the same line as 'url = Z:/GIT/REPOS/SEL.git' as shown:

[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
[remote "origin"]
    url = Z:/GIT/REPOS/SEL.git     fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[gui]
    wmstate = normal
    geometry = 1109x563+32+32 216 255

At first I did not think that this would have mattered but after seeing the post by Magere I moved the line and that fixed the problem:

[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
[remote "origin"]
    url = Z:/GIT/REPOS/SEL.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[gui]
    wmstate = normal
    geometry = 1109x563+32+32 216 255

How to move an entire div element up x pixels?

$('div').css({
    position: 'relative',
    top: '-15px'
});

How to automatically redirect HTTP to HTTPS on Apache servers?

for me this worked

RewriteEngine on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

This error

Failure [INSTALL_FAILED_OLDER_SDK]

Means that you're trying to install an app that has a higher minSdkVersion specified in its manifest than the device's API level. Change that number to 8 and it should work. I'm not sure about the other error, but it may be related to this one.

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

How to load a controller from another controller in codeigniter?

you cannot call a controller method from another controller directly

my solution is to use inheritances and extend your controller from the library controller

class Controller1 extends CI_Controller {

    public function index() {
        // some codes here
    }

    public function methodA(){
        // code here
    }
}

in your controller we call it Mycontoller it will extends Controller1

include_once (dirname(__FILE__) . "/controller1.php");

class Mycontroller extends Controller1 {

    public function __construct() {
        parent::__construct();
    }

    public function methodB(){
        // codes....
    }
}

and you can call methodA from mycontroller

http://example.com/mycontroller/methodA

http://example.com/mycontroller/methodB

this solution worked for me

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

First thing Correctly specify all settings in the .ENV file for Mail.

I LOST 6 HOURS FOR THIS

Example

MAIL_DRIVER=smtp
MAIL_MAILER=smtp
MAIL_HOST=smtp.yandex.ru
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=password //Create password for Apps in settings. NOT PASTE YOUR REAL MAIL PASSWORD
MAIL_ENCRYPTION=SSL
[email protected]
MAIL_FROM_NAME="${APP_NAME}"

Vertical alignment of text and icon in button

Just wrap the button label in an extra span and add class="align-middle" to both (the icon and the label). This will center your icon with text vertical.

<button id="edit-listing-form-house_Continue" 
    class="btn btn-large btn-primary"
    style=""
    value=""
    name="Continue"
    type="submit">
<span class="align-middle">Continue</span>
<i class="icon-ok align-middle" style="font-size:40px;"></i>

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

Although this may not be the cause of your issue, you'll get the same error if there are two MySQL services running on the same port. You can check on windows by looking at the list of services in the services tab of Task Manager.

How to get GET (query string) variables in Express.js on Node.js?

Since you've mentioned Express.js in your tags, here is an Express-specific answer: use req.query. E.g.

var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('id: ' + req.query.id);
});

app.listen(3000);

How to check if a string in Python is in ASCII?

Your question is incorrect; the error you see is not a result of how you built python, but of a confusion between byte strings and unicode strings.

Byte strings (e.g. "foo", or 'bar', in python syntax) are sequences of octets; numbers from 0-255. Unicode strings (e.g. u"foo" or u'bar') are sequences of unicode code points; numbers from 0-1112064. But you appear to be interested in the character é, which (in your terminal) is a multi-byte sequence that represents a single character.

Instead of ord(u'é'), try this:

>>> [ord(x) for x in u'é']

That tells you which sequence of code points "é" represents. It may give you [233], or it may give you [101, 770].

Instead of chr() to reverse this, there is unichr():

>>> unichr(233)
u'\xe9'

This character may actually be represented either a single or multiple unicode "code points", which themselves represent either graphemes or characters. It's either "e with an acute accent (i.e., code point 233)", or "e" (code point 101), followed by "an acute accent on the previous character" (code point 770). So this exact same character may be presented as the Python data structure u'e\u0301' or u'\u00e9'.

Most of the time you shouldn't have to care about this, but it can become an issue if you are iterating over a unicode string, as iteration works by code point, not by decomposable character. In other words, len(u'e\u0301') == 2 and len(u'\u00e9') == 1. If this matters to you, you can convert between composed and decomposed forms by using unicodedata.normalize.

The Unicode Glossary can be a helpful guide to understanding some of these issues, by pointing how how each specific term refers to a different part of the representation of text, which is far more complicated than many programmers realize.

jQuery: enabling/disabling datepicker

Well You can remove datepicker by simply remove hasDatepicker class from input.

Code

$( "#from" ).removeClass('hasDatepicker')

What are the differences between Pandas and NumPy+SciPy in Python?

pandas provides high level data manipulation tools built on top of NumPy. NumPy by itself is a fairly low-level tool, similar to MATLAB. pandas on the other hand provides rich time series functionality, data alignment, NA-friendly statistics, groupby, merge and join methods, and lots of other conveniences. It has become very popular in recent years in financial applications. I will have a chapter dedicated to financial data analysis using pandas in my upcoming book.

How to solve Object reference not set to an instance of an object.?

I think you just need;

List<string> list = new List<string>();
list.Add("hai");

There is a difference between

List<string> list; 

and

List<string> list = new List<string>();

When you didn't use new keyword in this case, your list didn't initialized. And when you try to add it hai, obviously you get an error.

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

In current AVD manager you can't. You just have the opportunity to use ARM images which will not need hardware virtualization.

To run ARM images:

  1. Open AVD manager.
  2. Create a new 'Virtual Device' OR right click an existing image and select 'Duplicate'
  3. Choose arm* instead of x86/x64.
  4. Continue with the wizard.
  5. Run!

Although this is the available solution but still a slow one !!

How to write multiple line string using Bash with variables?

The syntax (<<<) and the command used (echo) is wrong.

Correct would be:

#!/bin/bash

kernel="2.6.39"
distro="xyz"
cat >/etc/myconfig.conf <<EOL
line 1, ${kernel}
line 2, 
line 3, ${distro}
line 4 line
... 
EOL

cat /etc/myconfig.conf

This construction is referred to as a Here Document and can be found in the Bash man pages under man --pager='less -p "\s*Here Documents"' bash.

How to Convert JSON object to Custom C# object?

Performance-wise, I found the ServiceStack's serializer a bit faster than then others. It's JsonSerializer class in ServiceStack.Text namespace.

https://github.com/ServiceStack/ServiceStack.Text

ServiceStack is available through NuGet package: https://www.nuget.org/packages/ServiceStack/

How do I pass variables and data from PHP to JavaScript?

I usually use data-* attributes in HTML.

<div class="service-container" data-service="<?php echo $myService->getValue(); ?>">

</div>

<script>
    $(document).ready(function() {
        $('.service-container').each(function() {
            var container = $(this);
            var service = container.data('service');

            // Variable "service" now contains the value of $myService->getValue();
        });
    });
</script>

This example uses jQuery, but it can be adapted for another library or vanilla JavaScript.

You can read more about the dataset property here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset

Remove values from select list based on condition

For clear all options en Important en FOR : remove(0) - Important: 0

var select = document.getElementById("element_select");
var length = select.length;
for (i = 0; i < length; i++) {
     select.remove(0);
 //  or
 //  select.options[0] = null;
} 

Passing Parameters JavaFX FXML

Why answer a 6 year old question ?
One the most fundamental concepts working with any programming language is how to navigate from one (window, form or page) to another. Also while doing this navigation the developer often wants to pass data from one (window, form or page) and display or use the data passed
While most of the answers here provide good to excellent examples how to accomplish this we thought we would kick it up a notch or two or three
We said three because we will navigate between three (window, form or page) and use the concept of static variables to pass data around the (window, form or page)
We will also include some decision making code while we navigate

public class Start extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        // This is MAIN Class which runs first
        Parent root = FXMLLoader.load(getClass().getResource("start.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setResizable(false);// This sets the value for all stages
        stage.setTitle("Start Page"); 
        stage.show();
        stage.sizeToScene();
    }

    public static void main(String[] args) {
        launch(args);
    } 
}

Start Controller

public class startController implements Initializable {

@FXML Pane startPane,pageonePane;
@FXML Button btnPageOne;
@FXML TextField txtStartValue;
public Stage stage;
public static int intSETonStartController;
String strSETonStartController;

@FXML
private void toPageOne() throws IOException{

    strSETonStartController = txtStartValue.getText().trim();


        // yourString != null && yourString.trim().length() > 0
        // int L = testText.length();
        // if(L == 0){
        // System.out.println("LENGTH IS "+L);
        // return;
        // }
        /* if (testText.matches("[1-2]") && !testText.matches("^\\s*$")) 
           Second Match is regex for White Space NOT TESTED !
        */

        String testText = txtStartValue.getText().trim();
        // NOTICE IF YOU REMOVE THE * CHARACTER FROM "[1-2]*"
        // NO NEED TO CHECK LENGTH it also permited 12 or 11 as valid entry 
        // =================================================================
        if (testText.matches("[1-2]")) {
            intSETonStartController = Integer.parseInt(strSETonStartController);
        }else{
            txtStartValue.setText("Enter 1 OR 2");
            return;
        }

        System.out.println("You Entered = "+intSETonStartController);
        stage = (Stage)startPane.getScene().getWindow();// pane you are ON
        pageonePane = FXMLLoader.load(getClass().getResource("pageone.fxml"));// pane you are GOING TO
        Scene scene = new Scene(pageonePane);// pane you are GOING TO
        stage.setScene(scene);
        stage.setTitle("Page One"); 
        stage.show();
        stage.sizeToScene();
        stage.centerOnScreen();  
}

private void doGET(){
    // Why this testing ?
    // strSENTbackFROMPageoneController is null because it is set on Pageone
    // =====================================================================
    txtStartValue.setText(strSENTbackFROMPageoneController);
    if(intSETonStartController == 1){
      txtStartValue.setText(str);  
    }
    System.out.println("== doGET WAS RUN ==");
    if(txtStartValue.getText() == null){
       txtStartValue.setText("");   
    }
}

@Override
public void initialize(URL url, ResourceBundle rb) {
    // This Method runs every time startController is LOADED
     doGET();
}    
}

Page One Controller

public class PageoneController implements Initializable {

@FXML Pane startPane,pageonePane,pagetwoPane;
@FXML Button btnOne,btnTwo;
@FXML TextField txtPageOneValue;
public static String strSENTbackFROMPageoneController;
public Stage stage;

    @FXML
private void onBTNONE() throws IOException{

        stage = (Stage)pageonePane.getScene().getWindow();// pane you are ON
        pagetwoPane = FXMLLoader.load(getClass().getResource("pagetwo.fxml"));// pane you are GOING TO
        Scene scene = new Scene(pagetwoPane);// pane you are GOING TO
        stage.setScene(scene);
        stage.setTitle("Page Two"); 
        stage.show();
        stage.sizeToScene();
        stage.centerOnScreen();
}

@FXML
private void onBTNTWO() throws IOException{
    if(intSETonStartController == 2){
        Alert alert = new Alert(AlertType.CONFIRMATION);
        alert.setTitle("Alert");
        alert.setHeaderText("YES to change Text Sent Back");
        alert.setResizable(false);
        alert.setContentText("Select YES to send 'Alert YES Pressed' Text Back\n"
                + "\nSelect CANCEL send no Text Back\r");// NOTE this is a Carriage return\r
        ButtonType buttonTypeYes = new ButtonType("YES");
        ButtonType buttonTypeCancel = new ButtonType("CANCEL", ButtonData.CANCEL_CLOSE);

        alert.getButtonTypes().setAll(buttonTypeYes, buttonTypeCancel);

        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == buttonTypeYes){
            txtPageOneValue.setText("Alert YES Pressed");
        } else {
            System.out.println("canceled");
            txtPageOneValue.setText("");
            onBack();// Optional
        }
    }
}

@FXML
private void onBack() throws IOException{

    strSENTbackFROMPageoneController = txtPageOneValue.getText();
    System.out.println("Text Returned = "+strSENTbackFROMPageoneController);
    stage = (Stage)pageonePane.getScene().getWindow();
    startPane = FXMLLoader.load(getClass().getResource("start.fxml")); 
    Scene scene = new Scene(startPane);
    stage.setScene(scene);
    stage.setTitle("Start Page"); 
    stage.show();
    stage.sizeToScene();
    stage.centerOnScreen(); 
}

private void doTEST(){
    String fromSTART = String.valueOf(intSETonStartController);
    txtPageOneValue.setText("SENT  "+fromSTART);
    if(intSETonStartController == 1){
       btnOne.setVisible(true);
       btnTwo.setVisible(false);
       System.out.println("INTEGER Value Entered = "+intSETonStartController);  
    }else{
       btnOne.setVisible(false);
       btnTwo.setVisible(true);
       System.out.println("INTEGER Value Entered = "+intSETonStartController); 
    }  
}

@Override
public void initialize(URL url, ResourceBundle rb) {
    doTEST();
}    

}

Page Two Controller

public class PagetwoController implements Initializable {

@FXML Pane startPane,pagetwoPane;
public Stage stage;
public static String str;

@FXML
private void toStart() throws IOException{

    str = "You ON Page Two";
    stage = (Stage)pagetwoPane.getScene().getWindow();// pane you are ON
    startPane = FXMLLoader.load(getClass().getResource("start.fxml"));// pane you are GOING TO
    Scene scene = new Scene(startPane);// pane you are GOING TO
    stage.setScene(scene);
    stage.setTitle("Start Page"); 
    stage.show();
    stage.sizeToScene();
    stage.centerOnScreen();  
}

@Override
public void initialize(URL url, ResourceBundle rb) {

}    

}

Below are all the FXML files

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
_x000D_
<?import javafx.scene.control.Button?>_x000D_
<?import javafx.scene.layout.AnchorPane?>_x000D_
<?import javafx.scene.text.Font?>_x000D_
_x000D_
<AnchorPane id="AnchorPane" fx:id="pagetwoPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="atwopage.PagetwoController">_x000D_
   <children>_x000D_
      <Button layoutX="227.0" layoutY="62.0" mnemonicParsing="false" onAction="#toStart" text="To Start Page">_x000D_
         <font>_x000D_
            <Font name="System Bold" size="18.0" />_x000D_
         </font>_x000D_
      </Button>_x000D_
   </children>_x000D_
</AnchorPane>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
_x000D_
<?import javafx.scene.control.Button?>_x000D_
<?import javafx.scene.control.Label?>_x000D_
<?import javafx.scene.control.TextField?>_x000D_
<?import javafx.scene.layout.AnchorPane?>_x000D_
<?import javafx.scene.text.Font?>_x000D_
_x000D_
<AnchorPane id="AnchorPane" fx:id="startPane" prefHeight="200.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="atwopage.startController">_x000D_
   <children>_x000D_
      <Label focusTraversable="false" layoutX="115.0" layoutY="47.0" text="This is the Start Pane">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font>_x000D_
      </Label>_x000D_
      <Button fx:id="btnPageOne" focusTraversable="false" layoutX="137.0" layoutY="100.0" mnemonicParsing="false" onAction="#toPageOne" text="To Page One">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font>_x000D_
      </Button>_x000D_
      <Label focusTraversable="false" layoutX="26.0" layoutY="150.0" text="Enter 1 OR 2">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font>_x000D_
      </Label>_x000D_
      <TextField fx:id="txtStartValue" layoutX="137.0" layoutY="148.0" prefHeight="28.0" prefWidth="150.0" />_x000D_
   </children>_x000D_
</AnchorPane>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
_x000D_
<?import javafx.scene.control.Button?>_x000D_
<?import javafx.scene.control.Label?>_x000D_
<?import javafx.scene.control.TextField?>_x000D_
<?import javafx.scene.layout.AnchorPane?>_x000D_
<?import javafx.scene.text.Font?>_x000D_
_x000D_
<AnchorPane id="AnchorPane" fx:id="pageonePane" prefHeight="200.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="atwopage.PageoneController">_x000D_
   <children>_x000D_
      <Label focusTraversable="false" layoutX="111.0" layoutY="35.0" text="This is Page One Pane">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font>_x000D_
      </Label>_x000D_
      <Button focusTraversable="false" layoutX="167.0" layoutY="97.0" mnemonicParsing="false" onAction="#onBack" text="BACK">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font></Button>_x000D_
      <Button fx:id="btnOne" focusTraversable="false" layoutX="19.0" layoutY="97.0" mnemonicParsing="false" onAction="#onBTNONE" text="Button One" visible="false">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font>_x000D_
      </Button>_x000D_
      <Button fx:id="btnTwo" focusTraversable="false" layoutX="267.0" layoutY="97.0" mnemonicParsing="false" onAction="#onBTNTWO" text="Button Two">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font>_x000D_
      </Button>_x000D_
      <Label focusTraversable="false" layoutX="19.0" layoutY="152.0" text="Send Anything BACK">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font>_x000D_
      </Label>_x000D_
      <TextField fx:id="txtPageOneValue" layoutX="195.0" layoutY="150.0" prefHeight="28.0" prefWidth="150.0" />_x000D_
   </children>_x000D_
</AnchorPane>
_x000D_
_x000D_
_x000D_

Modify request parameter with servlet filter

Based on all your remarks here is my proposal that worked for me :

 private final class CustomHttpServletRequest extends HttpServletRequestWrapper {

    private final Map<String, String[]> queryParameterMap;
    private final Charset requestEncoding;

    public CustomHttpServletRequest(HttpServletRequest request) {
        super(request);
        queryParameterMap = getCommonQueryParamFromLegacy(request.getParameterMap());

        String encoding = request.getCharacterEncoding();
        requestEncoding = (encoding != null ? Charset.forName(encoding) : StandardCharsets.UTF_8);
    }

    private final Map<String, String[]> getCommonQueryParamFromLegacy(Map<String, String[]> paramMap) {
        Objects.requireNonNull(paramMap);

        Map<String, String[]> commonQueryParamMap = new LinkedHashMap<>(paramMap);

        commonQueryParamMap.put(CommonQueryParams.PATIENT_ID, new String[] { paramMap.get(LEGACY_PARAM_PATIENT_ID)[0] });
        commonQueryParamMap.put(CommonQueryParams.PATIENT_BIRTHDATE, new String[] { paramMap.get(LEGACY_PARAM_PATIENT_BIRTHDATE)[0] });
        commonQueryParamMap.put(CommonQueryParams.KEYWORDS, new String[] { paramMap.get(LEGACY_PARAM_STUDYTYPE)[0] });

        String lowerDateTime = null;
        String upperDateTime = null;

        try {
            String studyDateTime = new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("dd-MM-yyyy").parse(paramMap.get(LEGACY_PARAM_STUDY_DATE_TIME)[0]));

            lowerDateTime = studyDateTime + "T23:59:59";
            upperDateTime = studyDateTime + "T00:00:00";

        } catch (ParseException e) {
            LOGGER.error("Can't parse StudyDate from query parameters : {}", e.getLocalizedMessage());
        }

        commonQueryParamMap.put(CommonQueryParams.LOWER_DATETIME, new String[] { lowerDateTime });
        commonQueryParamMap.put(CommonQueryParams.UPPER_DATETIME, new String[] { upperDateTime });

        legacyQueryParams.forEach(commonQueryParamMap::remove);
        return Collections.unmodifiableMap(commonQueryParamMap);

    }

    @Override
    public String getParameter(String name) {
        String[] params = queryParameterMap.get(name);
        return params != null ? params[0] : null;
    }

    @Override
    public String[] getParameterValues(String name) {
        return queryParameterMap.get(name);
    }

    @Override
    public Map<String, String[]> getParameterMap() {
            return queryParameterMap; // unmodifiable to uphold the interface contract.
        }

        @Override
        public Enumeration<String> getParameterNames() {
            return Collections.enumeration(queryParameterMap.keySet());
        }

        @Override
        public String getQueryString() {
            // @see : https://stackoverflow.com/a/35831692/9869013
            // return queryParameterMap.entrySet().stream().flatMap(entry -> Stream.of(entry.getValue()).map(value -> entry.getKey() + "=" + value)).collect(Collectors.joining("&")); // without encoding !!
            return queryParameterMap.entrySet().stream().flatMap(entry -> encodeMultiParameter(entry.getKey(), entry.getValue(), requestEncoding)).collect(Collectors.joining("&"));
        }

        private Stream<String> encodeMultiParameter(String key, String[] values, Charset encoding) {
            return Stream.of(values).map(value -> encodeSingleParameter(key, value, encoding));
        }

        private String encodeSingleParameter(String key, String value, Charset encoding) {
            return urlEncode(key, encoding) + "=" + urlEncode(value, encoding);
        }

        private String urlEncode(String value, Charset encoding) {
            try {
                return URLEncoder.encode(value, encoding.name());
            } catch (UnsupportedEncodingException e) {
                throw new IllegalArgumentException("Cannot url encode " + value, e);
            }
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            throw new UnsupportedOperationException("getInputStream() is not implemented in this " + CustomHttpServletRequest.class.getSimpleName() + " wrapper");
        }

    }

note : queryString() requires to process ALL the values for each KEY and don't forget to encodeUrl() when adding your own param values, if required

As a limitation, if you call request.getParameterMap() or any method that would call request.getReader() and begin reading, you will prevent any further calls to request.setCharacterEncoding(...)

How to force a web browser NOT to cache images

I checked all the answers around the web and the best one seemed to be: (actually it isn't)

<img src="image.png?cache=none">

at first.

However, if you add cache=none parameter (which is static "none" word), it doesn't effect anything, browser still loads from cache.

Solution to this problem was:

<img src="image.png?nocache=<?php echo time(); ?>">

where you basically add unix timestamp to make the parameter dynamic and no cache, it worked.

However, my problem was a little different: I was loading on the fly generated php chart image, and controlling the page with $_GET parameters. I wanted the image to be read from cache when the URL GET parameter stays the same, and do not cache when the GET parameters change.

To solve this problem, I needed to hash $_GET but since it is array here is the solution:

$chart_hash = md5(implode('-', $_GET));
echo "<img src='/images/mychart.png?hash=$chart_hash'>";

Edit:

Although the above solution works just fine, sometimes you want to serve the cached version UNTIL the file is changed. (with the above solution, it disables the cache for that image completely) So, to serve cached image from browser UNTIL there is a change in the image file use:

echo "<img src='/images/mychart.png?hash=" . filemtime('mychart.png') . "'>";

filemtime() gets file modification time.

How to run a .awk file?

If you put #!/bin/awk -f on the first line of your AWK script it is easier. Plus editors like Vim and ... will recognize the file as an AWK script and you can colorize. :)

#!/bin/awk -f
BEGIN {}  # Begin section
{}        # Loop section
END{}     # End section

Change the file to be executable by running:

chmod ugo+x ./awk-script

and you can then call your AWK script like this:

`$ echo "something" | ./awk-script`

What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

I had a need for a routine to do this and before searching the web (and finding this page) I came up with my own solution basedon a binary search. Although I'm sure someone has done this before! It runs in constant time and can be faster than the "obvious" solution posted, although I'm not making any great claims, just posting it for interest.

int highest_bit(unsigned int a) {
  static const unsigned int maskv[] = { 0xffff, 0xff, 0xf, 0x3, 0x1 };
  const unsigned int *mask = maskv;
  int l, h;

  if (a == 0) return -1;

  l = 0;
  h = 32;

  do {
    int m = l + (h - l) / 2;

    if ((a >> m) != 0) l = m;
    else if ((a & (*mask << l)) != 0) h = m;

    mask++;
  } while (l < h - 1);

  return l;
}

Selector on background color of TextView

Even this works.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/dim_orange_btn_pressed" />
    <item android:state_focused="true" android:drawable="@color/dim_orange_btn_pressed" />
    <item android:drawable="@android:color/white" />
</selector>

I added the android:drawable attribute to each item, and their values are colors.

By the way, why do they say that color is one of the attributes of selector? They don't write that android:drawable is required.

Color State List Resource

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:color="hex_color"
        android:state_pressed=["true" | "false"]
        android:state_focused=["true" | "false"]
        android:state_selected=["true" | "false"]
        android:state_checkable=["true" | "false"]
        android:state_checked=["true" | "false"]
        android:state_enabled=["true" | "false"]
        android:state_window_focused=["true" | "false"] />
</selector>

setImmediate vs. nextTick

In the comments in the answer, it does not explicitly state that nextTick shifted from Macrosemantics to Microsemantics.

before node 0.9 (when setImmediate was introduced), nextTick operated at the start of the next callstack.

since node 0.9, nextTick operates at the end of the existing callstack, whereas setImmediate is at the start of the next callstack

check out https://github.com/YuzuJS/setImmediate for tools and details

jquery - return value using ajax result on success

With Help from here

function get_result(some_value) {
   var ret_val = {};
   $.ajax({
       url: '/some/url/to/fetch/from',
       type: 'GET',
       data: {'some_key': some_value},
       async: false,
       dataType: 'json'
   }).done(function (response) {
       ret_val = response;
   }).fail(function (jqXHR, textStatus, errorThrown) {
           ret_val = null;
       });
   return ret_val;
}

Hope this helps someone somewhere a bit.

SVG Positioning

There are two ways to group multiple SVG shapes and position the group:

The first to use <g> with transform attribute as Aaron wrote. But you can't just use a x attribute on the <g> element.

The other way is to use nested <svg> element.

<svg id="parent">
   <svg id="group1" x="10">
      <!-- some shapes -->
   </svg>
</svg>

In this way, the #group1 svg is nested in #parent, and the x=10 is relative to the parent svg. However, you can't use transform attribute on <svg> element, which is quite the contrary of <g> element.

Styling Form with Label above Inputs

I know this is an old one with an accepted answer, and that answer works great.. IF you are not styling the background and floating the final inputs left. If you are, then the form background will not include the floated input fields.

To avoid this make the divs with the smaller input fields inline-block rather than float left.

This:

<div style="display:inline-block;margin-right:20px;">
    <label for="name">Name</label>
    <input id="name" type="text" value="" name="name">
</div>

Rather than:

<div style="float:left;margin-right:20px;">
    <label for="name">Name</label>
    <input id="name" type="text" value="" name="name">
</div>

JavaScript function to add X months to a date

Simple solution: 2678400000 is 31 day in milliseconds

var oneMonthFromNow = new Date((+new Date) + 2678400000);

Update:

Use this data to build our own function:

  • 2678400000 - 31 day
  • 2592000000 - 30 days
  • 2505600000 - 29 days
  • 2419200000 - 28 days

How to search for a string in cell array in MATLAB?

I see that everybody missed the most important flaw in your code:

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}

should be:

strs = {'HA' 'KU' 'NA' 'MA' 'TATA'} 

or

strs = {'HAKUNA' 'MATATA'}

Now if you stick to using

ind=find(ismember(strs,'KU'))

You'll have no worries :).

Bootstrap DatePicker, how to set the start date for tomorrow?

There is no official datepicker for bootstrap; as such, you should explicitly state which one you're using.

If you're using eternicode/bootstrap-datepicker, there's a startDate option. As discussed directly under the Options section in the README:

All options that take a "Date" can handle a Date object; a String formatted according to the given format; or a timedelta relative to today, eg '-1d', '+6m +1y', etc, where valid units are 'd' (day), 'w' (week), 'm' (month), and 'y' (year).

So you would do:

$('#datepicker').datepicker({
    startDate: '+1d'
})

Pause in Python

There's no need to wait for input before closing, just change your command like so:

cmd /K python <script>

The /K switch will execute the command that follows, but leave the command interpreter window open, in contrast to /C, which executes and then closes.

How to define static property in TypeScript interface

Static modifiers cannot appear on a type member (TypeScript error TS1070). That's why I recommend to use an abstract class to solve the mission:

Example

// Interface definition
abstract class MyInterface {
  static MyName: string;
  abstract getText(): string;
}

// Interface implementation
class MyClass extends MyInterface {
  static MyName = 'TestName';
  getText(): string {
    return `This is my name static name "${MyClass.MyName}".`;
  }
}

// Test run
const test: MyInterface = new MyClass();
console.log(test.getText());

How to install PHP intl extension in Ubuntu 14.04

you could search with aptitude search intl after you can choose the right one, for example sudo aptitude install php-intl and finally sudo service apache2 restart

good Luck!

Conversion failed when converting the varchar value 'simple, ' to data type int

If you are converting a varchar to int make sure you do not have decimal places.

For example, if you are converting a varchar field with value (12345.0) to an integer then you get this conversion error. In my case I had all my fields with .0 as ending so I used the following statement to globally fix the problem.

CONVERT(int, replace(FIELD_NAME,'.0',''))

Multiple files upload in Codeigniter

I change upload method with images[] according to @Denmark.

    private function upload_files($path, $title, $files)
    {
        $config = array(
            'upload_path'   => $path,
            'allowed_types' => 'jpg|gif|png',
            'overwrite'     => 1,                       
        );

        $this->load->library('upload', $config);

        $images = array();

        foreach ($files['name'] as $key => $image) {
            $_FILES['images[]']['name']= $files['name'][$key];
            $_FILES['images[]']['type']= $files['type'][$key];
            $_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
            $_FILES['images[]']['error']= $files['error'][$key];
            $_FILES['images[]']['size']= $files['size'][$key];

            $fileName = $title .'_'. $image;

            $images[] = $fileName;

            $config['file_name'] = $fileName;

            $this->upload->initialize($config);

            if ($this->upload->do_upload('images[]')) {
                $this->upload->data();
            } else {
                return false;
            }
        }

        return $images;
    }

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

Numpy arrays do not have an append method. Use the Numpy append function instead:

import numpy as np

array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely

For example, if array_1 and array_2 have the following values:

array_1 = np.array([1, 2])
array_2 = np.array([3, 4])

If you call np.append without specifying an axis value, like so:

array_3 = np.append(array_1, array_2)

array_3 will have the following value:

array([1, 2, 3, 4])

Else, if you call np.append with an axis value of 0, like so:

array_3 = np.append(array_1, array_2, axis=0)

array_3 will have the following value:

 array([[1, 2],
        [3, 4]]) 

More information on the append function here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html

What is the proper way to re-attach detached objects in Hibernate?

calling first merge() (to update persistent instance), then lock(LockMode.NONE) (to attach the current instance, not the one returned by merge()) seems to work for some use cases.

React js onClick can't pass value to method

Use a closure, it result in a clean solution:

<th onClick={this.handleSort(column)} >{column}</th>

handleSort function will return a function that have the value column already set.

handleSort: function(value) { 
    return () => {
        console.log(value);
    }
}

The anonymous function will be called with the correct value when the user click on the th.

Example: https://stackblitz.com/edit/react-pass-parameters-example

The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'

Try setting 'clientCredentialType' to 'Windows' instead of 'Ntlm'.

I think that this is what the server is expecting - i.e. when it says the server expects "Negotiate,NTLM", that actually means Windows Auth, where it will try to use Kerberos if available, or fall back to NTLM if not (hence the 'negotiate')

I'm basing this on somewhat reading between the lines of: Selecting a Credential Type

Scala Doubles, and Precision

Here's another solution without BigDecimals

Truncate:

(math floor 1.23456789 * 100) / 100

Round:

(math rint 1.23456789 * 100) / 100

Or for any double n and precision p:

def truncateAt(n: Double, p: Int): Double = { val s = math pow (10, p); (math floor n * s) / s }

Similar can be done for the rounding function, this time using currying:

def roundAt(p: Int)(n: Double): Double = { val s = math pow (10, p); (math round n * s) / s }

which is more reusable, e.g. when rounding money amounts the following could be used:

def roundAt2(n: Double) = roundAt(2)(n)

implementing merge sort in C++

The problem with merge sort is the merge, if you don't actually need to implement the merge, then it is pretty simple (for a vector of ints):

#include <algorithm>
#include <vector>
using namespace std;

typedef vector<int>::iterator iter;

void mergesort(iter b, iter e) {
    if (e -b > 1) {
        iter m = b + (e -b) / 2;
        mergesort(b, m);
        mergesort(m, e);
        inplace_merge(b, m, e);
    }
}

How to remove "disabled" attribute using jQuery?

2018, without JQuery

I know the question is about JQuery: this answer is just FYI.

document.getElementById('edit').addEventListener(event => {
    event.preventDefault();
    [...document.querySelectorAll('.inputDisabled')].map(e => e.disabled = false);
}); 

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

For anyone getting this using ServiceStack backend; add "Authorization" to allowed headers in the Cors plugin:

Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type,Authorization"));

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do it using group by:

c_maxes = df.groupby(['A', 'B']).C.transform(max)
df = df.loc[df.C == c_maxes]

c_maxes is a Series of the maximum values of C in each group but which is of the same length and with the same index as df. If you haven't used .transform then printing c_maxes might be a good idea to see how it works.

Another approach using drop_duplicates would be

df.sort('C').drop_duplicates(subset=['A', 'B'], take_last=True)

Not sure which is more efficient but I guess the first approach as it doesn't involve sorting.

EDIT: From pandas 0.18 up the second solution would be

df.sort_values('C').drop_duplicates(subset=['A', 'B'], keep='last')

or, alternatively,

df.sort_values('C', ascending=False).drop_duplicates(subset=['A', 'B'])

In any case, the groupby solution seems to be significantly more performing:

%timeit -n 10 df.loc[df.groupby(['A', 'B']).C.max == df.C]
10 loops, best of 3: 25.7 ms per loop

%timeit -n 10 df.sort_values('C').drop_duplicates(subset=['A', 'B'], keep='last')
10 loops, best of 3: 101 ms per loop

How to use the 'og' (Open Graph) meta tag for Facebook share

Use:

<!-- For Google -->
<meta name="description" content="" />
<meta name="keywords" content="" />

<meta name="author" content="" />
<meta name="copyright" content="" />
<meta name="application-name" content="" />

<!-- For Facebook -->
<meta property="og:title" content="" />
<meta property="og:type" content="article" />
<meta property="og:image" content="" />
<meta property="og:url" content="" />
<meta property="og:description" content="" />

<!-- For Twitter -->
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="" />
<meta name="twitter:description" content="" />
<meta name="twitter:image" content="" />

Fill the content =" ... " according to the content of your page.

For more information, visit 18 Meta Tags Every Webpage Should Have in 2013.

Git push error '[remote rejected] master -> master (branch is currently checked out)'

I ran into this issue when I had cloned a repo on my NAS and then cloned that repo on to my machines.

The set up is something like this:

ORIGINAL (github):

  • cloned to network storage in my private home network (my home network)
    • branch checked out: DEVELOPMENT
  • cloned to other machines (laptops, small data center server in my office, etc)
    • branch checked out: DEVELOPMENT

When I tried to commit to the from the laptop to the NAS server the error which comes up is

! [remote rejected]   development -> development (branch is currently checked out)

The root cause is that DEVELOPMENT branch is checked out on the NAS server. My solution was on the NAS repository to switch to any other branch. This let me commit my changes.

Retrieving JSON Object Literal from HttpServletRequest

This is simple method to get request data from HttpServletRequest using Java 8 Stream API:

String requestData = request.getReader().lines().collect(Collectors.joining());

curl -GET and -X GET

By default you use curl without explicitly saying which request method to use. If you just pass in a HTTP URL like curl http://example.com it will use GET. If you use -d or -F curl will use POST, -I will cause a HEAD and -T will make it a PUT.

If for whatever reason you're not happy with these default choices that curl does for you, you can override those request methods by specifying -X [WHATEVER]. This way you can for example send a DELETE by doing curl -X DELETE [URL].

It is thus pointless to do curl -X GET [URL] as GET would be used anyway. In the same vein it is pointless to do curl -X POST -d data [URL]... But you can make a fun and somewhat rare request that sends a request-body in a GET request with something like curl -X GET -d data [URL].

Digging deeper

curl -GET (using a single dash) is just wrong for this purpose. That's the equivalent of specifying the -G, -E and -T options and that will do something completely different.

There's also a curl option called --get to not confuse matters with either. It is the long form of -G, which is used to convert data specified with -d into a GET request instead of a POST.

(I subsequently used my own answer here to populate the curl FAQ to cover this.)

Warnings

Modern versions of curl will inform users about this unnecessary and potentially harmful use of -X when verbose mode is enabled (-v) - to make users aware. Further explained and motivated in this blog post.

-G converts a POST + body to a GET + query

You can ask curl to convert a set of -d options and instead of sending them in the request body with POST, put them at the end of the URL's query string and issue a GET, with the use of `-G. Like this:

curl -d name=daniel -d grumpy=yes -G https://example.com/

LINQ: "contains" and a Lambda query

The Linq extension method Any could work for you...

buildingStatus.Any(item => item.GetCharValue() == v.Status)

How to hide a div after some time period?

_x000D_
_x000D_
$().ready(function(){_x000D_
_x000D_
  $('div.alert').delay(1500);_x000D_
   $('div.alert').hide(1000);_x000D_
});
_x000D_
div.alert{_x000D_
color: green;_x000D_
background-color: rgb(50,200,50, .5);_x000D_
padding: 10px;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="alert"><p>Inserted Successfully . . .</p></div>
_x000D_
_x000D_
_x000D_

Add a Progress Bar in WebView

pass your url in this method

private void startWebView(String url) {

        WebSettings settings = webView.getSettings();

        settings.setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);

        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);

        progressDialog = new ProgressDialog(ContestActivity.this);
        progressDialog.setMessage("Loading...");
        progressDialog.show();

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(ContestActivity.this, "Error:" + description, Toast.LENGTH_SHORT).show();

            }
        });
        webView.loadUrl(url);
    }

fork and exec in bash

Use the ampersand just like you would from the shell.

#!/usr/bin/bash
function_to_fork() {
   ...
}

function_to_fork &
# ... execution continues in parent process ...

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

Create a OpenSSL certificate on Windows

You can download a native OpenSSL for Windows, or you can always use Cygwin.

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

How do I call a Django function on button click?

There are 2 possible solutions that I personally use

1.without using form

 <button type="submit" value={{excel_path}} onclick="location.href='{% url 'downloadexcel' %}'" name='mybtn2'>Download Excel file</button>

2.Using Form

<form action="{% url 'downloadexcel' %}" method="post">
{% csrf_token %}


 <button type="submit" name='mybtn2' value={{excel_path}}>Download results in Excel</button>
 </form>

Where urls.py should have this

path('excel/',views1.downloadexcel,name="downloadexcel"),

How to quickly clear a JavaScript Object?

So to recap your question: you want to avoid, as much as possible, trouble with the IE6 GC bug. That bug has two causes:

  1. Garbage Collection occurs once every so many allocations; therefore, the more allocations you make, the oftener GC will run;
  2. The more objects you've got ‘in the air’, the more time each Garbage Collection run takes (since it'll crawl through the entire list of objects to see which are marked as garbage).

The solution to cause 1 seems to be: keep the number of allocations down; assign new objects and strings as little as possible.

The solution to cause 2 seems to be: keep the number of 'live' objects down; delete your strings and objects as soon as you don't need them anymore, and create them afresh when necessary.

To a certain extent, these solutions are contradictory: to keep the number of objects in memory low will entail more allocations and de-allocations. Conversely, constantly reusing the same objects could mean keeping more objects in memory than strictly necessary.


Now for your question. Whether you'll reset an object by creating a new one, or by deleting all its properties: that will depend on what you want to do with it afterwards.

You’ll probably want to assign new properties to it:

  • If you do so immediately, then I suggest assigning the new properties straightaway, and skip deleting or clearing first. (Make sure that all properties are either overwritten or deleted, though!)
  • If the object won't be used immediately, but will be repopulated at some later stage, then I suggest deleting it or assigning it null, and create a new one later on.

There's no fast, easy to use way to clear a JScript object for reuse as if it were a new object — without creating a new one. Which means the short answer to your question is ‘No’, like jthompson says.

How to debug external class library projects in visual studio?

NuGet references

Assume the -Project_A (produces project_a.dll) -Project_B (produces project_b.dll) and Project_B references to Project_A by NuGet packages then just copy project_a.dll , project_a.pdb to the folder Project_B/Packages. In effect that should be copied to the /bin.

Now debug Project_A. When code reaches the part where you need to call dll's method or events etc while debugging, press F11 to step into the dll's code.

Disabling enter key for form

In your form tag just paste this:

onkeypress="return event.keyCode != 13;"

Example

<input type="text" class="search" placeholder="search" onkeypress="return event.keyCode != 13;">

This can be useful if you want to do search when typing and ignoring ENTER.

/// Grab the search term
const searchInput = document.querySelector('.search')
/// Update search term when typing
searchInput.addEventListener('keyup', displayMatches)

Aligning a button to the center

For me it worked using flexbox, which is in my opinion the cleanest solution.

Add a css class around the parent div / element with :

.parent {
display: flex;
}

and for the button use:

.button {
justify-content: center;
}

You should use a parent div, otherwise the button doesn't 'know' what the middle of the page / element is.

If this is not working, try :

#wrapper {
    display:flex;
    justify-content: center;
}

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

For anyone that is still stuck on this issue after trying the above. If you are right-clicking on the database and going to tasks->import, then here is the issue. Go to your start menu and under sql server, find the x64 bit import export wizard and try that. Worked like a charm for me, but it took me FAR too long to find it Microsoft!

SQLite Query in Android to count rows

how to get count column

final String DATABASE_COMPARE = "select count(*) from users where uname="+loginname+ "and pwd="+loginpass;

int sometotal = (int) DatabaseUtils.longForQuery(db, DATABASE_COMPARE, null);

This is the most concise and precise alternative. No need to handle cursors and their closing.

What is python's site-packages directory?

site-packages is just the location where Python installs its modules.

No need to "find it", python knows where to find it by itself, this location is always part of the PYTHONPATH (sys.path).

Programmatically you can find it this way:

import sys
site_packages = next(p for p in sys.path if 'site-packages' in p)
print site_packages

'/Users/foo/.envs/env1/lib/python2.7/site-packages'

Check if a value exists in ArrayList

Better to use a HashSet than an ArrayList when you are checking for existence of a value. Java docs for HashSet says: "This class offers constant time performance for the basic operations (add, remove, contains and size)"

ArrayList.contains() might have to iterate the whole list to find the instance you are looking for.

Use custom build output folder when using create-react-app

Open Command Prompt inside your Application's source. Run the Command

npm run eject

Open your scripts/build.js file and add this at the beginning of the file after 'use strict' line

'use strict';
....
process.env.PUBLIC_URL = './' 
// Provide the current path
.....

enter image description here

Open your config/paths.js and modify the buildApp property in the exports object to your destination folder. (Here, I provide 'react-app-scss' as the destination folder)

module.exports = {
.....
appBuild: resolveApp('build/react-app-scss'),
.....
}

enter image description here

Run

npm run build

Note: Running Platform dependent scripts are not advisable

How do I assign ls to an array in Linux Bash?

This would print the files in those directories line by line.

array=(ww/* ee/* qq/*)
printf "%s\n" "${array[@]}"

How do I search an SQL Server database for a string?

If I want to find where anything I want to search is, I use this:

DECLARE @search_string    varchar(200)
    SET @search_string = '%myString%'

    SELECT DISTINCT
           o.name AS Object_Name,
           o.type_desc,
           m.definition
      FROM sys.sql_modules m
           INNER JOIN
           sys.objects o
             ON m.object_id = o.object_id
     WHERE m.definition Like @search_string;

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

Make the DropDownStyle to DropDownList

stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

Changing WPF title bar background color

Here's an example on how to achieve this:

    <Grid DockPanel.Dock="Right"
      HorizontalAlignment="Right">

        <StackPanel Orientation="Horizontal"
                HorizontalAlignment="Right"
                VerticalAlignment="Center">

            <Button x:Name="MinimizeButton"
                KeyboardNavigation.IsTabStop="False"
                Click="MinimizeWindow"
                Style="{StaticResource MinimizeButton}" 
                Template="{StaticResource MinimizeButtonControlTemplate}" />

            <Button x:Name="MaximizeButton"
                KeyboardNavigation.IsTabStop="False"
                Click="MaximizeClick"
                Style="{DynamicResource MaximizeButton}" 
                Template="{DynamicResource MaximizeButtonControlTemplate}" />

            <Button x:Name="CloseButton"
                KeyboardNavigation.IsTabStop="False"
                Command="{Binding ApplicationCommands.Close}"
                Style="{DynamicResource CloseButton}" 
                Template="{DynamicResource CloseButtonControlTemplate}"/>

        </StackPanel>
    </Grid>
</DockPanel>

Handle Click Events in the code-behind.

For MouseDown -

App.Current.MainWindow.DragMove();

For Minimize Button -

App.Current.MainWindow.WindowState = WindowState.Minimized;

For DoubleClick and MaximizeClick

if (App.Current.MainWindow.WindowState == WindowState.Maximized)
{
    App.Current.MainWindow.WindowState = WindowState.Normal;
}
else if (App.Current.MainWindow.WindowState == WindowState.Normal)
{
    App.Current.MainWindow.WindowState = WindowState.Maximized;
}

How do function pointers in C work?

Function pointers in C

Let's start with a basic function which we will be pointing to:

int addInt(int n, int m) {
    return n+m;
}

First thing, let's define a pointer to a function which receives 2 ints and returns an int:

int (*functionPtr)(int,int);

Now we can safely point to our function:

functionPtr = &addInt;

Now that we have a pointer to the function, let's use it:

int sum = (*functionPtr)(2, 3); // sum == 5

Passing the pointer to another function is basically the same:

int add2to3(int (*functionPtr)(int, int)) {
    return (*functionPtr)(2, 3);
}

We can use function pointers in return values as well (try to keep up, it gets messy):

// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
    printf("Got parameter %d", n);
    int (*functionPtr)(int,int) = &addInt;
    return functionPtr;
}

But it's much nicer to use a typedef:

typedef int (*myFuncDef)(int, int);
// note that the typedef name is indeed myFuncDef

myFuncDef functionFactory(int n) {
    printf("Got parameter %d", n);
    myFuncDef functionPtr = &addInt;
    return functionPtr;
}

Does JavaScript pass by reference?

Primitives are passed by value, and Objects are passed by "copy of a reference".

Specifically, when you pass an object (or array) you are (invisibly) passing a reference to that object, and it is possible to modify the contents of that object, but if you attempt to overwrite the reference it will not affect the copy of the reference held by the caller - i.e. the reference itself is passed by value:

function replace(ref) {
    ref = {};           // this code does _not_ affect the object passed
}

function update(ref) {
    ref.key = 'newvalue';  // this code _does_ affect the _contents_ of the object
}

var a = { key: 'value' };
replace(a);  // a still has its original value - it's unmodfied
update(a);   // the _contents_ of 'a' are changed

How to delete columns in a CSV file?

I would use Pandas with col number

f = pd.read_csv("test.csv", usecols=[0,1,3,4])

f.to_csv("test.csv", index=False)

Play infinitely looping video on-load in HTML5

For iPhone it works if you add also playsinline so:

<video width="320" height="240" autoplay loop muted playsinline>
  <source src="movie.mp4" type="video/mp4" />
</video>

REST API Best practices: Where to put parameters?

I see a lot of REST APIs that don't handle parameters well. One example that comes up often is when the URI includes personally identifiable information.

http://software.danielwatrous.com/design-principles-for-rest-apis/

I think a corollary question is when a parameter shouldn't be a parameter at all, but should instead be moved to the HEADER or BODY of the request.

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}

How can I draw circle through XML Drawable - Android?

no need for the padding or the corners.

here's a sample:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>
</shape>

based on :

https://stackoverflow.com/a/10104037/878126

How to initialize a JavaScript Date to a particular time zone

As Matt Johnson said

If you can limit your usage to modern web browsers, you can now do the following without any special libraries:

new Date().toLocaleString("en-US", {timeZone: "America/New_York"})

This isn't a comprehensive solution, but it works for many scenarios that require only output conversion (from UTC or local time to a specific time zone, but not the other direction).

So although the browser can not read IANA timezones when creating a date, or has any methods to change the timezones on an existing Date object, there seems to be a hack around it:

_x000D_
_x000D_
function changeTimezone(date, ianatz) {

  // suppose the date is 12:00 UTC
  var invdate = new Date(date.toLocaleString('en-US', {
    timeZone: ianatz
  }));

  // then invdate will be 07:00 in Toronto
  // and the diff is 5 hours
  var diff = date.getTime() - invdate.getTime();

  // so 12:00 in Toronto is 17:00 UTC
  return new Date(date.getTime() - diff); // needs to substract

}

// E.g.
var here = new Date();
var there = changeTimezone(here, "America/Toronto");

console.log(`Here: ${here.toString()}\nToronto: ${there.toString()}`);
_x000D_
_x000D_
_x000D_

Confused about __str__ on list in Python

The thing about classes, and setting unencumbered global variables equal to some value within the class, is that what your global variable stores is actually the reference to the memory location the value is actually stored.

What you're seeing in your output is indicative of this.

Where you might be able to see the value and use print without issue on the initial global variables you used because of the str method and how print works, you won't be able to do this with lists, because what is stored in the elements within that list is just a reference to the memory location of the value -- read up on aliases, if you'd like to know more.

Additionally, when using lists and losing track of what is an alias and what is not, you might find you're changing the value of the original list element, if you change it in an alias list -- because again, when you set a list element equal to a list or element within a list, the new list only stores the reference to the memory location (it doesn't actually create new memory space specific to that new variable). This is where deepcopy comes in handy!

Randomize numbers with jQuery?

This doesn't require jQuery. The JavaScript Math.random function returns a random number between 0 and 1, so if you want a number between 1 and 6, you can do:

var number = 1 + Math.floor(Math.random() * 6);

Update: (as per comment) If you want to display a random number that changes every so often, you can use setInterval to create a timer:

setInterval(function() {
  var number = 1 + Math.floor(Math.random() * 6);
  $('#my_div').text(number);
},
1000); // every 1 second

Load local images in React.js

If you have questions about creating React App I encourage you to read its User Guide.
It answers this and many other questions you may have.

Specifically, to include a local image you have two options:

  1. Use imports:

    // Assuming logo.png is in the same folder as JS file
    import logo from './logo.png';
    
    // ...later
    <img src={logo} alt="logo" />
    

This approach is great because all assets are handled by the build system and will get filenames with hashes in the production build. You’ll also get an error if the file is moved or deleted.

The downside is it can get cumbersome if you have hundreds of images because you can’t have arbitrary import paths.

  1. Use the public folder:

    // Assuming logo.png is in public/ folder of your project
    <img src={process.env.PUBLIC_URL + '/logo.png'} alt="logo" />
    

This approach is generally not recommended, but it is great if you have hundreds of images and importing them one by one is too much hassle. The downside is that you have to think about cache busting and watch out for moved or deleted files yourself.

Hope this helps!

Possible heap pollution via varargs parameter

It's rather safe to add @SafeVarargs annotation to the method when you can control the way it's called (e.g. a private method of a class). You must make sure that only the instances of the declared generic type are passed to the method.

If the method exposed externally as a library, it becomes hard to catch such mistakes. In this case it's best to avoid this annotation and rewrite the solution with a collection type (e.g. Collection<Type1<Type2>>) input instead of varargs (Type1<Type2>...).

As for the naming, the term heap pollution phenomenon is quite misleading in my opinion. In the documentation the actual JVM heap is not event mentioned. There is a question at Software Engineering that contains some interesting thoughts on the naming of this phenomenon.

UnsatisfiedDependencyException: Error creating bean with name

If you are using Spring Boot, your main app should be like this (just to make and understand things in simple way) -

package aaa.bbb.ccc;
@SpringBootApplication
@ComponentScan({ "aaa.bbb.ccc.*" })
public class Application {
.....

Make sure you have @Repository and @Service appropriately annotated.

Make sure all your packages fall under - aaa.bbb.ccc.*

In most cases this setup resolves these kind of trivial issues. Here is a full blown example. Hope it helps.

Reverse colormap in matplotlib

The standard colormaps also all have reversed versions. They have the same names with _r tacked on to the end. (Documentation here.)

Inserting image into IPython notebook markdown

I put the IPython notebook in the same folder with the image. I use Windows. The image name is "phuong huong xac dinh.PNG".

In Markdown:

<img src="phuong huong xac dinh.PNG">

Code:

from IPython.display import Image
Image(filename='phuong huong xac dinh.PNG')

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

this will work as you asked without CHAR(38):

update t set country = 'Trinidad and Tobago' where country = 'trinidad & '|| 'tobago';

create table table99(col1 varchar(40));
insert into table99 values('Trinidad &' || '  Tobago');
insert into table99 values('Trinidad &' || '  Tobago');
insert into table99 values('Trinidad &' || '  Tobago');
insert into table99 values('Trinidad &' || '  Tobago');
SELECT * FROM table99;

update table99 set col1 = 'Trinidad and Tobago' where col1 = 'Trinidad &'||'  Tobago';

How to check if text fields are empty on form submit using jQuery?

you need to add a handler to the form submit event. In the handler you need to check for each text field, select element and password fields if there values are non empty.

$('form').submit(function() {
     var res = true;
     // here I am checking for textFields, password fields, and any 
     // drop down you may have in the form
     $("input[type='text'],select,input[type='password']",this).each(function() {
         if($(this).val().trim() == "") {
             res = false; 
         }
     })
     return res; // returning false will prevent the form from submitting.
});

How to hide keyboard in swift on pressing return key?

I hate to add the same function to every UIViewController. By extending UIViewController to support UITextFieldDelegate, you can provide a default behavior of "return pressed".

extension UIViewController: UITextFieldDelegate{
    public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true;
    }
}

When you create new UIViewController and UITextField, all you have to do is to write one line code in your UIViewController.

override func viewDidLoad() {
    super.viewDidLoad()
    textField.delegate = self
}

You can even omit this one line code by hooking delegate in Main.storyboard. (Using "ctrl" and drag from UITextField to UIViewController)

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.

I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.

  1. Go to the "Manage NuGet Packages"
  2. Select the Installed Package "Microsoft ASP.NET Web API 2.1"
  3. Click Manage and check the projects that I manually added before.

jQuery datepicker years shown

au, nz, ie, etc. are the country codes for the countries whose national days are being displayed (Australia, New Zealand, Ireland, ...). As seen in the code, these values are combined with '_day' and passed back to be applied to that day as a CSS style. The corresponding styles are of the form show below, which moves the text for that day out of the way and replaces it with an image of the country's flag.

.au_day {
  text-indent: -9999px;
  background: #eee url(au.gif) no-repeat center;
}

The 'false' value that is passed back with the new style indicates that these days may not be selected.

How do I perform HTML decoding/encoding using Python/Django?

I found this in the Cheetah source code (here)

htmlCodes = [
    ['&', '&amp;'],
    ['<', '&lt;'],
    ['>', '&gt;'],
    ['"', '&quot;'],
]
htmlCodesReversed = htmlCodes[:]
htmlCodesReversed.reverse()
def htmlDecode(s, codes=htmlCodesReversed):
    """ Returns the ASCII decoded version of the given HTML string. This does
        NOT remove normal HTML tags like <p>. It is the inverse of htmlEncode()."""
    for code in codes:
        s = s.replace(code[1], code[0])
    return s

not sure why they reverse the list, I think it has to do with the way they encode, so with you it may not need to be reversed. Also if I were you I would change htmlCodes to be a list of tuples rather than a list of lists... this is going in my library though :)

i noticed your title asked for encode too, so here is Cheetah's encode function.

def htmlEncode(s, codes=htmlCodes):
    """ Returns the HTML encoded version of the given string. This is useful to
        display a plain ASCII text string on a web page."""
    for code in codes:
        s = s.replace(code[0], code[1])
    return s

How can I put a ListView into a ScrollView without it collapsing?

Although the suggested setListViewHeightBasedOnChildren() methods work in most of the cases, in some cases, specially with a lot of items, I noticed that the last elements are not displayed. So I decided to mimic a simple version of the ListView behavior in order to reuse any Adapter code, here it's the ListView alternative:

import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListAdapter;

public class StretchedListView extends LinearLayout {

private final DataSetObserver dataSetObserver;
private ListAdapter adapter;
private OnItemClickListener onItemClickListener;

public StretchedListView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setOrientation(LinearLayout.VERTICAL);
    this.dataSetObserver = new DataSetObserver() {
        @Override
        public void onChanged() {
            syncDataFromAdapter();
            super.onChanged();
        }

        @Override
        public void onInvalidated() {
            syncDataFromAdapter();
            super.onInvalidated();
        }
    };
}

public void setAdapter(ListAdapter adapter) {
    ensureDataSetObserverIsUnregistered();

    this.adapter = adapter;
    if (this.adapter != null) {
        this.adapter.registerDataSetObserver(dataSetObserver);
    }
    syncDataFromAdapter();
}

protected void ensureDataSetObserverIsUnregistered() {
    if (this.adapter != null) {
        this.adapter.unregisterDataSetObserver(dataSetObserver);
    }
}

public Object getItemAtPosition(int position) {
    return adapter != null ? adapter.getItem(position) : null;
}

public void setSelection(int i) {
    getChildAt(i).setSelected(true);
}

public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
    this.onItemClickListener = onItemClickListener;
}

public ListAdapter getAdapter() {
    return adapter;
}

public int getCount() {
    return adapter != null ? adapter.getCount() : 0;
}

private void syncDataFromAdapter() {
    removeAllViews();
    if (adapter != null) {
        int count = adapter.getCount();
        for (int i = 0; i < count; i++) {
            View view = adapter.getView(i, null, this);
            boolean enabled = adapter.isEnabled(i);
            if (enabled) {
                final int position = i;
                final long id = adapter.getItemId(position);
                view.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (onItemClickListener != null) {
                            onItemClickListener.onItemClick(null, v, position, id);
                        }
                    }
                });
            }
            addView(view);

        }
    }
}
}

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

How to set an image as a background for Frame in Swing GUI of java?

There is no concept of a "background image" in a JPanel, so one would have to write their own way to implement such a feature.

One way to achieve this would be to override the paintComponent method to draw a background image on each time the JPanel is refreshed.

For example, one would subclass a JPanel, and add a field to hold the background image, and override the paintComponent method:

public class JPanelWithBackground extends JPanel {

  private Image backgroundImage;

  // Some code to initialize the background image.
  // Here, we use the constructor to load the image. This
  // can vary depending on the use case of the panel.
  public JPanelWithBackground(String fileName) throws IOException {
    backgroundImage = ImageIO.read(new File(fileName));
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Draw the background image.
    g.drawImage(backgroundImage, 0, 0, this);
  }
}

(Above code has not been tested.)

The following code could be used to add the JPanelWithBackground into a JFrame:

JFrame f = new JFrame();
f.getContentPane().add(new JPanelWithBackground("sample.jpeg"));

In this example, the ImageIO.read(File) method was used to read in the external JPEG file.

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

SELECT CAST(Datetimefield AS DATE) as DateField, SUM(intfield) as SumField
FROM MyTable
GROUP BY CAST(Datetimefield AS DATE)

How can I select an element by name with jQuery?

You can get the name value from an input field using name element in jQuery by:

_x000D_
_x000D_
var firstname = jQuery("#form1 input[name=firstname]").val(); //Returns ABCD_x000D_
var lastname = jQuery("#form1 input[name=lastname]").val(); //Returns XYZ _x000D_
console.log(firstname);_x000D_
console.log(lastname);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form name="form1" id="form1">_x000D_
  <input type="text" name="firstname" value="ABCD"/>_x000D_
  <input type="text" name="lastname" value="XYZ"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Calling stored procedure with return value

This is a very short sample of returning a single value from a procedure:

SQL:

CREATE PROCEDURE [dbo].[MakeDouble] @InpVal int AS BEGIN 
SELECT @InpVal * 2; RETURN 0; 
END

C#-code:

int inpVal = 11;
string retVal = "?";
using (var sqlCon = new SqlConnection(
    "Data Source = . ; Initial Catalog = SampleDb; Integrated Security = True;"))
{
    sqlCon.Open();
    retVal = new SqlCommand("Exec dbo.MakeDouble " + inpVal + ";", 
        sqlCon).ExecuteScalar().ToString();
    sqlCon.Close();
}
Debug.Print(inpVal + " * 2 = " + retVal); 
//> 11 * 2 = 22

http://localhost:50070 does not work HADOOP

if you are running and old version of Hadoop (hadoop 1.2) you got an error because http://localhost:50070/dfshealth.html does'nt exit. Check http://localhost:50070/dfshealth.jsp which works !

What are examples of TCP and UDP in real life?

SCTP vs TCP vs UDPServices/Features       SCTP        TCP       UDP
Connection-oriented                       yes         yes       no
Full duplex                               yes         yes       yes
Reliable data transfer                    yes         yes       no
Partial-reliable data transfer            optional    no        no
Ordered data delivery                     yes         yes       no
Unordered data delivery                   yes         no        yes
Flow control                              yes         yes       no
Congestion control                        yes         yes       no
ECN capable                               yes         yes       no
Selective ACKs                            yes         optional  no
Preservation of message boundaries        yes         no        yes
Path MTU discovery                        yes         yes       no
Application PDU fragmentation             yes         yes       no
Application PDU bundling                  yes         yes       no
Multistreaming                            yes         no        no
Multihoming                               yes         no        no
Protection against SYN flooding attacks   yes         no        n/a
Allows half-closed connections            no          yes       n/a
Reachability check                        yes         yes       no
Psuedo-header for checksum                no (vtags)  yes       yes
Time wait state                           vtags       4-tuple   n/a

"Could not find Developer Disk Image"

Simply updated Xcode. Solved my problem

Use mysql_fetch_array() with foreach() instead of while()

the most obvious way to make foreach a possibility includes materializing the whole resultset in an array, which will probably kill you memory-wise, sooner or later. you'd need to turn to iterators to avoid that problem. see http://www.php.net/~helly/php/ext/spl/

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

I had this problem but didn't have a version conflict in my package.json.

My package-lock.json was somehow out of sync with package json though. Deleting and regenerating it worked for me.

Save bitmap to file function

implementation save bitmap and load bitmap directly. fast and ease on mfc class

void CMRSMATH1Dlg::Loadit(TCHAR *destination, CDC &memdc)
{
CImage img;
PBITMAPINFO bmi;
BITMAPINFOHEADER Info;
BITMAPFILEHEADER bFileHeader;
CBitmap bm;     
CFile file2;
file2.Open(destination, CFile::modeRead | CFile::typeBinary);
file2.Read(&bFileHeader, sizeof(BITMAPFILEHEADER));
file2.Read(&Info, sizeof(BITMAPINFOHEADER));    
BYTE ch;
int width = Info.biWidth;
int height = Info.biHeight;
if (height < 0)height = -height;
int size1 = width*height * 3;
int size2 = ((width * 24 + 31) / 32) * 4 * height;
int widthnew = (size2 - size1) / height;
BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
//////////////////////////
HGDIOBJ old;
unsigned char alpha = 0;    
int z = 0;  
z = 0;
int gap = (size2 - size1) / height;
for (int y = 0;y < height;y++)
{
    for (int x = 0;x < width*3;x++)
    {
        file2.Read(&ch, 1);
        buffer[z] = ch;
        z++;
    }
    for (int z1 = 0;z1 <gap;z1++)
    {
        file2.Read(&ch,1);
    }
}
bm.CreateCompatibleBitmap(&memdc, width, height);
bm.SetBitmapBits(size1,buffer);
old = memdc.SelectObject(&bm);   
///////////////////////////  
 //bm.SetBitmapBits(size1, buffer);     
 GetDC()->BitBlt(1, 95, width, height, &memdc, 0, 0, SRCCOPY);
 memdc.SelectObject(&old);
 bm.DeleteObject();
 GlobalFree(buffer);     
 file2.Close();
 }
 void CMRSMATH1Dlg::saveit(CBitmap &bit1, CDC &memdc, TCHAR *destination)
  {     
BITMAP bm;
PBITMAPINFO bmi;
BITMAPINFOHEADER Info;
BITMAPFILEHEADER bFileHeader;
CFile file1;
            CSize size = bit1.GetBitmap(&bm);
 int z = 0;  
 BYTE ch = 0;
 size.cx = bm.bmWidth;
 size.cy = bm.bmHeight;
 int width = size.cx;    
 int size1 = (size.cx)*(size.cy);
 int size2 = size1 * 3;  
 size1 = ((size.cx * 24 + 31) / 32) *4* size.cy;     
 BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);               
 bFileHeader.bfType = 'B' + ('M' << 8); 
 bFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
 bFileHeader.bfSize = bFileHeader.bfOffBits + size1;
 bFileHeader.bfReserved1 = 0;
 bFileHeader.bfReserved2 = 0;   
 Info.biSize = sizeof(BITMAPINFOHEADER);
 Info.biPlanes = 1;
 Info.biBitCount = 24;//bm.bmBitsPixel;//bitsperpixel///////////////////32
 Info.biCompression = BI_RGB;
 Info.biWidth =bm.bmWidth;
 Info.biHeight =-bm.bmHeight;///reverse pic if negative height
 Info.biSizeImage =size1;
 Info.biClrImportant = 0;
 if (bm.bmBitsPixel <= 8)
 {
     Info.biClrUsed = 1 << bm.bmBitsPixel;
 }else
 Info.biClrUsed = 0;
 Info.biXPelsPerMeter = 0;
 Info.biYPelsPerMeter = 0;
 bit1.GetBitmapBits(size2, buffer);      
 file1.Open(destination, CFile::modeCreate | CFile::modeWrite |CFile::typeBinary,0);
 file1.Write(&bFileHeader, sizeof(BITMAPFILEHEADER));
 file1.Write(&Info, sizeof(BITMAPINFOHEADER));
 unsigned char alpha = 0;    
 for (int y = 0;y<size.cy;y++)
 {
     for (int x = 0;x<size.cx;x++)
     {
         //for reverse picture below
         //z = (((size.cy - 1 - y)*size.cx) + (x)) * 3;          
     z = (((y)*size.cx) + (x)) * 3;
     file1.Write(&buffer[z], 1);
     file1.Write(&buffer[z + 1], 1);
     file1.Write(&buffer[z + 2], 1);
     }               
     for (int z = 0;z < (size1 - size2) / size.cy;z++)
     {
         file1.Write(&alpha, 1);
     }
 }   
 GlobalFree(buffer);     
 file1.Close();  
 file1.m_hFile = NULL;
        }

await is only valid in async function

async/await is the mechanism of handling promise, two ways we can do it

functionWhichReturnsPromise()
            .then(result => {
                console.log(result);
            })
            .cathc(err => {
                console.log(result);

            });

or we can use await to wait for the promise to full-filed it first, which means either it is rejected or resolved.

Now if we want to use await (waiting for a promise to fulfil) inside a function, it's mandatory that the container function must be an async function because we are waiting for a promise to fulfiled asynchronously || make sense right?.

async function getRecipesAw(){
            const IDs = await getIds; // returns promise
            const recipe = await getRecipe(IDs[2]); // returns promise
            return recipe; // returning a promise
        }

        getRecipesAw().then(result=>{
            console.log(result);
        }).catch(error=>{
            console.log(error);
        });

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment as you can see above).

Try checking to see if Hibernate core is put in as dependency:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.0.11.Final</version>
  <scope>compile</scope>
</dependency>

break/exit script

You could use the stopifnot() function if you want the program to produce an error:

foo <- function(x) {
    stopifnot(x > 500)
    # rest of program
}

How to perform a for-each loop over all the files under a specified path?

Use command substitution instead of quotes to execute find instead of passing the command as a string:

for line in $(find . -iname '*.txt'); do 
     echo $line
     ls -l $line; 
done

Creating a file name as a timestamp in a batch job

used Martin's suggestion with a little tweak to add time stamp to the file name:

forfiles /p [foldername] /m rsync2.log /c "cmd /c ren @file %DATE:~6,4%%DATE:~3,2%%DATE:~0,2%_%time:~-11,2%-%time:~-8,2%-%time:~-5,2%-@file

For the 10:17:21 23/10/2019 The result is:

20191023_10-17-21-rsync2.log

jQuery autohide element after 5 seconds

$(function() {
    // setTimeout() function will be fired after page is loaded
    // it will wait for 5 sec. and then will fire
    // $("#successMessage").hide() function
    setTimeout(function() {
        $("#successMessage").hide('blind', {}, 500)
    }, 5000);
});

Note: In order to make you jQuery function work inside setTimeout you should wrap it inside

function() { ... }

Search for value in DataGridView in a column

"MyTable".DefaultView.RowFilter = " LIKE '%" + textBox1.Text + "%'"; this.dataGridView1.DataSource = "MyTable".DefaultView;

How about the relation to the database connections and the Datatable? And how should i set the DefaultView correct?

I use this code to get the data out:

con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=C:\\Users\\mhadj\\Documents\\Visual Studio 2015\\Projects\\data_base_test_2\\Sample.sdf";
con.Open();

DataTable dt = new DataTable();

adapt = new System.Data.SqlServerCe.SqlCeDataAdapter("select * from tbl_Record", con);        
adapt.Fill(dt);        
dataGridView1.DataSource = dt;
con.Close();

Variably modified array at file scope

If you're going to use the preprocessor anyway, as per the other answers, then you can make the compiler determine the value of NUM_TYPES automagically:

#define NUM_TYPES (sizeof types / sizeof types[0])
static int types[] = { 
  1,
  2, 
  3, 
  4 };

XAMPP Port 80 in use by "Unable to open process" with PID 4

Simply set Apache to listen on a different port. This can be done by clicking on the "Config" button on the same line as the "Apache" module, select the "httpd.conf" file in the dropdown, then change the "Listen 80" line to "Listen 8080". Save the file and close it.

Now it avoids Port 80 and uses Port 8080 instead without issue. The only additional thing you need to do is make sure to put localhost:8080 in the browser so the browser knows to look on Port 8080. Otherwise it defaults to Port 80 and won't find your local site.

SQL Server - inner join when updating

UPDATE R 
SET R.status = '0' 
FROM dbo.ProductReviews AS R
INNER JOIN dbo.products AS P 
       ON R.pid = P.id 
WHERE R.id = '17190' 
  AND P.shopkeeper = '89137';

Firebase FCM notifications click_action payload

Now it is possible to set click_action in Firebase Console. You just go to notifications-send message-advanced option and there you will have two fields for key and value. In first field you put click_action and in second you put some text which represents value of that action. And you add intent-filter in your Manifest and give him the same value as you wrote in console. And that is simulation of real click_action.

Bootstrap modal in React.js

You can use the model from the react-bootstrap from link and it's basically a function based

function Example() {
  const [show, setShow] = useState(false);
  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);
  return (
    <>
      <Button variant="primary" onClick={handleShow}>
        Launch demo modal
      </Button>

      <Modal show={show} onHide={handleClose} animation={false}>
        <Modal.Header closeButton>
          <Modal.Title>Modal heading</Modal.Title>
        </Modal.Header>
        <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={handleClose}>
            Close
          </Button>
          <Button variant="primary" onClick={handleClose}>
            Save Changes
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}

and You can convert it into the class component

import React, { Component } from "react";
import { Button, Modal } from "react-bootstrap";


export default class exampleextends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      close: false,
    };
  } 
  render() {
    return (
      <div>
        <Button
          variant="none"
          onClick={() => this.setState({ show: true })}
        >
          Choose Profile
        </Button>
        <Modal
          show={this.state.show}
          animation={true}
          size="md" className="" shadow-lg border">
          <Modal.Header className="bg-danger text-white text-center py-1">
            <Modal.Title className="text-center">
              <h5>Delete</h5>
            </Modal.Title>
          </Modal.Header>
          <Modal.Body className="py-0 border">
            body   
          </Modal.Body>
<Modal.Footer className="py-1 d-flex justify-content-center">
              <div>
                <Button
                  variant="outline-dark" onClick={() => this.setState({ show: false })}>Cancel</Button>
              </div>
              <div>
                <Button variant="outline-danger" className="mx-2 px-3">Delete</Button>
              </div>
            </Modal.Footer>
        </Modal>
      </div>
    );
  }
}

How to convert string to boolean php

You should be able to cast to a boolean using (bool) but I'm not sure without checking whether this works on the strings "true" and "false".

This might be worth a pop though

$myBool = (bool)"False"; 

if ($myBool) {
    //do something
}

It is worth knowing that the following will evaluate to the boolean False when put inside

if()
  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Everytyhing else will evaluate to true.

As descried here: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

Should try...catch go inside or outside a loop?

In your examples there is no functional difference. I find your first example more readable.

Button that refreshes the page on click

button that refresh the page on click

Use onClick button with window.location.reload():

<button onClick="window.location.reload();">

Get Hard disk serial Number

In case you want to use it for copy protection and you need it to return always the same serial on one computer (of course as far as first hdd or ssd is not changed) I would recommend code below. For ManagementClass you need to add reference to System.Management. P.S. Without "InterfaceType" and "DeviceID" check that method can return serial of random disk or serial of USB flash drive which connected to pc right now.

    public static string GetSerial()
    {
        try
        {
            var mc = new ManagementClass("Win32_DiskDrive");
            var moc = mc.GetInstances();
            var res = string.Empty;
            var resList = new List<string>(moc.Count);

            foreach (ManagementObject mo in moc)
            {
                try
                {
                    if (mo["InterfaceType"].ToString().Replace(" ", string.Empty) == "USB")
                    {
                        continue;
                    }
                }
                catch
                {
                }

                try
                {
                    res = mo["SerialNumber"].ToString().Replace(" ", string.Empty);
                    resList.Add(res);
                    if (mo["DeviceID"].ToString().Replace(" ", string.Empty).Contains("0"))
                    {
                        if (!string.IsNullOrWhiteSpace(res))
                        {
                            return res;
                        }
                    }
                }
                catch
                {
                }
            }

            res = resList[0];
            if (!string.IsNullOrWhiteSpace(res))
            {
                return res;
            }
        }
        catch
        {
        }

        return string.Empty;
    }