Programs & Examples On #File access

How do I create a file AND any folders, if the folders don't exist?

To summarize what has been commented in other answers:

//path = @"C:\Temp\Bar\Foo\Test.txt";
Directory.CreateDirectory(Path.GetDirectoryName(path));

Directory.CreateDirectory will create the directories recursively and if the directory already exist it will return without an error.

If there happened to be a file Foo at C:\Temp\Bar\Foo an exception will be thrown.

Local file access with JavaScript

UPDATE This feature is removed since Firefox 17 (see https://bugzilla.mozilla.org/show_bug.cgi?id=546848).


On Firefox you (the programmer) can do this from within a JavaScript file:

netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");

and you (the browser user) will be prompted to allow access. (for Firefox you just need to do this once every time the browser is started)

If the browser user is someone else, they have to grant permission.

Error converting data types when importing from Excel to SQL Server 2008

Going off of what Derloopkat said, which still can fail on conversion (no offense Derloopkat) because Excel is terrible at this:

  1. Paste from excel into Notepad and save as normal (.txt file).
  2. From within excel, open said .txt file.
  3. Select next as it is obviously tab delimited.
  4. Select "none" for text qualifier, then next again.
  5. Select the first row, hold shift, select the last row, and select the text radial button. Click Finish

It will open, check it to make sure it's accurate and then save as an excel file.

JavaScript Regular Expression Email Validation

You can also try this expression, I have tested it against many email addresses.

var pattern = /^[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+\.)+([A-Za-z0-9]{2,4}|museum)$/;

Create an application setup in visual studio 2013

Microsoft has listened to the cry for supporting installers (MSI) in Visual Studio and release the Visual Studio Installer Projects Extension. You can now create installers in VS2013, download the extension here from the visualstudiogallery.

visual-studio-installer-projects-extension

Need a query that returns every field that contains a specified letter

try this

Select * From Table
Where field like '%' + ltrValue1 + '%'
  And field like '%' + ltrValue2 + '%'
... etc.

and be prepared for a table scan as this functionality cannot use any existing indices

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

This works with me :
1- select the cells which shall be be affected by the drop down list .
2- home -> conditional formating -> new rule .
3- format only cells that contain .
4- in format only cells with ... select specific text , in formatting rule "= select Elementary from your drop down list"
if drop list in another sheet then when select Elementary we see "=Sheet3!$F$2" in the new rule , with your own sheet and cell number.
5- format -> fill -> select color -> ok.
6-ok .
do the same for each element in drop down list then you will see the magic !

jQuery javascript regex Replace <br> with \n

a cheap and nasty would be:

jQuery("#myDiv").html().replace("<br>", "\n").replace("<br />", "\n")

EDIT

jQuery("#myTextArea").val(
    jQuery("#myDiv").html()
        .replace(/\<br\>/g, "\n")
        .replace(/\<br \/\>/g, "\n")
);

Also created a jsfiddle if needed: http://jsfiddle.net/2D3xx/

How to get terminal's Character Encoding

To see the current locale information use locale command. Below is an example on RHEL 7.8

[usr@host ~]$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

How to prevent Right Click option using jquery

I think this should help. Trick is to bind the contextmenu event.

<script type="text/javascript" language="javascript">
        $(function() {
            $(this).bind("contextmenu", function(e) {
                e.preventDefault();
            });
        }); 
</script>

Binding a generic list to a repeater - ASP.NET

It is surprisingly simple...

Code behind:

// Here's your object that you'll create a list of
private class Products
{
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    public string ProductPrice { get; set; }
}

// Here you pass in the List of Products
private void BindItemsInCart(List<Products> ListOfSelectedProducts)
{   
    // The the LIST as the DataSource
    this.rptItemsInCart.DataSource = ListOfSelectedProducts;

    // Then bind the repeater
    // The public properties become the columns of your repeater
    this.rptItemsInCart.DataBind();
}

ASPX code:

<asp:Repeater ID="rptItemsInCart" runat="server">
  <HeaderTemplate>
    <table>
      <thead>
        <tr>
            <th>Product Name</th>
            <th>Product Description</th>
            <th>Product Price</th>
        </tr>
      </thead>
      <tbody>
  </HeaderTemplate>
  <ItemTemplate>
    <tr>
      <td><%# Eval("ProductName") %></td>
      <td><%# Eval("ProductDescription")%></td>
      <td><%# Eval("ProductPrice")%></td>
    </tr>
  </ItemTemplate>
  <FooterTemplate>
    </tbody>
    </table>
  </FooterTemplate>
</asp:Repeater>

I hope this helps!

How do you access the value of an SQL count () query in a Java program

I have done it this way (example):

String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"[email protected]"'";
int count=0;
try {
    ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
    while(rs.next())
        count=rs.getInt(1);
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    //...
}

Comparing Dates in Oracle SQL

Single quote must be there, since date converted to character.

Select employee_id, count(*)
From Employee
Where to_char(employee_date_hired, 'DD-MON-YY') > '31-DEC-95';

How to get the first non-null value in Java?

You can try this:

public static <T> T coalesce(T... t) {
    return Stream.of(t).filter(Objects::nonNull).findFirst().orElse(null);
}

Based on this response

React Modifying Textarea Values

I think you want something along the line of:

Parent:

<Editor name={this.state.fileData} />

Editor:

var Editor = React.createClass({
  displayName: 'Editor',
  propTypes: {
    name: React.PropTypes.string.isRequired
  },
  getInitialState: function() { 
    return {
      value: this.props.name
    };
  },
  handleChange: function(event) {
    this.setState({value: event.target.value});
  },
  render: function() {
    return (
      <form id="noter-save-form" method="POST">
        <textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
        <input type="submit" value="Save" />
      </form>
    );
  }
});

This is basically a direct copy of the example provided on https://facebook.github.io/react/docs/forms.html

Update for React 16.8:

import React, { useState } from 'react';

const Editor = (props) => {
    const [value, setValue] = useState(props.name);

    const handleChange = (event) => {
        setValue(event.target.value);
    };

    return (
        <form id="noter-save-form" method="POST">
            <textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
            <input type="submit" value="Save" />
        </form>
    );
}

Editor.propTypes = {
    name: PropTypes.string.isRequired
};

SQL subquery with COUNT help

Do you want to get the number of rows?

SELECT columnName, COUNT(*) AS row_count
FROM eventsTable
WHERE columnName = 'Business'
GROUP BY columnName

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

How to increment variable under DOS?

I've found my own solution.

Download FreeDOS from here: http://chtaube.eu/computers/freedos/bootable-usb/

Then using my Counter.exe file (which basically generates a Counter.txt file and increments the number inside every time it's being called), I can assign the value of the number to a variable using:

Set /P Variable =< Counter.txt

Then, I can check if it has run 250 cycles by doing:

if %variable%==250 echo PASS

BTW, I still can't use Set /A since FreeDOS doesn't support this command, but at least it supports the Set /P command.

Looping through all rows in a table column, Excel-VBA

You can loop through the cells of any column in a table by knowing just its name and not its position. If the table is in sheet1 of the workbook:

Dim rngCol as Range
Dim cl as Range
Set rngCol = Sheet1.Range("TableName[ColumnName]")
For Each cl in rngCol
    cl.Value = "PHEV"
Next cl

The code above will loop through the data values only, excluding the header row and the totals row. It is not necessary to specify the number of rows in the table.

Use this to find the location of any column in a table by its column name:

Dim colNum as Long
colNum = Range("TableName[Column name to search for]").Column

This returns the numeric position of a column in the table.

Pretty printing XML with javascript

here is another function to format xml

function formatXml(xml){
    var out = "";
    var tab = "    ";
    var indent = 0;
    var inClosingTag=false;
    var dent=function(no){
        out += "\n";
        for(var i=0; i < no; i++)
            out+=tab;
    }


    for (var i=0; i < xml.length; i++) {
        var c = xml.charAt(i);
        if(c=='<'){
            // handle </
            if(xml.charAt(i+1) == '/'){
                inClosingTag = true;
                dent(--indent);
            }
            out+=c;
        }else if(c=='>'){
            out+=c;
            // handle />
            if(xml.charAt(i-1) == '/'){
                out+="\n";
                //dent(--indent)
            }else{
              if(!inClosingTag)
                dent(++indent);
              else{
                out+="\n";
                inClosingTag=false;
              }
            }
        }else{
          out+=c;
        }
    }
    return out;
}

Import SQL file into mysql

Does your dump contain features that are not supported in your version of MySQL? You can also try to remove the starting (and ending) MySQL commented SET-statements.

I don't know if your dump comes from a Linux version of MySQL (line endings)?

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.

Conclusion

  • USE REQUIRES_NEW if you want to commit what did you do before exception (Local commit)
  • USE REQUIRED if you want to commit only when all processes are done (Global commit) And you just need to ignore "Transaction rolled back because it has been marked as rollback-only" exception. But you need to try-catch out side the caller processNextRegistrationMessage() to have a meaning log.

Let's me explain more detail:

Question: How many Transaction we have? Answer: Only one

Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.

Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction

  1. When persist() method has an exception
  2. Go to the catch outside

    Spring will set the rollBackOnly to true -> it determine we must 
    rollback the caller (processNextRegistrationMessage) also.
    
  3. The persist() will rollback itself first.

  4. Throw an UnexpectedRollbackException to inform that, we need to rollback the caller also.
  5. The try-catch in run() will catch UnexpectedRollbackException and print the stack trace

Question: Why we change PROPAGATION to REQUIRES_NEW, it works?

Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.

Thanks

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

Maven uses batch files to do its business. With any batch script, you must call another script using the call command so it knows to return back to your script after the called script completes. Try prepending call to all commands.

Another thing you could try is using the start command which should work similarly.

INSERT IF NOT EXISTS ELSE UPDATE?

Firstly update it. If affected row count = 0 then insert it. Its the easiest and suitable for all RDBMS.

How to reset db in Django? I get a command 'reset' not found error

If you want to clean the whole database, you can use: python manage.py flush If you want to clean database table of a Django app, you can use: python manage.py migrate appname zero

Open the terminal in visual studio?

Microsoft just included an integrated Windows Terminal in Visual Studio version 16.3 Preview 3. Go to Tools > Options > Preview Features, enable the Experimental VS Terminal option and restart Visual Studio.

https://devblogs.microsoft.com/visualstudio/say-hello-to-the-new-visual-studio-terminal/

SQL query, store result of SELECT in local variable

I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.

declare @myVal int; set @myVal = isnull((select a from table1), 0);

Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.

CSS Selector for <input type="?"

Sorry, the short answer is no. CSS (2.1) will only mark up the elements of a DOM, not their attributes. You'd have to apply a specific class to each input.

Bummer I know, because that would be incredibly useful.

I know you've said you'd prefer CSS over JavaScript, but you should still consider using jQuery. It provides a very clean and elegant way of adding styles to DOM elements based on attributes.

Make child div stretch across width of page

You could take it out of the flow with position:absolute. But the helper_panel will oberlap with other stuff. (I added orders, to see the divs)

<div id="container" style="width: 960px; border:1px solid #f00;">
    Text before<br>
   <div id="help_panel" style="width: 100%; position:absolute; margin: 0 auto; border:1px solid #0f0;">
     Content goes here.
   </div> 
   This is behind the help_penal
</div>

Get line number while using grep

In order to display the results with the line numbers, you might try this

grep -nr "word to search for" /path/to/file/file 

The result should be something like this:

linenumber: other data "word to search for" other data

How to avoid 'cannot read property of undefined' errors?

Update:

  • If you use JavaScript according to ECMAScript 2020 or later, see optional chaining.
  • TypeScript has added support for optional chaining in version 3.7.
// use it like this
obj?.a?.lot?.of?.properties

Solution for JavaScript before ECMASCript 2020 or TypeScript older than version 3.7:

A quick workaround is using a try/catch helper function with ES6 arrow function:

_x000D_
_x000D_
function getSafe(fn, defaultVal) {
  try {
    return fn();
  } catch (e) {
    return defaultVal;
  }
}

// use it like this
console.log(getSafe(() => obj.a.lot.of.properties));

// or add an optional default value
console.log(getSafe(() => obj.a.lot.of.properties, 'nothing'));
_x000D_
_x000D_
_x000D_

mkdir's "-p" option

mkdir [-switch] foldername

-p is a switch which is optional, it will create subfolder and parent folder as well even parent folder doesn't exist.

From the man page:

-p, --parents no error if existing, make parent directories as needed

Example:

mkdir -p storage/framework/{sessions,views,cache}

This will create subfolder sessions,views,cache inside framework folder irrespective of 'framework' was available earlier or not.

Correct way to quit a Qt program?

If you're using Qt Jambi, this should work:

QApplication.closeAllWindows();

How to generate javadoc comments in Android Studio

I can't find any shortcut to generate javadoc comments. But if you type /** before the method declaration and press Enter, the javadoc comment block will be generated automatically.

Read this for more information.

How to list imported modules?

import sys
sys.modules.keys()

An approximation of getting all imports for the current module only would be to inspect globals() for modules:

import types
def imports():
    for name, val in globals().items():
        if isinstance(val, types.ModuleType):
            yield val.__name__

This won't return local imports, or non-module imports like from x import y. Note that this returns val.__name__ so you get the original module name if you used import module as alias; yield name instead if you want the alias.

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

numba

For recursive calculations which are not vectorisable, numba, which uses JIT-compilation and works with lower level objects, often yields large performance improvements. You need only define a regular for loop and use the decorator @njit or (for older versions) @jit(nopython=True):

For a reasonable size dataframe, this gives a ~30x performance improvement versus a regular for loop:

from numba import jit

@jit(nopython=True)
def calculator_nb(a, b, d):
    res = np.empty(d.shape)
    res[0] = d[0]
    for i in range(1, res.shape[0]):
        res[i] = res[i-1] * a[i] + b[i]
    return res

df['C'] = calculator_nb(*df[list('ABD')].values.T)

n = 10**5
df = pd.concat([df]*n, ignore_index=True)

# benchmarking on Python 3.6.0, Pandas 0.19.2, NumPy 1.11.3, Numba 0.30.1
# calculator() is same as calculator_nb() but without @jit decorator
%timeit calculator_nb(*df[list('ABD')].values.T)  # 14.1 ms per loop
%timeit calculator(*df[list('ABD')].values.T)     # 444 ms per loop

How can I get screen resolution in java?

This is the resolution of the screen that the given component is currently assigned (something like most part of the root window is visible on that screen).

public Rectangle getCurrentScreenBounds(Component component) {
    return component.getGraphicsConfiguration().getBounds();
}

Usage:

Rectangle currentScreen = getCurrentScreenBounds(frameOrWhateverComponent);
int currentScreenWidth = currentScreen.width // current screen width
int currentScreenHeight = currentScreen.height // current screen height
// absolute coordinate of current screen > 0 if left of this screen are further screens
int xOfCurrentScreen = currentScreen.x

If you want to respect toolbars, etc. you'll need to calculate with this, too:

GraphicsConfiguration gc = component.getGraphicsConfiguration();
Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(gc);

What is aria-label and how should I use it?

Prerequisite:

Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control

Aria does not change anything visually. (Aria is scared of designers too).

aria-label

aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users

How To Use:

<input type="edit" aria-label="search" placeholder="search">

There is no visual change in application. But screen readers can understand the purpose of control

aria-labelledby

Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually

Approach 1:

<span id="sd">Search</span>

<input type="text" aria-labelledby="sd">

Approach 2:

aria-labelledby can also be used to combine two labels for screen reader users

<span id="de">Billing Address</span>

<span id="sd">First Name</span>

<input type="text" aria-labelledby="de sd">

How to create cross-domain request?

Many long (and correct) answers here. But usually you won't do these things manually - at least not when you set up your first projects for development (this is where you usually stumble upon these things). If you use koa for the backend: use koa-cors. Install via npm...

npm install --save koa-cors

...and use it in the code:

const cors = require('koa-cors');
const Koa = require('koa');
const app = new Koa();
app.use(cors());

problem solved.

Changing the resolution of a VNC session in linux

I'm not sure about linux, but under windows, tightvnc will detect and adapt to resolution changes on the server.

So you should be able to VNC into the workstation, do the equivalent of right-click on desktop, properties, set resolution to whatever, and have your client vnc window resize itself accordingly.

store and retrieve a class object in shared preference

Using Gson Library:

dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}

Store:

Gson gson = new Gson();
//Your json response object value store in json object
JSONObject jsonObject = response.getJSONObject();
//Convert json object to string
String json = gson.toJson(jsonObject);
//Store in the sharedpreference
getPrefs().setUserJson(json);

Retrieve:

String json = getPrefs().getUserJson();

Ajax request returns 200 OK, but an error event is fired instead of success

See this. Its also similar problem. Working i tried.

Dont remove dataType: 'JSON',

Note: echo only JSON Formate in PHP file if you use only php echo your ajax code return 200

YouTube API to fetch all videos on a channel

Using API version 2, which is deprecated, the URL for uploads (of channel UCqAEtEr0A0Eo2IVcuWBfB9g) is:

https://gdata.youtube.com/feeds/users/UCqAEtEr0A0Eo2IVcuWBfB9g/uploads

There is an API version 3.

How to backup MySQL database in PHP?

try this 100% working.

<?php
function dbbackup($host,$user,$pass,$name,$tables=false, $backup_name=false)
{ 
set_time_limit(3000); 
$mysqli = new mysqli($host,$user,$pass,$name); 
$mysqli->select_db($name); 
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES'); 
while($row = $queryTables->fetch_row()) 
{ 
    $target_tables[] = $row[0]; 
}   
if($tables !== false) 
{
    $target_tables = array_intersect( $target_tables, $tables); 
} 
$content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n--\r\n-- Database: `".$name."`\r\n--\r\n\r\n\r\n";
foreach($target_tables as $table)
{
    if (empty($table))
    {
        continue;
    } 
    $result = $mysqli->query('SELECT * FROM `'.$table.'`');     $fields_amount=$result->field_count;  $rows_num=$mysqli->affected_rows;     $res = $mysqli->query('SHOW CREATE TABLE '.$table); $TableMLine=$res->fetch_row(); 
    $content .= "\n\n".$TableMLine[1].";\n\n";   $TableMLine[1]=str_ireplace('CREATE TABLE `','CREATE TABLE IF NOT EXISTS `',$TableMLine[1]);
    for ($i = 0, $st_counter = 0; $i < $fields_amount;   $i++, $st_counter=0) 
    {
        while($row = $result->fetch_row())  
        {
            if ($st_counter%100 == 0 || $st_counter == 0 )  
            {
                $content .= "\nINSERT INTO ".$table." VALUES";
            }
            $content .= "\n(";    
            for($j=0; $j<$fields_amount; $j++)
            {
                $row[$j] = str_replace("\n","\\n", addslashes($row[$j]) ); 
                if (isset($row[$j]))
                {
                    $content .= '"'.$row[$j].'"' ;
                } 
                else
                {
                    $content .= '""';
                }
                if ($j<($fields_amount-1))
                {
                    $content.= ',';
                }  
            }
            $content .=")";
            if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) 
            {
                $content .= ";";
            }
            else
            {
                $content .= ",";
            }
            $st_counter=$st_counter+1;
        }
    } $content .="\n\n\n";
}
$content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
$backup_name = $backup_name ? $backup_name : $name.'___('.date('H-i-s').'_'.date('d-m-Y').').sql';
ob_get_clean(); 
header('Content-Type: application/octet-stream'); 
header("Content-Transfer-Encoding: Binary"); 
header('Content-Length: '. (function_exists('mb_strlen') ? mb_strlen($content, '8bit'): strlen($content)) );   
header("Content-disposition: attachment; filename=\"".$backup_name."\""); 
echo $content; exit;
}
dbbackup("host", "user", "password", "database" );
?>

check on github

DataAdapter.Fill(Dataset)

DataSet ds = new DataSet();

using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(query, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
    adapter.Fill(ds);
}

return ds;

How to open URL in Microsoft Edge from the command line?

Windows 10: Create a shortcut with this destination:

%windir%\system32\cmd.exe /c "start microsoft-edge:https://twitter.com"

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

Chrome refuses to execute an AJAX script due to wrong MIME type

For the record and Google search users, If you are a .NET Core developer, you should set the content-types manually, because their default value is null or empty:

var provider = new FileExtensionContentTypeProvider();
app.UseStaticFiles(new StaticFileOptions
{
    ContentTypeProvider = provider
});

Can't use Swift classes inside Objective-C

I use CocoaPods and the Swift class from my library couldn't be located from the Objective-C code in the example app because it's project and target were named the same as the library, so I had to remove the Objective-C Generated Interface Name values so they didn't conflict with the ones from the library.

How to host a Node.Js application in shared hosting

You can run node.js server on a typical shared hosting with Linux, Apache and PHP (LAMP). I have successfully installed it, even with NPM, Express and Grunt working fine. Follow the steps:

1) Create a new PHP file on the server with the following code and run it:

<?php
//Download and extract the latest node
exec('curl http://nodejs.org/dist/latest/node-v0.10.33-linux-x86.tar.gz | tar xz');
//Rename the folder for simplicity
exec('mv node-v0.10.33-linux-x86 node');

2) The same way install your node app, e.g. jt-js-sample, using npm:

<?php
exec('node/bin/npm install jt-js-sample');

3) Run the node app from PHP:

<?php
//Choose JS file to run
$file = 'node_modules/jt-js-sample/index.js';
//Spawn node server in the background and return its pid
$pid = exec('PORT=49999 node/bin/node ' . $file . ' >/dev/null 2>&1 & echo $!');
//Wait for node to start up
usleep(500000);
//Connect to node server using cURL
$curl = curl_init('http://127.0.0.1:49999/');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//Get the full response
$resp = curl_exec($curl);
if($resp === false) {
    //If couldn't connect, try increasing usleep
    echo 'Error: ' . curl_error($curl);
} else {
    //Split response headers and body
    list($head, $body) = explode("\r\n\r\n", $resp, 2);
    $headarr = explode("\n", $head);
    //Print headers
    foreach($headarr as $headval) {
        header($headval);
    }
    //Print body
    echo $body;
}
//Close connection
curl_close($curl);
//Close node server
exec('kill ' . $pid);

Voila! Have a look at the demo of a node app on PHP shared hosting.

EDIT: I started a Node.php project on GitHub.

Print DIV content by JQuery

I prefer this one, I have tested it and its working

https://github.com/jasonday/printThis

$("#mySelector").printThis();

or

$("#mySelector").printThis({
*      debug: false,              * show the iframe for debugging
*      importCSS: true,           * import page CSS
*      printContainer: true,      * grab outer container as well as the contents of the selector
*      loadCSS: "path/to/my.css", * path to additional css file
*      pageTitle: "",             * add title to print page
*      removeInline: false        * remove all inline styles from print elements
*  });

C# 4.0 optional out/ref arguments

What about like this?

public bool OptionalOutParamMethod([Optional] ref string pOutParam)
{
    return true;
}

You still have to pass a value to the parameter from C# but it is an optional ref param.

Jquery Ajax Posting json to webservice

I have encountered this one too and this is my solution.

If you are encountering an invalid json object exception when parsing data, even though you know that your json string is correct, stringify the data you received in your ajax code before parsing it to JSON:

$.post(CONTEXT+"servlet/capture",{
        yesTransactionId : yesTransactionId, 
        productOfferId : productOfferId
        },
        function(data){
            try{
                var trimData = $.trim(JSON.stringify(data));
                var obj      = $.parseJSON(trimData);
                if(obj.success == 'true'){ 
                    //some codes ...

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

Collections.synchronizedMap() method synchronizes all the methods of the HashMap and effectively reduces it to a data structure where one thread can enter at a time because it locks every method on a common lock.

In ConcurrentHashMap synchronization is done a little differently. Rather than locking every method on a common lock, ConcurrentHashMap uses separate lock for separate buckets thus locking only a portion of the Map. By default there are 16 buckets and also separate locks for separate buckets. So the default concurrency level is 16. That means theoretically any given time 16 threads can access ConcurrentHashMap if they all are going to separate buckets.

Way to go from recursion to iteration

One pattern to look for is a recursion call at the end of the function (so called tail-recursion). This can easily be replaced with a while. For example, the function foo:

void foo(Node* node)
{
    if(node == NULL)
       return;
    // Do something with node...
    foo(node->left);
    foo(node->right);
}

ends with a call to foo. This can be replaced with:

void foo(Node* node)
{
    while(node != NULL)
    {
        // Do something with node...
        foo(node->left);
        node = node->right;
     }
}

which eliminates the second recursive call.

Compare a date string to datetime in SQL Server?

Technique 2:

DECLARE @p_date DATETIME
SET     @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )

SELECT  *
FROM    table1
WHERE   DATEDIFF( d, column_datetime, @p_date ) = 0

If the column_datetime field is not indexed, and is unlikely to be (or the index is unlikely to be used) then using DATEDIFF() is shorter.

How to programmatically set drawableLeft on Android button?

as @Jérémy Reynaud pointing out, as described in this answer, the safest way to set the left drawable without changing the values of the other drawables (top, right, and bottom) is by using the previous values from the button with setCompoundDrawablesWithIntrinsicBounds:

Drawable leftDrawable = getContext().getResources()
                          .getDrawable(R.drawable.yourdrawable);

// Or use ContextCompat
// Drawable leftDrawable = ContextCompat.getDrawable(getContext(),
//                                        R.drawable.yourdrawable);

Drawable[] drawables = button.getCompoundDrawables();
button.setCompoundDrawablesWithIntrinsicBounds(leftDrawable,drawables[1],
                                               drawables[2], drawables[3]);

So all your previous drawable will be preserved.

How to easily initialize a list of Tuples?

One technique I think is a little easier and that hasn't been mentioned before here:

var asdf = new [] { 
    (Age: 1, Name: "cow"), 
    (Age: 2, Name: "bird")
}.ToList();

I think that's a little cleaner than:

var asdf = new List<Tuple<int, string>> { 
    (Age: 1, Name: "cow"), 
    (Age: 2, Name: "bird")
};

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can call a stored procedure from another stored procedure by using the EXECUTE command.

Say your procedure is X. Then in X you can use

EXECUTE PROCEDURE Y () RETURNING_VALUES RESULT;"

What are the main differences between JWT and OAuth authentication?

Firstly, we have to differentiate JWT and OAuth. Basically, JWT is a token format. OAuth is an authorization protocol that can use JWT as a token. OAuth uses server-side and client-side storage. If you want to do real logout you must go with OAuth2. Authentication with JWT token can not logout actually. Because you don't have an Authentication Server that keeps track of tokens. If you want to provide an API to 3rd party clients, you must use OAuth2 also. OAuth2 is very flexible. JWT implementation is very easy and does not take long to implement. If your application needs this sort of flexibility, you should go with OAuth2. But if you don't need this use-case scenario, implementing OAuth2 is a waste of time.

XSRF token is always sent to the client in every response header. It does not matter if a CSRF token is sent in a JWT token or not, because the CSRF token is secured with itself. Therefore sending CSRF token in JWT is unnecessary.

Applying CSS styles to all elements inside a DIV

If you're looking for a shortcut for writing out all of your selectors, then a CSS Preprocessor (Sass, LESS, Stylus, etc.) can do what you're looking for. However, the generated styles must be valid CSS.

Sass:

#applyCSS {
    .ui-bar-a {
       color: blue;
    }
    .ui-bar-a .ui-link-inherit {
       color: orange;
    }
    background: #CCC;
}

Generated CSS:

#applyCSS {
  background: #CCC;
}

#applyCSS .ui-bar-a {
  color: blue;
}

#applyCSS .ui-bar-a .ui-link-inherit {
  color: orange;
}

minimum double value in C/C++

A truly portable C++ solution

As from C++11 you can use numeric_limits<double>::lowest(). According to the standard, it returns exactly what you're looking for:

A finite value x such that there is no other finite value y where y < x.
Meaningful for all specializations in which is_bounded != false.

Online demo


Lots of non portable C++ answers here !

There are many answers going for -std::numeric_limits<double>::max().

Fortunately, they will work well in most of the cases. Floating point encoding schemes decompose a number in a mantissa and an exponent and most of them (e.g. the popular IEEE-754) use a distinct sign bit, which doesn't belong to the mantissa. This allows to transform the largest positive in the smallest negative just by flipping the sign:

enter image description here

Why aren't these portable ?

The standard doesn't impose any floating point standard.

I agree that my argument is a little bit theoretic, but suppose that some excentric compiler maker would use a revolutionary encoding scheme with a mantissa encoded in some variations of a two's complement. Two's complement encoding are not symmetric. for example for a signed 8 bit char the maximum positive is 127, but the minimum negative is -128. So we could imagine some floating point encoding show similar asymmetric behavior.

I'm not aware of any encoding scheme like that, but the point is that the standard doesn't guarantee that the sign flipping yields the intended result. So this popular answer (sorry guys !) can't be considered as fully portable standard solution ! /* at least not if you didn't assert that numeric_limits<double>::is_iec559 is true */

How to get overall CPU usage (e.g. 57%) on Linux

Take a look at cat /proc/stat

grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'

EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it's an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can "apt-get install" anything.

NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.

Current CPU usage can be potentially calculated with:

awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \
<(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)

Move_uploaded_file() function is not working

If you are on a windows machine, there won't be any problems with uploading or writing to the specified folder path, except the syntactical errors.

But in case of Linux users, there is a workaround to this problem, even if there are no syntactical errors visible.

First of all, I am assuming that you are using this in a Linux environment and you need to upload something to your project folder in the public directory.

Even if you are having the write and read access to the project folder, PHP is not handled by the end user. It is and can be handled by a www-data user, or group.

So in order to make this www-data get access first type in;

sudo chgrp "www-data" your_project_folder

once its done, if there is no write access to the following as well;

sudo chown g+w your_project_folder

That will do the trick in Linux.

Please, not that this is done in a Linux environment, with phpmyadmin, and mysql running.

Iterating over every property of an object in javascript using Prototype?

You should iterate over the keys and get the values using square brackets.

See: How do I enumerate the properties of a javascript object?

EDIT: Obviously, this makes the question a duplicate.

C++ convert string to hexadecimal and vice versa

As of C++17 there's also std::from_chars. The following function takes a string of hex characters and returns a vector of T:

#include <charconv>

template<typename T>
std::vector<T> hexstr_to_vec(const std::string& str, unsigned char chars_per_num = 2)
{
  std::vector<T> out(str.size() / chars_per_num, 0);

  T value;
  for (int i = 0; i < str.size() / chars_per_num; i++) {
    std::from_chars<T>(
      str.data() + (i * chars_per_num),
      str.data() + (i * chars_per_num) + chars_per_num,
      value,
      16
    );
    out[i] = value;
  }

  return out;
}

Call Python function from JavaScript code

All you need is to make an ajax request to your pythoncode. You can do this with jquery http://api.jquery.com/jQuery.ajax/, or use just javascript

$.ajax({
  type: "POST",
  url: "~/pythoncode.py",
  data: { param: text}
}).done(function( o ) {
   // do something
});

Efficiently getting all divisors of a given number

Here's my code:

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

#define pii pair<int, int>

#define MAX 46656
#define LMT 216
#define LEN 4830
#define RNG 100032

unsigned base[MAX / 64], segment[RNG / 64], primes[LEN];

#define sq(x) ((x)*(x))
#define mset(x,v) memset(x,v,sizeof(x))
#define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31)))
#define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31)))

// http://zobayer.blogspot.com/2009/09/segmented-sieve.html
void sieve()
{
    unsigned i, j, k;
    for (i = 3; i<LMT; i += 2)
        if (!chkC(base, i))
            for (j = i*i, k = i << 1; j<MAX; j += k)
                setC(base, j);
    primes[0] = 2;
    for (i = 3, j = 1; i<MAX; i += 2)
        if (!chkC(base, i))
            primes[j++] = i;
}


//http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/
vector <pii> factors;
void primeFactors(int num)
{
    int expo = 0;   
    for (int i = 0; primes[i] <= sqrt(num); i++)
    {
        expo = 0;
        int prime = primes[i];
        while (num % prime == 0){
            expo++;
            num = num / prime;
        }
        if (expo>0)
            factors.push_back(make_pair(prime, expo));
    }

    if ( num >= 2)
        factors.push_back(make_pair(num, 1));

}

vector <int> divisors;
void setDivisors(int n, int i) {
    int j, x, k;
    for (j = i; j<factors.size(); j++) {
        x = factors[j].first * n;
        for (k = 0; k<factors[j].second; k++) {
            divisors.push_back(x);
            setDivisors(x, j + 1);
            x *= factors[j].first;
        }
    }
}

int main() {

    sieve();
    int n, x, i; 
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> x;
        primeFactors(x);
        setDivisors(1, 0);
        divisors.push_back(1);
        sort(divisors.begin(), divisors.end());
        cout << divisors.size() << "\n";
        for (int j = 0; j < divisors.size(); j++) {
            cout << divisors[j] << " "; 
        }
        cout << "\n";
        divisors.clear();
        factors.clear();
    }
}

The first part, sieve() is used to find the prime numbers and put them in primes[] array. Follow the link to find more about that code (bitwise sieve).

The second part primeFactors(x) takes an integer (x) as input and finds out its prime factors and corresponding exponent, and puts them in vector factors[]. For example, primeFactors(12) will populate factors[] in this way:

factors[0].first=2, factors[0].second=2
factors[1].first=3, factors[1].second=1

as 12 = 2^2 * 3^1

The third part setDivisors() recursively calls itself to calculate all the divisors of x, using the vector factors[] and puts them in vector divisors[].

It can calculate divisors of any number which fits in int. Also it is quite fast.

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

I used to get the same problem, but solved it by pointing to the right jre used for the project.

Right click on the project properties java builpath see the jre selected edit it select alternate jre installed jre select the right one ok After changing right click on project>maven>update project

Hope it helps. Attaching screen shot.enter image description here

error_log per Virtual Host?

You can try:

    <VirtualHost myvhost:80>
       php_value error_log "/var/log/httpd/vhost_php_error_log"
    </Virtual Host>

But I'm not sure if it is going to work. I tried on my sites with no success.

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

For me it was a table name upper/lower case issue. I had to make sure that table case name matched in a delete query, table notifications was not the same as Notifications. I fixed it by matching table name case with query and what MySQLWorkbench reported.

What is wierd is that this error showed up in a worked sql statement. Don't know what caused this case sensitivity. Perhaps an auto AWS RDS update.

How to change heatmap.2 color range in R?

Here's another option for those not using heatmap.2 (aheatmap is good!)

Make a sequential vector of 100 values from min to max of your input matrix, find value closest to 0 in that, make two vector of colours to and from desired midpoint, combine and use them:

breaks <- seq(from=min(range(inputMatrix)), to=max(range(inputMatrix)), length.out=100)
midpoint <- which.min(abs(breaks - 0))
rampCol1 <- colorRampPalette(c("forestgreen", "darkgreen", "black"))(midpoint)
rampCol2 <- colorRampPalette(c("black", "darkred", "red"))(100-(midpoint+1))
rampCols <- c(rampCol1,rampCol2)

How to programmatically send a 404 response with Express/Node?

You don't have to simulate it. The second argument to res.send I believe is the status code. Just pass 404 to that argument.

Let me clarify that: Per the documentation on expressjs.org it seems as though any number passed to res.send() will be interpreted as the status code. So technically you could get away with:

res.send(404);

Edit: My bad, I meant res instead of req. It should be called on the response

Edit: As of Express 4, the send(status) method has been deprecated. If you're using Express 4 or later, use: res.sendStatus(404) instead. (Thanks @badcc for the tip in the comments)

How to add property to a class dynamically?

Extending the idea from kjfletch

# This is my humble contribution, extending the idea to serialize
# data from and to tuples, comparison operations and allowing functions
# as default values.

def Struct(*args, **kwargs):
    FUNCTIONS = (types.BuiltinFunctionType, types.BuiltinMethodType, \
                 types.FunctionType, types.MethodType)
    def init(self, *iargs, **ikwargs):
        """Asume that unamed args are placed in the same order than
        astuple() yields (currently alphabetic order)
        """
        kw = list(self.__slots__)

        # set the unnamed args
        for i in range(len(iargs)):
            k = kw.pop(0)
            setattr(self, k, iargs[i])

        # set the named args
        for k, v in ikwargs.items():
            setattr(self, k, v)
            kw.remove(k)

        # set default values
        for k in kw:
            v = kwargs[k]
            if isinstance(v, FUNCTIONS):
                v = v()
            setattr(self, k, v)

    def astuple(self):
        return tuple([getattr(self, k) for k in self.__slots__])

    def __str__(self):
        data = ['{}={}'.format(k, getattr(self, k)) for k in self.__slots__]
        return '<{}: {}>'.format(self.__class__.__name__, ', '.join(data))

    def __repr__(self):
        return str(self)

    def __eq__(self, other):
        return self.astuple() == other.astuple()

    name = kwargs.pop("__name__", "MyStruct")
    slots = list(args)
    slots.extend(kwargs.keys())
    # set non-specific default values to None
    kwargs.update(dict((k, None) for k in args))

    return type(name, (object,), {
        '__init__': init,
        '__slots__': tuple(slots),
        'astuple': astuple,
        '__str__': __str__,
        '__repr__': __repr__,
        '__eq__': __eq__,
    })


Event = Struct('user', 'cmd', \
               'arg1', 'arg2',  \
               date=time.time, \
               __name__='Event')

aa = Event('pepe', 77)
print(aa)
raw = aa.astuple()

bb = Event(*raw)
print(bb)

if aa == bb:
    print('Are equals')

cc = Event(cmd='foo')
print(cc)

Output:

<Event: user=pepe, cmd=77, arg1=None, arg2=None, date=1550051398.3651814>
<Event: user=pepe, cmd=77, arg1=None, arg2=None, date=1550051398.3651814>
Are equals
<Event: user=None, cmd=foo, arg1=None, arg2=None, date=1550051403.7938335>

How to add one column into existing SQL Table

What about something like:

Alter Table Products
Add LastUpdate varchar(200) null

Do you need something more complex than this?

Inserting an item in a Tuple

def tuple_insert(tup,pos,ele):
    tup = tup[:pos]+(ele,)+tup[pos:]
    return tup

tuple_insert(tup,pos,9999)

tup: tuple
pos: Position to insert
ele: Element to insert

Detect iPhone/iPad purely by css

You might want to try the solution from this O'Reilly article.

The important part are these CSS media queries:

<link rel="stylesheet" media="all and (max-device-width: 480px)" href="iphone.css"> 
<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait)" href="ipad-portrait.css"> 
<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape)" href="ipad-landscape.css"> 
<link rel="stylesheet" media="all and (min-device-width: 1025px)" href="ipad-landscape.css"> 

Submit a form using jQuery

I have also used the following to submit a form (without actually submitting it) via Ajax:

  jQuery.get("process_form.php"+$("#form_id").serialize(), {}, 
    function() {
      alert("Okay!"); 
    });

How do we check if a pointer is NULL pointer?

//Do this

int IS_NULL_PTR(char *k){
memset(&k, k, sizeof k);
if(k) { return 71; } ;
return 72;
}
int PRINT_PTR_SAFE(char *KR){
    char *E=KR;;
    if (IS_NULL_PTR(KR)==71){
        printf("%s\r\n",KR);
    } else {
        printf("%s","(null)\r\n");
    }
}
int main(int argc,char *argv[]){
    int i=0;
    char *A=malloc(sizeof(char)*9);
    ;strcpy(A,"hello world");
    for (i=((int)(A))-10;i<1e+40;i++){
        PRINT_PTR_SAFE(i);
    }

}
//Then watch the show!
//Edit as you wish. Just credit me if you really want more of this.

Curl error: Operation timed out

I got same problem lot of time. Check your request url, if you are requesting on local server like 127.1.1/api or 192.168...., try to change it, make sure you are hitting cloud.

Programmatically create a UIView with color gradient

What you are looking for is CAGradientLayer. Every UIView has a layer - into that layer you can add sublayers, just as you can add subviews. One specific type is the CAGradientLayer, where you give it an array of colors to gradiate between.

One example is this simple wrapper for a gradient view:

http://oleb.net/blog/2010/04/obgradientview-a-simple-uiview-wrapper-for-cagradientlayer/

Note that you need to include the QuartZCore framework in order to access all of the layer parts of a UIView.

Is it possible to have a default parameter for a mysql stored procedure?

If you look into CREATE PROCEDURE Syntax for latest MySQL version you'll see that procedure parameter can only contain IN/OUT/INOUT specifier, parameter name and type.

So, default values are still unavailable in latest MySQL version.

Error: «Could not load type MvcApplication»

I had the same issue and solved it with below steps

  1. Go to project properties
  2. On the "Build' tab, set output path to "bin\"

How to Insert Double or Single Quotes

If you save the Excel file as a CSV format file, you might find that the result is convenient to inserting into a database, though I'm not sure all of the fields would be quoted.

How to get file path in iPhone app

You need to add your tiles into your resource bundle. I mean add all those files to your project make sure to copy all files to project directory option checked.

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

The issue is with this line

 xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text

You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.

Hence replace this with

 xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text 

HTTP POST with URL query parameters -- good idea or not?

I would think it could still be quite RESTful to have query arguments that identify the resource on the URL while keeping the content payload confined to the POST body. This would seem to separate the considerations of "What am I sending?" versus "Who am I sending it to?".

Recursive directory listing in DOS

You can get the parameters you are asking for by typing:

dir /?

For the full list, try:

dir /s /b /a:d

Regular expression which matches a pattern, or is an empty string

An alternative would be to place your regexp in non-capturing parentheses. Then make that expression optional using the ? qualifier, which will look for 0 (i.e. empty string) or 1 instances of the non-captured group.

For example:

/(?: some regexp )?/

In your case the regular expression would look something like this:

/^(?:[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+)?$/

No | "or" operator necessary!

Here is the Mozilla documentation for JavaScript Regular Expression syntax.

Load image from url

UrlImageViewHelper will fill an ImageView with an image that is found at a URL. UrlImageViewHelper will automatically download, save, and cache all the image urls the BitmapDrawables. Duplicate urls will not be loaded into memory twice. Bitmap memory is managed by using a weak reference hash table, so as soon as the image is no longer used by you, it will be garbage collected automatically.

UrlImageViewHelper.setUrlDrawable(imageView, "http://example.com/image.png");

https://github.com/koush/UrlImageViewHelper

Finding square root without using sqrt function?

There is a better algorithm, which needs at most 6 iterations to converge to maximum precision for double numbers:

#include <math.h>

double sqrt(double x) {
    if (x <= 0)
        return 0;       // if negative number throw an exception?
    int exp = 0;
    x = frexp(x, &exp); // extract binary exponent from x
    if (exp & 1) {      // we want exponent to be even
        exp--;
        x *= 2;
    }
    double y = (1+x)/2; // first approximation
    double z = 0;
    while (y != z) {    // yes, we CAN compare doubles here!
        z = y;
        y = (y + x/y) / 2;
    }
    return ldexp(y, exp/2); // multiply answer by 2^(exp/2)
}

Algorithm starts with 1 as first approximation for square root value. Then, on each step, it improves next approximation by taking average between current value y and x/y. If y = sqrt(x), it will be the same. If y > sqrt(x), then x/y < sqrt(x) by about the same amount. In other words, it will converge very fast.

UPDATE: To speed up convergence on very large or very small numbers, changed sqrt() function to extract binary exponent and compute square root from number in [1, 4) range. It now needs frexp() from <math.h> to get binary exponent, but it is possible to get this exponent by extracting bits from IEEE-754 number format without using frexp().

SCP Permission denied (publickey). on EC2 only when using -r flag on directories

Even if above solutions don't work, check permissions to destination file of aws ec2 instance. May be you can try with- sudo chmod 777 -R destinationFolder/*

How to make phpstorm display line numbers by default?

In PHPStorm 2016: File > Settings > Editor > General > Appearance > check "Show line numbers"

How to check the extension of a filename in a bash script?

You can use the "file" command if you actually want to find out information about the file rather than rely on the extensions.

If you feel comfortable with using the extension you can use grep to see if it matches.

Java - What does "\n" mean?

In the specific case of the code example from the original question, the

System.out.print("\n");

is there to move to a new line between incrementing i.

So the first print statement prints all of the elements of Grid[0][j]. When the innermost for loop has completed, the "\n" gets printed and then all of the elements of Grid[1][j] are printed on the next line, and this is repeated until you have a 10x10 grid of the elements of the 2-dimensional array, Grid.

Android: adb: Permission Denied

According to adb help:

adb root                     - restarts the adbd daemon with root permissions

Which indeed resolved the issue for me.

Twitter Bootstrap and ASP.NET GridView

There are 2 steps to resolve this:

  1. Add UseAccessibleHeader="true" to Gridview tag:

    <asp:GridView ID="MyGridView" runat="server" UseAccessibleHeader="true">
    
  2. Add the following Code to the PreRender event:


Protected Sub MyGridView_PreRender(sender As Object, e As EventArgs) Handles MyGridView.PreRender
    Try
        MyGridView.HeaderRow.TableSection = TableRowSection.TableHeader
    Catch ex As Exception
    End Try
End Sub

Note setting Header Row in DataBound() works only when the object is databound, any other postback that doesn't databind the gridview will result in the gridview header row style reverting to a standard row again. PreRender works everytime, just make sure you have an error catch for when the gridview is empty.

Selecting fields from JSON output

Assume you stored that dictionary in a variable called values. To get id in to a variable, do:

idValue = values['criteria'][0]['id']

If that json is in a file, do the following to load it:

import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()

If that json is from a URL, do the following to load it:

import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''

ScalaTest in sbt: is there a way to run a single test without tags?

Here's the Scalatest page on using the runner and the extended discussion on the -t and -z options.

This post shows what commands work for a test file that uses FunSpec.

Here's the test file:

package com.github.mrpowers.scalatest.example

import org.scalatest.FunSpec

class CardiBSpec extends FunSpec {

  describe("realName") {

    it("returns her birth name") {
      assert(CardiB.realName() === "Belcalis Almanzar")
    }

  }

  describe("iLike") {

    it("works with a single argument") {
      assert(CardiB.iLike("dollars") === "I like dollars")
    }

    it("works with multiple arguments") {
      assert(CardiB.iLike("dollars", "diamonds") === "I like dollars, diamonds")
    }

    it("throws an error if an integer argument is supplied") {
      assertThrows[java.lang.IllegalArgumentException]{
        CardiB.iLike()
      }
    }

    it("does not compile with integer arguments") {
      assertDoesNotCompile("""CardiB.iLike(1, 2, 3)""")
    }

  }

}

This command runs the four tests in the iLike describe block (from the SBT command line):

testOnly *CardiBSpec -- -z iLike

You can also use quotation marks, so this will also work:

testOnly *CardiBSpec -- -z "iLike"

This will run a single test:

testOnly *CardiBSpec -- -z "works with multiple arguments"

This will run the two tests that start with "works with":

testOnly *CardiBSpec -- -z "works with"

I can't get the -t option to run any tests in the CardiBSpec file. This command doesn't run any tests:

testOnly *CardiBSpec -- -t "works with multiple arguments"

Looks like the -t option works when tests aren't nested in describe blocks. Let's take a look at another test file:

class CalculatorSpec extends FunSpec {
  it("adds two numbers") {
    assert(Calculator.addNumbers(3, 4) === 7)
  }
}

-t can be used to run the single test:

testOnly *CalculatorSpec -- -t "adds two numbers"

-z can also be used to run the single test:

testOnly *CalculatorSpec -- -z "adds two numbers"

See this repo if you'd like to run these examples. You can find more info on running tests here.

Center image horizontally within a div

Style.css

img#center-img{

 display: block;
 margin: auto;
}

Html

<html>
  <body>
    <div>
      <img src='pic.png' id='center-img'>
    </div>
  </body>
</html>

Artisan migrate could not find driver

I am a Windows and XAMPP user. What works for me is adding extension=php_pdo_mysql.dll in both php.ini of XAMPP and php.ini in C:\php\php.ini.

Run this command in your cmd to know where your config file is

php -i | find /i "Configuration File

Decreasing for loops in Python impossible?

Late to the party, but for anyone tasked with creating their own or wants to see how this would work, here's the function with an added bonus of rearranging the start-stop values based on the desired increment:

def RANGE(start, stop=None, increment=1):
    if stop is None:
        stop = start
        start = 1

    value_list = sorted([start, stop])

    if increment == 0:
        print('Error! Please enter nonzero increment value!')
    else:
        value_list = sorted([start, stop])
        if increment < 0:
            start = value_list[1]
            stop = value_list[0]
            while start >= stop:
                worker = start
                start += increment
                yield worker
        else:
            start = value_list[0]
            stop = value_list[1]
            while start < stop:
                worker = start
                start += increment
                yield worker

Negative increment:

for i in RANGE(1, 10, -1):
    print(i)

Or, with start-stop reversed:

for i in RANGE(10, 1, -1):
    print(i)

Output:

10
9
8
7
6
5
4
3
2
1

Regular increment:

for i in RANGE(1, 10):
    print(i)

Output:

1
2
3
4
5
6
7
8
9

Zero increment:

for i in RANGE(1, 10, 0):
    print(i)

Output:

'Error! Please enter nonzero increment value!'

Multiple lines of input in <input type="text" />

Check this:

The TEXTAREA element creates a multi-line text input control

Convert Iterator to ArrayList

use google guava !

Iterable<String> fieldsIterable = ...
List<String> fields = Lists.newArrayList(fieldsIterable);

++

Network usage top/htop on Linux

NetHogs is probably what you're looking for:

a small 'net top' tool. Instead of breaking the traffic down per protocol or per subnet, like most tools do, it groups bandwidth by process.

NetHogs does not rely on a special kernel module to be loaded. If there's suddenly a lot of network traffic, you can fire up NetHogs and immediately see which PID is causing this. This makes it easy to identify programs that have gone wild and are suddenly taking up your bandwidth.

Since NetHogs heavily relies on /proc, most features are only available on Linux. NetHogs can be built on Mac OS X and FreeBSD, but it will only show connections, not processes...

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

Doing Project -> Clean... fixed it for me.

My eclipse had stopped working so I cleaned workspace directory and after I run eclipse when I import the project I had this problem. Other solutions suggested here didn't work.

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

Try with this:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer_layout"
android:fitsSystemWindows="true">


<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!--Main layout and ads-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <FrameLayout
            android:id="@+id/ll_main_hero"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

        </FrameLayout>

        <FrameLayout
            android:id="@+id/ll_ads"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <View
                android:layout_width="320dp"
                android:layout_height="50dp"
                android:layout_gravity="center"
                android:background="#ff00ff" />
        </FrameLayout>


    </LinearLayout>

    <!--Toolbar-->
    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/toolbar"
        android:elevation="4dp" />
</FrameLayout>


<!--left-->
<ListView
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@null"
    android:background="@mipmap/layer_image"
    android:id="@+id/left_drawer"></ListView>

<!--right-->
<FrameLayout
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="right"
    android:background="@mipmap/layer_image">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/ken2"
        android:scaleType="centerCrop" />
</FrameLayout>

style :

<style name="ts_theme_overlay" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/red_A700</item>
    <item name="colorPrimaryDark">@color/red1</item>
    <item name="android:windowBackground">@color/blue_A400</item>
</style>

Main Activity extends ActionBarActivity

toolBar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolBar);

Now you can onCreateOptionsMenu like as normal ActionBar with ToolBar.

This is my Layout

  • TOP: Left Drawer - Right Drawer
    • MID: ToolBar (ActionBar)
    • BOTTOM: ListFragment

Hope you understand !have fun !

How to install XNA game studio on Visual Studio 2012?

Yes, it's possible with a bit of tweak. Unfortunately, you still have to have VS 2010 installed.

  1. First, install XNA Game Studio 4.0. The easiest way is to install the Windows Phone SDK 7.1 which contains everything required.

  2. Copy the XNA Game Extension from VS 10 to VS 11 by opening a command prompt 'as administrator' and executing the following (may vary if not x64 computer with defaults paths) :

    xcopy /e "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0" "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0"

  3. Run notepad as administrator then open extension.vsixmanifest in the destination directory just created.

  4. Upgrade the Supported product version to match the new version (or duplicate the whole VisualStudio element and change the Version attribute, as @brainslugs83 said in comments):

    <SupportedProducts>
      <VisualStudio Version="11.0">
        <Edition>VSTS</Edition>
        <Edition>VSTD</Edition>
        <Edition>Pro</Edition>
        <Edition>VCSExpress</Edition>
        <Edition>VPDExpress</Edition>
      </VisualStudio>
    </SupportedProducts>
    
  5. Don't forget to clear/delete your cache in %localappdata%\Microsoft\VisualStudio\12.0\Extensions.

  6. You may have to run the command to tells Visual Studio that new extensions are available. If you see an 'access denied' message, try launching the console as an administrator.

    "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe" /setup
    

This has been tested for Windows Games, but not WP7 or Xbox games.

[Edit] According Jowsty, this works also for XBox 360 Games.

[Edit for Visual Studio 2013 & Windows 8.1] See here for documentation on installing Windows Phone SDK 7.1 on Windows 8.1. Use VS version number 12.0 in place of 11.0 for all of these steps, and they will still work correctly.

Jquery submit form

You can try like:

   $("#myformid").submit(function(){
        //perform anythng
   });

Or even you can try like

$(".nextbutton").click(function() { 
    $('#form1').submit();
});

Why do I get a warning icon when I add a reference to an MEF plugin project?

Check NETFramework of the referred dll & the Project where you are adding the DLL. Ex: DLL ==> supportedRuntime version="v4.0" Project ==> supportedRuntime version="v3.0"

You will get warning icon. Solution : Make dll version consistence across.

Div Height in Percentage

It doesn't take the 50% of the whole page is because the "whole page" is only how tall your contents are. Change the enclosing html and body to 100% height and it will work.

html, body{
    height: 100%;
}
div{
    height: 50%;
}

http://jsfiddle.net/DerekL/5YukJ/1/

enter image description here

^ Your document is only 20px high. 50% of 20px is 10px, and it is not what you expected.

enter image description here

^ Now if you change the height of the document to the height of the whole page (150px), 50% of 150px is 75px, then it will work.

Combine two columns of text in pandas dataframe

Small data-sets (< 150rows)

[''.join(i) for i in zip(df["Year"].map(str),df["quarter"])]

or slightly slower but more compact:

df.Year.str.cat(df.quarter)

Larger data sets (> 150rows)

df['Year'].astype(str) + df['quarter']

UPDATE: Timing graph Pandas 0.23.4

enter image description here

Let's test it on 200K rows DF:

In [250]: df
Out[250]:
   Year quarter
0  2014      q1
1  2015      q2

In [251]: df = pd.concat([df] * 10**5)

In [252]: df.shape
Out[252]: (200000, 2)

UPDATE: new timings using Pandas 0.19.0

Timing without CPU/GPU optimization (sorted from fastest to slowest):

In [107]: %timeit df['Year'].astype(str) + df['quarter']
10 loops, best of 3: 131 ms per loop

In [106]: %timeit df['Year'].map(str) + df['quarter']
10 loops, best of 3: 161 ms per loop

In [108]: %timeit df.Year.str.cat(df.quarter)
10 loops, best of 3: 189 ms per loop

In [109]: %timeit df.loc[:, ['Year','quarter']].astype(str).sum(axis=1)
1 loop, best of 3: 567 ms per loop

In [110]: %timeit df[['Year','quarter']].astype(str).sum(axis=1)
1 loop, best of 3: 584 ms per loop

In [111]: %timeit df[['Year','quarter']].apply(lambda x : '{}{}'.format(x[0],x[1]), axis=1)
1 loop, best of 3: 24.7 s per loop

Timing using CPU/GPU optimization:

In [113]: %timeit df['Year'].astype(str) + df['quarter']
10 loops, best of 3: 53.3 ms per loop

In [114]: %timeit df['Year'].map(str) + df['quarter']
10 loops, best of 3: 65.5 ms per loop

In [115]: %timeit df.Year.str.cat(df.quarter)
10 loops, best of 3: 79.9 ms per loop

In [116]: %timeit df.loc[:, ['Year','quarter']].astype(str).sum(axis=1)
1 loop, best of 3: 230 ms per loop

In [117]: %timeit df[['Year','quarter']].astype(str).sum(axis=1)
1 loop, best of 3: 230 ms per loop

In [118]: %timeit df[['Year','quarter']].apply(lambda x : '{}{}'.format(x[0],x[1]), axis=1)
1 loop, best of 3: 9.38 s per loop

Answer contribution by @anton-vbr

CSS text-align not working

Change the rule on your <a> element from:

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
}?

to

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
    width:100%;
    text-align:center;
}?

Just add two new rules (width:100%; and text-align:center;). You need to make the anchor expand to take up the full width of the list item and then text-align center it.

jsFiddle example

String.contains in Java

Thinking of a string as a set of characters, in mathematics the empty set is always a subset of any set.

How to find file accessed/created just few minutes ago

To find files accessed 1, 2, or 3 minutes ago use -3

find . -cmin -3

Difference between Hashing a Password and Encrypting it

Encrypted vs Hashed Passwords

As shown in the above image, if the password is encrypted it is always a hidden secret where someone can extract the plain text password. However when password is hashed, you are relaxed as there is hardly any method of recovering the password from the hash value.


Extracted from Encrypted vs Hashed Passwords - Which is better?

Is encryption good?

Plain text passwords can be encrypted using symmetric encryption algorithms like DES, AES or with any other algorithms and be stored inside the database. At the authentication (confirming the identity with user name and password), application will decrypt the encrypted password stored in database and compare with user provided password for equality. In this type of an password handling approach, even if someone get access to database tables the passwords will not be simply reusable. However there is a bad news in this approach as well. If somehow someone obtain the cryptographic algorithm along with the key used by your application, he/she will be able to view all the user passwords stored in your database by decryption. "This is the best option I got", a software developer may scream, but is there a better way?

Cryptographic hash function (one-way-only)

Yes there is, may be you have missed the point here. Did you notice that there is no requirement to decrypt and compare? If there is one-way-only conversion approach where the password can be converted into some converted-word, but the reverse operation (generation of password from converted-word) is impossible. Now even if someone gets access to the database, there is no way that the passwords be reproduced or extracted using the converted-words. In this approach, there will be hardly anyway that some could know your users' top secret passwords; and this will protect the users using the same password across multiple applications. What algorithms can be used for this approach?

Using find command in bash script

If you want to loop over what you "find", you should use this:

find . -type f -name '*.*' -print0 | while IFS= read -r -d '' file; do
    printf '%s\n' "$file"
done

Source: https://askubuntu.com/questions/343727/filenames-with-spaces-breaking-for-loop-find-command

how to use python2.7 pip instead of default pip

as noted here, this is what worked best for me:

sudo apt-get install python3 python3-pip python3-setuptools

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10

PHP String to Float

$rootbeer = (float) $InvoicedUnits;

Should do it for you. Check out Type-Juggling. You should also read String conversion to Numbers.

Algorithm to return all combinations of k elements from n

Algorithm:

  • Count from 1 to 2^n.
  • Convert each digit to its binary representation.
  • Translate each 'on' bit to elements of your set, based on position.

In C#:

void Main()
{
    var set = new [] {"A", "B", "C", "D" }; //, "E", "F", "G", "H", "I", "J" };

    var kElement = 2;

    for(var i = 1; i < Math.Pow(2, set.Length); i++) {
        var result = Convert.ToString(i, 2).PadLeft(set.Length, '0');
        var cnt = Regex.Matches(Regex.Escape(result),  "1").Count; 
        if (cnt == kElement) {
            for(int j = 0; j < set.Length; j++)
                if ( Char.GetNumericValue(result[j]) == 1)
                    Console.Write(set[j]);
            Console.WriteLine();
        }
    }
}

Why does it work?

There is a bijection between the subsets of an n-element set and n-bit sequences.

That means we can figure out how many subsets there are by counting sequences.

e.g., the four element set below can be represented by {0,1} X {0, 1} X {0, 1} X {0, 1} (or 2^4) different sequences.

So - all we have to do is count from 1 to 2^n to find all the combinations. (We ignore the empty set.) Next, translate the digits to their binary representation. Then substitute elements of your set for 'on' bits.

If you want only k element results, only print when k bits are 'on'.

(If you want all subsets instead of k length subsets, remove the cnt/kElement part.)

(For proof, see MIT free courseware Mathematics for Computer Science, Lehman et al, section 11.2.2. https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/readings/ )

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

I was having this issue in a WebForms application, the error clearly says that A default document is not configured and it was true in my case, the default document was not configured. What worked for me is that I clicked on my site and on the middle pane in iis there is an option named Default Document. In the Default Document you have to check if the default page of the application exists or not.

The default page of my application was index.aspx and it wasnt present on iis Default Document window. So I made a new entry of index.aspx and it started working.

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

Had the same error but with a different scenario. I had my state as

        this.state = {
        date: new Date()
    }

so when I was asking it in my Class Component I had

p>Date = {this.state.date}</p>

Instead of

p>Date = {this.state.date.toLocaleDateString()}</p>

Update a submodule to the latest commit

Since git 1.8 you can do

git submodule update --remote --merge

This will update the submodule to the latest remote commit. You will then need to commit the change so the gitlink in the parent repository is updated

git commit

And then push the changes as without this, the SHA-1 identity the pointing to the submodule won't be updated and so the change won't be visible to anyone else.

Why use the params keyword?

No need to create overload methods, just use one single method with params as shown below

// Call params method with one to four integer constant parameters.
//
int sum0 = addTwoEach();
int sum1 = addTwoEach(1);
int sum2 = addTwoEach(1, 2);
int sum3 = addTwoEach(3, 3, 3);
int sum4 = addTwoEach(2, 2, 2, 2);

Export to csv in jQuery

Just try the following coding...very simple to generate CSV with the values of HTML Tables. No browser issues will come

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>        
        <script src="http://www.csvscript.com/dev/html5csv.js"></script>
<script>
$(document).ready(function() {

 $('table').each(function() {
    var $table = $(this);

    var $button = $("<button type='button'>");
    $button.text("Export to CSV");
    $button.insertAfter($table);

    $button.click(function() {     
         CSV.begin('table').download('Export.csv').go();
    });
  });  
})

</script>
    </head>
<body>
<div id='PrintDiv'>
<table style="width:100%">
  <tr>
    <td>Jill</td>
    <td>Smith</td>      
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>        
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>        
    <td>80</td>
  </tr>
</table>
</div>
</body>
</html>

How to Convert Int to Unsigned Byte and Back

Java 8 provides Byte.toUnsignedInt to convert byte to int by unsigned conversion. In Oracle's JDK this is simply implemented as return ((int) x) & 0xff; because HotSpot already understands how to optimize this pattern, but it could be intrinsified on other VMs. More importantly, no prior knowledge is needed to understand what a call to toUnsignedInt(foo) does.

In total, Java 8 provides methods to convert byte and short to unsigned int and long, and int to unsigned long. A method to convert byte to unsigned short was deliberately omitted because the JVM only provides arithmetic on int and long anyway.

To convert an int back to a byte, just use a cast: (byte)someInt. The resulting narrowing primitive conversion will discard all but the last 8 bits.

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

On Android >=6.0, We have to request permission runtime.

Step1: add in AndroidManifest.xml file

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Step2: Request permission.

int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);

if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
} else {
    //TODO
}

Step3: Handle callback when you request permission.

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_READ_PHONE_STATE:
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                //TODO
            }
            break;

        default:
            break;
    }
}

Edit: Read official guide here Requesting Permissions at Run Time

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

How to Get JSON Array Within JSON Object?

  Gson gson = new Gson();
                Type listType = new TypeToken<List<Data>>() {}.getType();
                List<Data>     cartProductList = gson.fromJson(response.body().get("data"), listType);
                Toast.makeText(getContext(), ""+cartProductList.get(0).getCity(), Toast.LENGTH_SHORT).show();

socket.emit() vs. socket.send()

TL;DR:

socket.send(data, callback) is essentially equivalent to calling socket.emit('message', JSON.stringify(data), callback)

Without looking at the source code, I would assume that the send function is more efficient edit: for sending string messages, at least?

So yeah basically emit allows you to send objects, which is very handy.

Take this example with socket.emit:

sendMessage: function(type, message) {
    socket.emit('message', {
        type: type,
        message: message
    });
}

and for those keeping score at home, here is what it looks like using socket.send:

sendMessage: function(type, message) {
    socket.send(JSON.stringify({
        type: type,
        message: message
    }));
}

What is the use of "object sender" and "EventArgs e" parameters?

EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.

Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.

Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx

Example:

protected void btn_Click (object sender, EventArgs e){
   Button btn = sender as Button;
   btn.Text = "clicked!";
}

Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked

Store List to session

Yes, you can store any object (I assume you are using ASP.NET with default settings, which is in-process session state):

Session["test"] = myList;

You should cast it back to the original type for use:

var list = (List<int>)Session["test"];
// list.Add(something);

As Richard points out, you should take extra care if you are using other session state modes (e.g. SQL Server) that require objects to be serializable.

Git push rejected "non-fast-forward"

I'm late to the party but I found some useful instructions in github help page and I wanted to share them here.

Sometimes, Git can't make your change to a remote repository without losing commits. When this happens, your push is refused.

If another person has pushed to the same branch as you, Git won't be able to push your changes:

$ git push origin master
To https://github.com/USERNAME/REPOSITORY.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/USERNAME/REPOSITORY.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.

You can fix this by fetching and merging the changes made on the remote branch with the changes that you have made locally:

$ git fetch origin
# Fetches updates made to an online repository
$ git merge origin YOUR_BRANCH_NAME
# Merges updates made online with your local work

Or, you can simply use git pull to perform both commands at once:

$ git pull origin YOUR_BRANCH_NAME
# Grabs online updates and merges them with your local work

How can I check whether a numpy array is empty or not?

You can always take a look at the .size attribute. It is defined as an integer, and is zero (0) when there are no elements in the array:

import numpy as np
a = np.array([])

if a.size == 0:
    # Do something when `a` is empty

Force drop mysql bypassing foreign key constraint

Drop database exist in all versions of MySQL. But if you want to keep the table structure, here is an idea

mysqldump --no-data --add-drop-database --add-drop-table -hHOSTNAME -uUSERNAME -p > dump.sql

This is a program, not a mysql command

Then, log into mysql and

source dump.sql;

jQuery ajax success error

Try to set response dataType property directly:

dataType: 'text'

and put

die(''); 

in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.

How to open this .DB file?

I don't think there is a way to tell which program to use from just the .db extension. It could even be an encrypted database which can't be opened. You can MS Access, or a sqlite manager.

Edit: Try to rename the file to .txt and open it with a text editor. The first couple of words in the file could tell you the DB Type.

If it is a SQLite database, it will start with "SQLite format 3"

How to prevent XSS with HTML/PHP?

In order of preference:

  1. If you are using a templating engine (e.g. Twig, Smarty, Blade), check that it offers context-sensitive escaping. I know from experience that Twig does. {{ var|e('html_attr') }}
  2. If you want to allow HTML, use HTML Purifier. Even if you think you only accept Markdown or ReStructuredText, you still want to purify the HTML these markup languages output.
  3. Otherwise, use htmlentities($var, ENT_QUOTES | ENT_HTML5, $charset) and make sure the rest of your document uses the same character set as $charset. In most cases, 'UTF-8' is the desired character set.

Also, make sure you escape on output, not on input.

How to do a SOAP wsdl web services call from the command line

On linux command line, you can simply execute:

curl -H "Content-Type: text/xml; charset=utf-8" -H "SOAPAction:"  -d @your_soap_request.xml -X POST https://ws.paymentech.net/PaymentechGateway

How do I call an Angular 2 pipe with multiple arguments?

I use Pipes in Angular 2+ to filter arrays of objects. The following takes multiple filter arguments but you can send just one if that suits your needs. Here is a StackBlitz Example. It will find the keys you want to filter by and then filters by the value you supply. It's actually quite simple, if it sounds complicated it's not, check out the StackBlitz Example.

Here is the Pipe being called in an *ngFor directive,

<div *ngFor='let item of items | filtermulti: [{title:"mr"},{last:"jacobs"}]' >
  Hello {{item.first}} !
</div>

Here is the Pipe,

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filtermulti'
})
export class FiltermultiPipe implements PipeTransform {
  transform(myobjects: Array<object>, args?: Array<object>): any {
    if (args && Array.isArray(myobjects)) {
      // copy all objects of original array into new array of objects
      var returnobjects = myobjects;
      // args are the compare oprators provided in the *ngFor directive
      args.forEach(function (filterobj) {
        let filterkey = Object.keys(filterobj)[0];
        let filtervalue = filterobj[filterkey];
        myobjects.forEach(function (objectToFilter) {
          if (objectToFilter[filterkey] != filtervalue && filtervalue != "") {
            // object didn't match a filter value so remove it from array via filter
            returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
          }
        })
      });
      // return new array of objects to *ngFor directive
      return returnobjects;
    }
  }
}

And here is the Component containing the object to filter,

import { Component } from '@angular/core';
import { FiltermultiPipe } from './pipes/filtermulti.pipe';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  items = [{ title: "mr", first: "john", last: "jones" }
   ,{ title: "mr", first: "adrian", last: "jacobs" }
   ,{ title: "mr", first: "lou", last: "jones" }
   ,{ title: "ms", first: "linda", last: "hamilton" }
  ];
}

StackBlitz Example

GitHub Example: Fork a working copy of this example here

*Please note that in an answer provided by Gunter, Gunter states that arrays are no longer used as filter interfaces but I searched the link he provides and found nothing speaking to that claim. Also, the StackBlitz example provided shows this code working as intended in Angular 6.1.9. It will work in Angular 2+.

Happy Coding :-)

How do I check two or more conditions in one <c:if>?

This look like a duplicate of JSTL conditional check.

The error is having the && outside the expression. Instead use

<c:if test="${ISAJAX == 0 && ISDATE == 0}">

How to install a python library manually

You need to install it in a directory in your home folder, and somehow manipulate the PYTHONPATH so that directory is included.

The best and easiest is to use virtualenv. But that requires installation, causing a catch 22. :) But check if virtualenv is installed. If it is installed you can do this:

$ cd /tmp
$ virtualenv foo
$ cd foo
$ ./bin/python

Then you can just run the installation as usual, with /tmp/foo/python setup.py install. (Obviously you need to make the virtual environment in your a folder in your home directory, not in /tmp/foo. ;) )

If there is no virtualenv, you can install your own local Python. But that may not be allowed either. Then you can install the package in a local directory for packages:

$ wget http://pypi.python.org/packages/source/s/six/six-1.0b1.tar.gz#md5=cbfcc64af1f27162a6a6b5510e262c9d
$ tar xvf six-1.0b1.tar.gz 
$ cd six-1.0b1/
$ pythonX.X setup.py   install --install-dir=/tmp/frotz

Now you need to add /tmp/frotz/pythonX.X/site-packages to your PYTHONPATH, and you should be up and running!

How to use comparison operators like >, =, < on BigDecimal

Use the compareTo method of BigDecimal :

public int compareTo(BigDecimal val) Compares this BigDecimal with the specified BigDecimal.

Returns:
-1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.

LISTAGG function: "result of string concatenation is too long"

A new feature added in 12cR2 is the ON OVERFLOW clause of LISTAGG. The query including this clause would look like:

SELECT pid, LISTAGG(Desc, ' ' ON OVERFLOW TRUNCATE ) WITHIN GROUP (ORDER BY seq) AS desc
FROM B GROUP BY pid;

The above will restrict the output to 4000 characters but will not throw the ORA-01489 error.

These are some of the additional options of ON OVERFLOW clause:

  • ON OVERFLOW TRUNCATE 'Contd..' : This will display 'Contd..' at the end of string (Default is ... )
  • ON OVERFLOW TRUNCATE '' : This will display the 4000 characters without any terminating string.
  • ON OVERFLOW TRUNCATE WITH COUNT : This will display the total number of characters at the end after the terminating characters. Eg:- '...(5512)'
  • ON OVERFLOW ERROR : If you expect the LISTAGG to fail with the ORA-01489 error ( Which is default anyway ).

LISTAGG Enhancements in 12c R2

How to create a directive with a dynamic template in AngularJS?

i've used the $templateCache to accomplish something similar. i put several ng-templates in a single html file, which i reference using the directive's templateUrl. that ensures the html is available to the template cache. then i can simply select by id to get the ng-template i want.

template.html:

<script type="text/ng-template" id=“foo”>
foo
</script>

<script type="text/ng-template" id=“bar”>
bar
</script>

directive:

myapp.directive(‘foobardirective’, ['$compile', '$templateCache', function ($compile, $templateCache) {

    var getTemplate = function(data) {
        // use data to determine which template to use
        var templateid = 'foo';
        var template = $templateCache.get(templateid);
        return template;
    }

    return {
        templateUrl: 'views/partials/template.html',
        scope: {data: '='},
        restrict: 'E',
        link: function(scope, element) {
            var template = getTemplate(scope.data);

            element.html(template);
            $compile(element.contents())(scope);
        }
    };
}]);

How to insert current datetime in postgresql insert query

timestamp (or date or time columns) do NOT have "a format".

Any formatting you see is applied by the SQL client you are using.


To insert the current time use current_timestamp as documented in the manual:

INSERT into "Group" (name,createddate) 
VALUES ('Test', current_timestamp);

To display that value in a different format change the configuration of your SQL client or format the value when SELECTing the data:

select name, to_char(createddate, ''yyyymmdd hh:mi:ss tt') as created_date
from "Group"

For psql (the default command line client) you can configure the display format through the configuration parameter DateStyle: https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-DATESTYLE

How to store decimal values in SQL Server?

The settings for Decimal are its precision and scale or in normal language, how many digits can a number have and how many digits do you want to have to the right of the decimal point.

So if you put PI into a Decimal(18,0) it will be recorded as 3?

If you put PI into a Decimal(18,2) it will be recorded as 3.14?

If you put PI into Decimal(18,10) be recorded as 3.1415926535.

How to add button tint programmatically

For ImageButton you can use:

favoriteImageButton.setColorFilter(Color.argb(255, 255, 255, 255)); // White Tint

CSS force image resize and keep aspect ratio

Remove the "height" property.

<img src="big_image.jpg" width="900" alt=""/>

By specifying both you are changing the aspect ratio of the image. Just setting one will resize but preserve the aspect ratio.

Optionally, to restrict oversizings:

<img src="big_image.jpg" width="900" alt="" style="max-width:500px; height:auto; max-height:600px;"/>

jQuery / Javascript code check, if not undefined

$.fn.attr(attributeName) returns the attribute value as string, or undefined when the attribute is not present.

Since "", and undefined are both falsy (evaluates to false when coerced to boolean) values in JavaScript, in this case I would write the check as below:

if (wlocation) { ... }

Mockito test a void method throws an exception

The parentheses are poorly placed.

You need to use:

doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
                                          ^

and NOT use:

doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
                                                                   ^

This is explained in the documentation

How can I make a SQL temp table with primary key and auto-incrementing field?

If you're just doing some quick and dirty temporary work, you can also skip typing out an explicit CREATE TABLE statement and just make the temp table with a SELECT...INTO and include an Identity field in the select list.

select IDENTITY(int, 1, 1) as ROW_ID,
       Name
into #tmp
from (select 'Bob' as Name union all
      select 'Susan' as Name union all
      select 'Alice' as Name) some_data

select *
from #tmp

What does `set -x` do?

set -x enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.

set +x disables it.

Running Python in PowerShell?

The default execution policy, "Restricted", prevents all scripts from running, including scripts that you write on the local computer.

The execution policy is saved in the registry, so you need to change it only once on each computer.

To change the execution policy, use the following procedure:

  1. Start Windows PowerShell with the "Run as administrator" option.

  2. At the command prompt, type:

    Set-ExecutionPolicy AllSigned

    -or-

    Set-ExecutionPolicy RemoteSigned

The change is effective immediately.

To run a script, type the full name and the full path to the script file.

For example, to run the Get-ServiceLog.ps1 script in the C:\Scripts directory, type:

C:\Scripts\Get-ServiceLog.ps1

And to the Python file, you have two points. Try to add your Python folder to your PATH and the extension .py.

To PATHEXT from go properties of computer. Then click on advanced system protection. Then environment variable. Here you will find the two points.

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

Even though the question is too old, but I would like to share the solution that worked for me because I already checked everything when it comes to this error. It was a pain, I spent two days trying and at the end the solution was:

update the M2e plugin in eclipse

clean and build again

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

How to concatenate two layers in keras?

You're getting the error because result defined as Sequential() is just a container for the model and you have not defined an input for it.

Given what you're trying to build set result to take the third input x3.

first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))

second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))

third = Sequential()
# of course you must provide the input to result which will be your x3
third.add(Dense(1, input_shape=(1,), activation='sigmoid'))

# lets say you add a few more layers to first and second.
# concatenate them
merged = Concatenate([first, second])

# then concatenate the two outputs

result = Concatenate([merged,  third])

ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)

result.compile(optimizer=ada_grad, loss='binary_crossentropy',
               metrics=['accuracy'])

However, my preferred way of building a model that has this type of input structure would be to use the functional api.

Here is an implementation of your requirements to get you started:

from keras.models import Model
from keras.layers import Concatenate, Dense, LSTM, Input, concatenate
from keras.optimizers import Adagrad

first_input = Input(shape=(2, ))
first_dense = Dense(1, )(first_input)

second_input = Input(shape=(2, ))
second_dense = Dense(1, )(second_input)

merge_one = concatenate([first_dense, second_dense])

third_input = Input(shape=(1, ))
merge_two = concatenate([merge_one, third_input])

model = Model(inputs=[first_input, second_input, third_input], outputs=merge_two)
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
model.compile(optimizer=ada_grad, loss='binary_crossentropy',
               metrics=['accuracy'])

To answer the question in the comments:

  1. How are result and merged connected? Assuming you mean how are they concatenated.

Concatenation works like this:

  a        b         c
a b c   g h i    a b c g h i
d e f   j k l    d e f j k l

i.e rows are just joined.

  1. Now, x1 is input to first, x2 is input into second and x3 input into third.

Passing just a type as a parameter in C#

foo.GetColumnValues(dm.mainColumn, typeof(int));
foo.GetColumnValues(dm.mainColumn, typeof(string));

Or using generics:

foo.GetColumnValues<int>(dm.mainColumn);
foo.GetColumnValues<string>(dm.mainColumn);

How to escape % in String.Format?

To complement the previous stated solution, use:

str = str.replace("%", "%%");

"replace" function examples

If you look at the function (by typing it's name at the console) you will see that it is just a simple functionalized version of the [<- function which is described at ?"[". [ is a rather basic function to R so you would be well-advised to look at that page for further details. Especially important is learning that the index argument (the second argument in replace can be logical, numeric or character classed values. Recycling will occur when there are differing lengths of the second and third arguments:

You should "read" the function call as" "within the first argument, use the second argument as an index for placing the values of the third argument into the first":

> replace( 1:20, 10:15, 1:2)
 [1]  1  2  3  4  5  6  7  8  9  1  2  1  2  1  2 16 17 18 19 20

Character indexing for a named vector:

> replace(c(a=1, b=2, c=3, d=4), "b", 10)
 a  b  c  d 
 1 10  3  4 

Logical indexing:

> replace(x <- c(a=1, b=2, c=3, d=4), x>2, 10)
 a  b  c  d 
 1  2 10 10 

Merge DLL into EXE?

I Found The Solution Below are the Stpes:-

  1. Download ILMerge.msi and Install it on your Machine.
  2. Open Command Prompt
  3. type cd C:\Program Files (x86)\Microsoft\ILMerge Preess Enter
  4. C:\Program Files (x86)\Microsoft\ILMerge>ILMerge.exe /target:winexe /targetplatform:"v4,C:\Windows\Microsoft.NET\Framework\v4.0.30319" /out:NewExeName.exe SourceExeName.exe DllName.dll

For Multiple Dll :-

C:\Program Files (x86)\Microsoft\ILMerge>ILMerge.exe /target:winexe /targetplatform:"v4,C:\Windows\Microsoft.NET\Framework\v4.0.30319" /out:NewExeName.exe SourceExeName.exe DllName1.dll DllName2.dll DllName3.dll

GitHub authentication failing over https, returning wrong email address

Just incase this helps anyone else also, I was signed into the mac app, command line working fine, but because I then turned on 2FA, my commands were returning the error. I had to sign out of the app, then I could use my Personal access token in my commands as per ele's answer here.

Hopefully that helps someone!

webpack: Module not found: Error: Can't resolve (with relative path)

Just ran into this... I have a common library shared among multiple transpiled products. I was using symlinks with brunch to handle sharing things between the projects. When moving to webpack, this stopped working.

What did get things working was using webpack configuration to turn off symlink resolving.

i.e. adding this in webpack.config.js:

module.exports = {
  //...
  resolve: {
    symlinks: false
  }
};

as documented here:

https://webpack.js.org/configuration/resolve/#resolvesymlinks

How to save a figure in MATLAB from the command line?

When using the saveas function the resolution isn't as good as when manually saving the figure with File-->Save As..., It's more recommended to use hgexport instead, as follows:

hgexport(gcf, 'figure1.jpg', hgexport('factorystyle'), 'Format', 'jpeg');

This will do exactly as manually saving the figure.

source: http://www.mathworks.com/support/solutions/en/data/1-1PT49C/index.html?product=SL&solution=1-1PT49C

What's wrong with foreign keys?

I always thought it was lazy not to use them. I was taught it should always be done. But then, I didnt listen to Joel's discussion. He may have had a good reason, I don't know.

How do I create a message box with "Yes", "No" choices and a DialogResult?

Try this:

if (MessageBox.Show("Are you sure", "Title_here", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
    Do something here for 'Yes'...
}

Can I use tcpdump to get HTTP requests, response header and response body?

There are tcpdump filters for HTTP GET & HTTP POST (or for both plus message body):

  • Run man tcpdump | less -Ip examples to see some examples

  • Here’s a tcpdump filter for HTTP GET (GET = 0x47, 0x45, 0x54, 0x20):

    sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'
    
  • Here’s a tcpdump filter for HTTP POST (POST = 0x50, 0x4f, 0x53, 0x54):

    sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'
    
  • Monitor HTTP traffic including request and response headers and message body (source):

    tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    tcpdump -X -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    

For more information on the bit-twiddling in the TCP header see: String-Matching Capture Filter Generator (link to Sake Blok's explanation).

Java Regex to Validate Full Name allow only Spaces and Letters

To validate for only letters and spaces, try this

String name1_exp = "^[a-zA-Z]+[\-'\s]?[a-zA-Z ]+$";

Named capturing groups in JavaScript regex?

Another possible solution: create an object containing the group names and indexes.

var regex = new RegExp("(.*) (.*)");
var regexGroups = { FirstName: 1, LastName: 2 };

Then, use the object keys to reference the groups:

var m = regex.exec("John Smith");
var f = m[regexGroups.FirstName];

This improves the readability/quality of the code using the results of the regex, but not the readability of the regex itself.

How to create a dump with Oracle PL/SQL Developer?

Export (or datapump if you have 10g/11g) is the way to do it. Why not ask how to fix your problems with that rather than trying to find another way to do it?

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

Use the Take(int n) method:

var q = query.Take(10);

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

I could do this with a custom attribute as follows.

[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
    //...
    return View();
}

Custom Attribute class as follows.

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB

        return privilegeLevels.Contains(this.AccessLevel);           
    }
}

You can redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        { 
                            controller = "Error", 
                            action = "Unauthorised" 
                        })
                );
}

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

The event is probably raised before the elements are fully loaded or the references are still unset, hence the exceptions. Try only setting properties if the reference is not null and IsLoaded is true.

What is the "assert" function?

There are three main reasons for using the assert() function over the normal if else and printf

  1. assert() function is mainly used in the debugging phase, it is tedious to write if else with a printf statement everytime you want to test a condition which might not even make its way in the final code.

  2. In large software deployments , assert comes very handy where you can make the compiler ignore the assert statements using the NDEBUG macro defined before linking the header file for assert() function.

  3. assert() comes handy when you are designing a function or some code and want to get an idea as to what limits the code will and not work and finally include an if else for evaluating it basically playing with assumptions.

What, why or when it is better to choose cshtml vs aspx?

As other people have answered, .cshtml (or .vbhtml if that's your flavor) provides a handler-mapping to load the MVC engine. The .aspx extension simply loads the aspnet_isapi.dll that performs the compile and serves up web forms. The difference in the handler mapping is simply a method of allowing the two to co-exist on the same server allowing both MVC applications and WebForms applications to live under a common root.

This allows http://www.mydomain.com/MyMVCApplication to be valid and served with MVC rules along with http://www.mydomain.com/MyWebFormsApplication to be valid as a standard web form.

Edit:
As for the difference in the technologies, the MVC (Razor) templating framework is intended to return .Net pages to a more RESTful "web-based" platform of templated views separating the code logic between the model (business/data objects), the view (what the user sees) and the controllers (the connection between the two). The WebForms model (aspx) was an attempt by Microsoft to use complex javascript embedding to simulate a more stateful application similar to a WinForms application complete with events and a page lifecycle that would be capable of retaining its own state from page to page.

The choice to use one or the other is always going to be a contentious one because there are arguments for and against both systems. I for one like the simplicity in the MVC architecture (though routing is anything but simple) and the ease of the Razor syntax. I feel the WebForms architecture is just too heavy to be an effective web platform. That being said, there are a lot of instances where the WebForms framework provides a very succinct and usable model with a rich event structure that is well defined. It all boils down to the needs of the application and the preferences of those building it.

Cannot connect to Database server (mysql workbench)

Try opening services.msc from the start menu search box and try manually starting the MySQL service or directly write services.msc in Run box

How do I replace whitespaces with underscore?

I'm using the following piece of code for my friendly urls:

from unicodedata import normalize
from re import sub

def slugify(title):
    name = normalize('NFKD', title).encode('ascii', 'ignore').replace(' ', '-').lower()
    #remove `other` characters
    name = sub('[^a-zA-Z0-9_-]', '', name)
    #nomalize dashes
    name = sub('-+', '-', name)

    return name

It works fine with unicode characters as well.

Object Required Error in excel VBA

The Set statement is only used for object variables (like Range, Cell or Worksheet in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer. You can find a good explanation for when to use set here.

The other problem is, that your variable g1val isn't actually declared as Integer, but has the type Variant. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant. You can only shorten your Dim statement this way:

Dim intColumn As Integer, intRow As Integer  'This creates two integers

For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.

Try this example to understand the difference:

Sub Dimming()

  Dim thisBecomesVariant, thisIsAnInteger As Integer
  Dim integerOne As Integer, integerTwo As Integer

  MsgBox TypeName(thisBecomesVariant)  'Will display "Empty"
  MsgBox TypeName(thisIsAnInteger )  'Will display "Integer"
  MsgBox TypeName(integerOne )  'Will display "Integer"
  MsgBox TypeName(integerTwo )  'Will display "Integer"

  'By assigning an Integer value to a Variant it becomes Integer, too
  thisBecomesVariant = 0
  MsgBox TypeName(thisBecomesVariant)  'Will display "Integer"

End Sub

Two further notices on your code:

First remark: Instead of writing

'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
  g1val = g1val   'Don't change g1val
Else
  g1val = Cells(33, i).Value  'Otherwise set g1val to the cell's value
End If

you could simply write

'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
  g1val = Cells(33, i).Value  'Set g1val to the cell's value 
End If

Since you don't want to change g1val in the other case.

Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.

Use YAML with variables

Rails / ruby frameworks are able to do some templating ... it's frequently used to load env variables ...

# fooz.yml
  foo:
    bar: <%= $ENV[:some_var] %>

No idea if this works for javascript frameworks as I think that YML format is superset of json and it depends on what reads the yml file for you.

If you can use the template like that or the << >> or the {{ }} styles depending on your reader, after that you just ...

In another yml file ...

# boo.yml

development:
  fooz: foo

Which allows you to basically insert a variable as your reference that original file each time which is dynamically set. When reading I was also seeing you can create or open YML files as objects on the fly for several languages which allows you to create a file & chain write a series of YML files or just have them all statically pointing to the dynamically created one.

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

I tried with and it works

use mysql; # use mysql table
update user set authentication_string="" where User='root'; 

flush privileges;
quit;

Extend contigency table with proportions (percentages)

Here is another example using the lapply and table functions in base R.

freqList = lapply(select_if(tips, is.factor), 
              function(x) {
                  df = data.frame(table(x))

                  df = data.frame(fct = df[, 1], 
                                  n = sapply(df[, 2], function(y) {
                                      round(y / nrow(dat), 2)
                                    }
                                )
                            )
                  return(df) 
                    }
                )

Use print(freqList) to see the proportion tables (percent of frequencies) for each column/feature/variable (depending on your tradecraft) that is labeled as a factor.

How to print struct variables in console?

To print the name of the fields in a struct:

fmt.Printf("%+v\n", yourProject)

From the fmt package:

when printing structs, the plus flag (%+v) adds field names

That supposes you have an instance of Project (in 'yourProject')

The article JSON and Go will give more details on how to retrieve the values from a JSON struct.


This Go by example page provides another technique:

type Response2 struct {
  Page   int      `json:"page"`
  Fruits []string `json:"fruits"`
}

res2D := &Response2{
    Page:   1,
    Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))

That would print:

{"page":1,"fruits":["apple","peach","pear"]}

If you don't have any instance, then you need to use reflection to display the name of the field of a given struct, as in this example.

type T struct {
    A int
    B string
}

t := T{23, "skidoo"}
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()

for i := 0; i < s.NumField(); i++ {
    f := s.Field(i)
    fmt.Printf("%d: %s %s = %v\n", i,
        typeOfT.Field(i).Name, f.Type(), f.Interface())
}

How to change current Theme at runtime in Android

i got the same problem but i found the solution.

public class EditTextSmartPhoneActivity extends Activity implements DialogInterface.OnClickListener
{
    public final static int CREATE_DIALOG  = -1;
    public final static int THEME_HOLO_LIGHT  = 0;
    public final static int THEME_BLACK  = 1;

    int position;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        position = getIntent().getIntExtra("position", -1);

        switch(position)
        {
        case CREATE_DIALOG:
            createDialog();
            break;
        case THEME_HOLO_LIGHT:
            setTheme(android.R.style.Theme_Holo_Light);
            break;
        case THEME_BLACK:
            setTheme(android.R.style.Theme_Black);
            break;
        default:
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

    }

    private void createDialog()
    {
        /** Options for user to select*/
        String choose[] = {"Theme_Holo_Light","Theme_Black"};

        AlertDialog.Builder b = new AlertDialog.Builder(this);

        /** Setting a title for the window */
        b.setTitle("Choose your Application Theme");

        /** Setting items to the alert dialog */
        b.setSingleChoiceItems(choose, 0, null);

        /** Setting a positive button and its listener */
        b.setPositiveButton("OK",this);

        /** Setting a positive button and its listener */
        b.setNegativeButton("Cancel", null);

        /** Creating the alert dialog window using the builder class */
        AlertDialog d = b.create();

        /** show dialog*/
        d.show();
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
        AlertDialog alert = (AlertDialog)dialog;
        int position = alert.getListView().getCheckedItemPosition();

        finish();
        Intent intent = new Intent(this, EditTextSmartPhoneActivity.class);
        intent.putExtra("position", position);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}

PHP import Excel into database (xls & xlsx)

If you save the excel file as a CSV file then you can import it into a mysql database using tools such as PHPMyAdmin

Im not sure if this would help in your situation, but a csv file either manually or programatically would be a lot easier to parse into a database than an excel file I would have thought.

EDIT: I would however suggest looking at the other answers rather than mine since @diEcho answer seems more appropriate.

How to use format() on a moment.js duration?

var diff = moment(end).unix() - moment(start).unix();
moment.utc(moment.duration(diff).asMilliseconds()).format("HH:mm:ss.SSS");

MySQL Select all columns from one table and some from another table

Using alias for referencing the tables to get the columns from different tables after joining them.

Select tb1.*, tb2.col1, tb2.col2 from table1 tb1 JOIN table2 tb2 on tb1.Id = tb2.Id

position fixed header in html

set #container div top to zero

#container{ 


 top: 0;



}

Import pfx file into particular certificate store from command line

To anyone else looking for this, I wasn't able to use certutil -importpfx into a specific store, and I didn't want to download the importpfx tool supplied by jaspernygaard's answer in order to avoid the requirement of copying the file to a large number of servers. I ended up finding my answer in a powershell script shown here.

The code uses System.Security.Cryptography.X509Certificates to import the certificate and then moves it into the desired store:

function Import-PfxCertificate { 

    param([String]$certPath,[String]$certRootStore = “localmachine”,[String]$certStore = “My”,$pfxPass = $null) 
    $pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 

    if ($pfxPass -eq $null) 
    {
        $pfxPass = read-host "Password" -assecurestring
    } 

    $pfx.import($certPath,$pfxPass,"Exportable,PersistKeySet") 

    $store = new-object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore) 
    $store.open("MaxAllowed") 
    $store.add($pfx) 
    $store.close() 
}

HTML inside Twitter Bootstrap popover

you can use attribute data-html="true":

<a href="#" id="example"  rel="popover" 
    data-content="<div>This <b>is</b> your div content</div>" 
    data-html="true" data-original-title="A Title">popover</a>

Where to change default pdf page width and font size in jspdf.debug.js?

Besides using one of the default formats you can specify any size you want in the unit you specify.

For example:

// Document of 210mm wide and 297mm high
new jsPDF('p', 'mm', [297, 210]);
// Document of 297mm wide and 210mm high
new jsPDF('l', 'mm', [297, 210]);
// Document of 5 inch width and 3 inch high
new jsPDF('l', 'in', [3, 5]);

The 3rd parameter of the constructor can take an array of the dimensions. However they do not correspond to width and height, instead they are long side and short side (or flipped around).

Your 1st parameter (landscape or portrait) determines what becomes the width and the height.

In the sourcecode on GitHub you can see the supported units (relative proportions to pt), and you can also see the default page formats (with their sizes in pt).

Get webpage contents with Python?

A solution with works with Python 2.X and Python 3.X:

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

url = 'http://hiscore.runescape.com/index_lite.ws?player=zezima'
response = urlopen(url)
data = str(response.read())

How many threads is too many?

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

How to run a javascript function during a mouseover on a div

Here's a jQuery solution.

<script type="text/javascript" src="/path/to/your/copy/of/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#sub1").mouseover(function() {
        $("#welcome").toggle();
    });
});
</script>

Using this markup:

<div id="sub1">some text</div>
<div id="welcome" style="display:none;">Welcome message</div>

You didn't really specify if (or when) you wanted to hide the welcome message, but this would toggle hiding or showing each time you moused over the text.

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

Another easy way of solving this error is right clicking in the console and click on Terminate/Disconnect All. Afterwards run the application it should work fine.

What is "String args[]"? parameter in main method Java

I would break up

public static void main(String args[])

in parts.

"public" means that main() can be called from anywhere.

"static" means that main() doesn't belong to a specific object

"void" means that main() returns no value

"main" is the name of a function. main() is special because it is the start of the program.

"String[]" means an array of String.

"args" is the name of the String[] (within the body of main()). "args" is not special; you could name it anything else and the program would work the same.

  • String[] args is a collection of Strings, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.

OpenJDK8 for windows

Go to this link

Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download

Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.

JDK vs OpenJDK

Returning a pointer to a vector element in c++

Returning &iterator will return the address of the iterator. If you want to return a way of referring to the element return the iterator itself.

Beware that you do not need the vector to be a global in order to return the iterator/pointer, but that operations in the vector can invalidate the iterator. Adding elements to the vector, for example, can move the vector elements to a different position if the new size() is greater than the reserved memory. Deletion of an element before the given item from the vector will make the iterator refer to a different element.

In both cases, depending on the STL implementation it can be hard to debug with just random errors happening each so often.

EDIT after comment: 'yes, I didn't want to return the iterator a) because its const, and b) surely it is only a local, temporary iterator? – Krakkos'

Iterators are not more or less local or temporary than any other variable and they are copyable. You can return it and the compiler will make the copy for you as it will with the pointer.

Now with the const-ness. If the caller wants to perform modifications through the returned element (whether pointer or iterator) then you should use a non-const iterator. (Just remove the 'const_' from the definition of the iterator).