Programs & Examples On #Inputverifier

Press Keyboard keys using a batch file

Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?

If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--

My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.

You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.

The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.

edit: Just to help you get started you can look here:

  1. Automate tasks with Windows Script Host's SendKeys method
  2. A useful thread about SendKeys

grep a file, but show several surrounding lines?

$ grep thestring thefile -5

-5 gets you 5 lines above and below the match 'thestring' is equivalent to -C 5 or -A 5 -B 5.

Android Studio says "cannot resolve symbol" but project compiles

It happened to me when I removed the whole files in .gradle/caches, then studio downloaded the dependences. The dependences not showed in the External Libraries but I can build App successfully. rebuild clean Invalidate and Restart have no effect. I solved the problem by the steps:

  • Close Android Studio completely
  • Remove .idea package in your project
  • Restart Android Studio

Regex select all text between tags

You shouldn't be trying to parse html with regexes see this question and how it turned out.

In the simplest terms, html is not a regular language so you can't fully parse is with regular expressions.

Having said that you can parse subsets of html when there are no similar tags nested. So as long as anything between and is not that tag itself, this will work:

preg_match("/<([\w]+)[^>]*>(.*?)<\/\1>/", $subject, $matches);
$matches = array ( [0] => full matched string [1] => tag name [2] => tag content )

A better idea is to use a parser, like the native DOMDocument, to load your html, then select your tag and get the inner html which might look something like this:

$obj = new DOMDocument();
$obj -> load($html);
$obj -> getElementByTagName('el');
$value = $obj -> nodeValue();

And since this is a proper parser it will be able to handle nesting tags etc.

Attach (open) mdf file database with SQL Server Management Studio

You may need to repair your mdf file first using some tools. There are lot of tool available in the market. There is tool called SQL Database Recovery Tool Repairs which is very useful to repair the mdf files.

The issue might me because of corrupted transaction logs, you may use tool SQL Database Recovery Tool Repairs to repair your corrupted mdf file.

How to get current route in react-router 2.0.0-rc5

If you use the history,then Router put everything into the location from the history,such as:

this.props.location.pathname;
this.props.location.query;

get it?

'Conda' is not recognized as internal or external command

I was faced with the same issue in windows 10, Updating the environment variable following steps, it's working fine.

I know It is a lengthy answer for the simple environment setups, I thought it's may be useful for the new window 10 users.

1) Open Anaconda Prompt:

enter image description here

2) Check Conda Installed Location.

where conda

enter image description here

3) Open Advanced System Settings

enter image description here

4) Click on Environment Variables

enter image description here

5) Edit Path

enter image description here

6) Add New Path

 C:\Users\RajaRama\Anaconda3\Scripts

 C:\Users\RajaRama\Anaconda3

 C:\Users\RajaRama\Anaconda3\Library\bin

enter image description here

7) Open Command Prompt and Check Versions

8) After 7th step type conda install anaconda-navigator in cmd then press y

enter image description here

How to find a Java Memory Leak

Well, there's always the low tech solution of adding logging of the size of your maps when you modify them, then search the logs for which maps are growing beyond a reasonable size.

Create view with primary key?

I got the error "The table/view 'dbo.vMyView' does not have a primary key defined" after I created a view in SQL server query designer. I solved the problem by using ISNULL on a column to force entity framework to use it as a primary key. You might have to restart visual studio to get the warnings to go away.

CREATE VIEW [dbo].[vMyView]
AS
SELECT ISNULL(Id, -1) AS IdPrimaryKey, Name
FROM  dbo.MyTable

What does 'git blame' do?

The git blame command is used to know who/which commit is responsible for the latest changes made to a file. The author/commit of each line can also been seen.

git blame filename (commits responsible for changes for all lines in code)

git blame filename -L 0,10 (commits responsible for changes from line "0" to line "10")

There are many other options for blame, but generally these could help.

Full width image with fixed height

If you want to have same ratio you should create a container and hide a part of the image.

_x000D_
_x000D_
.container{_x000D_
  width:100%;_x000D_
  height:60px;_x000D_
  overflow:hidden;_x000D_
}_x000D_
.img {_x000D_
  width:100%;_x000D_
}
_x000D_
<div class="container">_x000D_
  <img src="http://placehold.it/100x100" class="img" alt="Our Location" /> _x000D_
</div>_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

How to check if a variable is an integer or a string?

Depending on your definition of shortly, you could use one of the following options:

How much data / information can we save / store in a QR code?

See this table.

A 101x101 QR code, with high level error correction, can hold 3248 bits, or 406 bytes. Probably not enough for any meaningful SVG/XML data.

A 177x177 grid, depending on desired level of error correction, can store between 1273 and 2953 bytes. Maybe enough to store something small.

enter image description here

Changing the browser zoom level

Try if this works for you. This works on FF, IE8+ and chrome. The else part applies for non-firefox browsers. Though this gives you a zoom effect, it does not actually modify the zoom value at browser level.

    var currFFZoom = 1;
    var currIEZoom = 100;

    $('#plusBtn').on('click',function(){
        if ($.browser.mozilla){
            var step = 0.02;
            currFFZoom += step; 
            $('body').css('MozTransform','scale(' + currFFZoom + ')');
        } else {
            var step = 2;
            currIEZoom += step;
            $('body').css('zoom', ' ' + currIEZoom + '%');
        }
    });

    $('#minusBtn').on('click',function(){
        if ($.browser.mozilla){
            var step = 0.02;
            currFFZoom -= step;                 
            $('body').css('MozTransform','scale(' + currFFZoom + ')');

        } else {
            var step = 2;
            currIEZoom -= step;
            $('body').css('zoom', ' ' + currIEZoom + '%');
        }
    });

HTML/CSS--Creating a banner/header

Height is missing a p from its value.

Should be height:200*p*x

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

This works in Bootstrap 3 and improves dubbe and flynfish 's 2 top answers by integrating GarciaWebDev 's answer as well (which allows for url parameters after the hash and is straight from Bootstrap authors on the github issue tracker):

// Javascript to enable link to tab
var hash = document.location.hash;
var prefix = "tab_";

if (hash) {
    hash = hash.replace(prefix,'');
    var hashPieces = hash.split('?');
    activeTab = $('.nav-tabs a[href=' + hashPieces[0] + ']');
    activeTab && activeTab.tab('show');
} 

// Change hash for page-reload
$('.nav-tabs a').on('shown', function (e) {
    window.location.hash = e.target.hash.replace("#", "#" + prefix);
});

Oracle date "Between" Query

As APC rightly pointed out, your start_date column appears to be a TIMESTAMP but it could be a TIMESTAMP WITH LOCAL TIMEZONE or TIMESTAMP WITH TIMEZONE datatype too. These could well influence any queries you were doing on the data if your database server was in a different timezone to yourself. However, let's keep this simple and assume you are in the same timezone as your server. First, to give you the confidence, check that the start_date is a TIMESTAMP data type.

Use the SQLPlus DESCRIBE command (or the equivalent in your IDE) to verify this column is a TIMESTAMP data type.

eg

DESCRIBE mytable

Should report :

Name        Null? Type
----------- ----- ------------
NAME              VARHAR2(20) 
START_DATE        TIMESTAMP

If it is reported as a Type = TIMESTAMP then you can query your date ranges with simplest TO_TIMESTAMP date conversion, one which requires no argument (or picture).

We use TO_TIMESTAMP to ensure that any index on the START_DATE column is considered by the optimizer. APC's answer also noted that a function based index could have been created on this column and that would influence the SQL predicate but we cannot comment on that in this query. If you want to know how to find out what indexes have been applied to table, post another question and we can answer that separately.

So, assuming there is an index on start_date, which is a TIMESTAMP datatype and you want the optimizer to consider it, your SQL would be :

select * from mytable where start_date between to_timestamp('15-JAN-10') AND to_timestamp('17-JAN-10')+.9999999

+.999999999 is very close to but isn't quite 1 so the conversion of 17-JAN-10 will be as close to midnight on that day as possible, therefore you query returns both rows.

The database will see the BETWEEN as from 15-JAN-10 00:00:00:0000000 to 17-JAN-10 23:59:59:99999 and will therefore include all dates from 15th,16th and 17th Jan 2010 whatever the time component of the timestamp.

Hope that helps.

Dazzer

How to install APK from PC?

  1. Connect Android device to PC via USB cable and turn on USB storage.
  2. Copy .apk file to attached device's storage.
  3. Turn off USB storage and disconnect it from PC.
  4. Check the option Settings ? Applications ? Unknown sources OR Settings > Security > Unknown Sources.
  5. Open FileManager app and click on the copied .apk file. If you can't fine the apk file try searching or allowing hidden files. It will ask you whether to install this app or not. Click Yes or OK.

This procedure works even if ADB is not available.

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

The database must have a name (example DB1), try this one:

OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit"); 

In case the TNS is not defined you can also try this one:

OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
User Id=fastecit;Password=fastecit"); 

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

Mercurial undo last commit

In the current version of TortoiseHg Workbench 4.4.1 (07.2018) you can use Repository - Rollback/undo...:
enter image description here

Why do we check up to the square root of a prime number to determine if it is prime?

It's all really just basic uses of Factorization and Square Roots.

It may appear to be abstract, but in reality it simply lies with the fact that a non-prime-number's maximum possible factorial would have to be its square root because:

sqrroot(n) * sqrroot(n) = n.

Given that, if any whole number above 1 and below or up to sqrroot(n) divides evenly into n, then n cannot be a prime number.

Pseudo-code example:

i = 2;

is_prime = true;

while loop (i <= sqrroot(n))
{
  if (n % i == 0)
  {
    is_prime = false;
    exit while;
  }
  ++i;
}

How to get option text value using AngularJS?

Also you can do like this:

<select class="form-control postType" ng-model="selectedProd">
    <option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>

where "selectedProd" will be selected product.

Laravel Unknown Column 'updated_at'

For those who are using laravel 5 or above must use public modifier other wise it will throw an exception

Access level to App\yourModelName::$timestamps must be
public (as in class Illuminate\Database\Eloquent\Model)

public $timestamps = false;

Magento addFieldToFilter: Two fields, match as OR, not AND

Thanks Anda, your post has been a great help!! However the OR sentence didnt' quite work for me and I was getting an error: getCollection() "invalid argument supplied for foreach".

So this is what I ended with (notice the attribute being specified 3 times instead of 2 in this case):

  $collection->addFieldToFilter('attribute', array(  
    array('attribute'=>'my_field1','eq'=>'my_value1'),            
    array('attribute'=>'my_field2','eq'=>'my_value2') ));

addFieldToFilter first requires a field and then condition -> link.

Rewrite URL after redirecting 404 error htaccess

Put this code in your .htaccess file

RewriteEngine On
ErrorDocument 404 /404.php

where 404.php is the file name and placed at root. You can put full path over here.

jQuery DataTables Getting selected row values

You can iterate over the row data

$('#button').click(function () {
    var ids = $.map(table.rows('.selected').data(), function (item) {
        return item[0]
    });
    console.log(ids)
    alert(table.rows('.selected').data().length + ' row(s) selected');
});

Demo: Fiddle

How to see the CREATE VIEW code for a view in PostgreSQL?

These is a little thing to point out.
Using the function pg_get_viewdef or pg_views or information_schema.views you will always get a rewrited version of your original DDL.
The rewited version may or not be the same as your originl DDL script.

If the Rule Manager rewrite your view definition your original DLL will be lost and you will able to read the only the rewrited version of your view definition.
Not all views are rewrited but if you use sub-select or joins probably your views will be rewrited.

What is the difference between a port and a socket?

Socket is an abstraction provided by kernel to user applications for data I/O. A socket type is defined by the protocol its handling, an IPC communication etc. So if somebody creates a TCP socket he can do manipulations like reading data to socket and writing data to it by simple methods and the lower level protocol handling like TCP conversions and forwarding packets to lower level network protocols is done by the particular socket implementation in the kernel. The advantage is that user need not worry about handling protocol specific nitigrities and should just read and write data to socket like a normal buffer. Same is true in case of IPC, user just reads and writes data to socket and kernel handles all lower level details based on the type of socket created.

Port together with IP is like providing an address to the socket, though its not necessary, but it helps in network communications.

iOS 7's blurred overlay effect using CSS?

Check this one out http://codepen.io/GianlucaGuarini/pen/Hzrhf Seems like it does the effect without duplication the background image of the element under itself. See texts are blurring also in the example.

Vague.js

var vague = $blurred.find('iframe').Vague({
  intensity:5 //blur intensity
});
vague.blur();

Rotate image with javascript

You use a combination of CSS's transform (with vendor prefixes as necessary) and transform-origin, like this: (also on jsFiddle)

_x000D_
_x000D_
var angle = 0,_x000D_
  img = document.getElementById('container');_x000D_
document.getElementById('button').onclick = function() {_x000D_
  angle = (angle + 90) % 360;_x000D_
  img.className = "rotate" + angle;_x000D_
}
_x000D_
#container {_x000D_
  width: 820px;_x000D_
  height: 100px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
#container.rotate90,_x000D_
#container.rotate270 {_x000D_
  width: 100px;_x000D_
  height: 820px_x000D_
}_x000D_
#image {_x000D_
  transform-origin: top left;_x000D_
  /* IE 10+, Firefox, etc. */_x000D_
  -webkit-transform-origin: top left;_x000D_
  /* Chrome */_x000D_
  -ms-transform-origin: top left;_x000D_
  /* IE 9 */_x000D_
}_x000D_
#container.rotate90 #image {_x000D_
  transform: rotate(90deg) translateY(-100%);_x000D_
  -webkit-transform: rotate(90deg) translateY(-100%);_x000D_
  -ms-transform: rotate(90deg) translateY(-100%);_x000D_
}_x000D_
#container.rotate180 #image {_x000D_
  transform: rotate(180deg) translate(-100%, -100%);_x000D_
  -webkit-transform: rotate(180deg) translate(-100%, -100%);_x000D_
  -ms-transform: rotate(180deg) translateX(-100%, -100%);_x000D_
}_x000D_
#container.rotate270 #image {_x000D_
  transform: rotate(270deg) translateX(-100%);_x000D_
  -webkit-transform: rotate(270deg) translateX(-100%);_x000D_
  -ms-transform: rotate(270deg) translateX(-100%);_x000D_
}
_x000D_
<button id="button">Click me!</button>_x000D_
<div id="container">_x000D_
  <img src="http://i.stack.imgur.com/zbLrE.png" id="image" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

A 'for' loop to iterate over an enum in Java

You can do this as follows:

for (Direction direction : EnumSet.allOf(Direction.class)) {
  // do stuff
}

Node.js global proxy setting

You can try my package node-global-proxy which work with all node versions and most of http-client (axios, got, superagent, request etc.)

after install by

npm install node-global-proxy --save

a global proxy can start by

const proxy = require("node-global-proxy").default;

proxy.setConfig({
  http: "http://localhost:1080",
  https: "https://localhost:1080",
});
proxy.start();

/** Proxy working now! */

More information available here: https://github.com/wwwzbwcom/node-global-proxy

How to wrap async function calls into a sync function in Node.js or Javascript?

You shouldn't be looking at what happens around the call that creates the fiber but rather at what happens inside the fiber. Once you are inside the fiber you can program in sync style. For example:

function f1() {
    console.log('wait... ' + new Date);
    sleep(1000);
    console.log('ok... ' + new Date);   
}

function f2() {
    f1();
    f1();
}

Fiber(function() {
    f2();
}).run();

Inside the fiber you call f1, f2 and sleep as if they were sync.

In a typical web application, you will create the Fiber in your HTTP request dispatcher. Once you've done that you can write all your request handling logic in sync style, even if it calls async functions (fs, databases, etc.).

"The semaphore timeout period has expired" error for USB connection

I had a similar problem which I solved by changing the Port Settings in the port driver (located in Ports in device manager) to fit the device I was using.

For me it was that wrong Bits per second value was set.

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

Recursively look for files with a specific extension

  1. There's a { missing after browsefolders ()
  2. All $in should be $suffix
  3. The line with cut gets you only the middle part of front.middle.extension. You should read up your shell manual on ${varname%%pattern} and friends.

I assume you do this as an exercise in shell scripting, otherwise the find solution already proposed is the way to go.

To check for proper shell syntax, without running a script, use sh -n scriptname.

MySQL Join Where Not Exists

I'd use a 'where not exists' -- exactly as you suggest in your title:

SELECT `voter`.`ID`, `voter`.`Last_Name`, `voter`.`First_Name`,
       `voter`.`Middle_Name`, `voter`.`Age`, `voter`.`Sex`,
       `voter`.`Party`, `voter`.`Demo`, `voter`.`PV`,
       `household`.`Address`, `household`.`City`, `household`.`Zip`
FROM (`voter`)
JOIN `household` ON `voter`.`House_ID`=`household`.`id`
WHERE `CT` = '5'
AND `Precnum` = 'CTY3'
AND  `Last_Name`  LIKE '%Cumbee%'
AND  `First_Name`  LIKE '%John%'

AND NOT EXISTS (
  SELECT * FROM `elimination`
   WHERE `elimination`.`voter_id` = `voter`.`ID`
)

ORDER BY `Last_Name` ASC
LIMIT 30

That may be marginally faster than doing a left join (of course, depending on your indexes, cardinality of your tables, etc), and is almost certainly much faster than using IN.

HTML display result in text (input) field?

Do you really want the result to come up in an input box? If not, consider a table with borders set to other than transparent and use

document.getElementById('sum').innerHTML = sum;

How to Toggle a div's visibility by using a button click

jQuery would be the easiest way if you want to use it, but this should work.

function showHide(){
    var e = document.getElementById('e');

    if ( e.style.display !== 'none' ) {
        e.style.display = 'none';
    } else {
        e.style.display = '';
    }
}

java: ArrayList - how can I check if an index exists?

a simple way to do this:

try {
  list.get( index ); 
} 
catch ( IndexOutOfBoundsException e ) {
  if(list.isEmpty() || index >= list.size()){
    // Adding new item to list.
  }
}

How to use JavaScript regex over multiple lines?

Now there's the s (single line) modifier, that lets the dot matches new lines as well :) \s will also match new lines :D

Just add the s behind the slash

 /<pre.*?<\/pre>/gms

How can I get a list of repositories 'apt-get' is checking?

It seems the closest is:

apt-cache policy

SSIS how to set connection string dynamically from a config file

First add a variable to your SSIS package (Package Scope) - I used FileName, OleRootFilePath, OleProperties, OleProvider. The type for each variable is "string". Then I create a Configuration file (Select each variable - value) - populate the values in the configuration file - Eg: for OleProperties - Microsoft.ACE.OLEDB.12.0; for OleProperties - Excel 8.0;HDR=, OleRootFilePath - Your Excel file path, FileName - FileName

In the Connection manager - I then set the Properties-> Expressions-> Connection string expression dynamically eg:

"Provider=" + @[User::OleProvider] + "Data Source=" + @[User::OleRootFilePath]
+ @[User::FileName]  + ";Extended Properties=\"" + @[User::OleProperties] + "NO \""+";"

This way once you set the variables values and change it in your configuration file - the connection string will change dynamically - this helps especially in moving from development to production environments.

How to create an empty file with Ansible?

Something like this (using the stat module first to gather data about it and then filtering using a conditional) should work:

- stat: path=/etc/nologin
  register: p

- name: create fake 'nologin' shell
  file: path=/etc/nologin state=touch owner=root group=sys mode=0555
  when: p.stat.exists is defined and not p.stat.exists

You might alternatively be able to leverage the changed_when functionality.

Download files from SFTP with SSH.NET library

A simple working code to download a file with SSH.NET library is:

using (Stream fileStream = File.Create(@"C:\target\local\path\file.zip"))
{
    sftp.DownloadFile("/source/remote/path/file.zip", fileStream);
}

See also Downloading a directory using SSH.NET SFTP in C#.


To explain, why your code does not work:

The second parameter of SftpClient.DownloadFile is a stream to write a downloaded contents to.

You are passing in a read stream instead of a write stream. And moreover the path you are opening read stream with is a remote path, what cannot work with File class operating on local files only.

Just discard the File.OpenRead line and use a result of previous File.OpenWrite call instead (that you are not using at all now):

Stream file1 = File.OpenWrite(localFileName);

sftp.DownloadFile(file.FullName, file1);

Or even better, use File.Create to discard any previous contents that the local file may have.

I'm not sure if your localFileName is supposed to hold full path, or just file name. So you may need to add a path too, if necessary (combine localFileName with sDir?)

Are global variables bad?

In web applications within an enterprize can be used for holding session/window/thread/user specific data on the server for reasons of optimization and to preserve against loss of work where connection are unstable. As mentioned, race conditions need to be handled. We use a single instance of a class for this information and it is carefully managed.

Which HTTP methods match up to which CRUD methods?

The Symfony project tries to keep its HTTP methods joined up with CRUD methods, and their list associates them as follows:

  • GET Retrieve the resource from the server
  • POST Create a resource on the server
  • PUT Update the resource on the server
  • DELETE Delete the resource from the server

It's worth noting that, as they say on that page, "In reality, many modern browsers don't support the PUT and DELETE methods."

From what I remember, Symfony "fakes" PUT and DELETE for those browsers that don't support them when generating its forms, in order to try to be as close to using the theoretically-correct HTTP method even when a browser doesn't support it.

Submitting form and pass data to controller method of type FileStreamResult

here the problem is model binding if you specify a class then the model binding can understand it during the post if it an integer or string then you have to specify the [FromBody] to bind it properly.

make the following changes in FormMethod

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post, new { id = @item.JobId })){

}

and inside your home controller for binding the string you should specify [FromBody]

using System.Web.Http;
[HttpPost]
public FileStreamResult myMethod([FromBody]string id)
{
     // Set a local variable with the incoming data
     string str = id;

}

FromBody is available in System.Web.Http. make sure you have the reference to that class and added it in the cs file.

Apache error: _default_ virtualhost overlap on port 443

I ran into this problem because I had multiple wildcard entries for the same ports. You can easily check this by executing apache2ctl -S:

# apache2ctl -S
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 30000, the first has precedence
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 20001, the first has precedence
VirtualHost configuration:
11.22.33.44:80       is a NameVirtualHost
         default server xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
         port 80 namevhost xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
         [...]
11.22.33.44:443      is a NameVirtualHost
         default server yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
         port 443 namevhost yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
wildcard NameVirtualHosts and _default_ servers:
*:80                   hostname.com (/etc/apache2/sites-enabled/000-default:1)
*:20001                hostname.com (/etc/apache2/sites-enabled/000-default:33)
*:30000                hostname.com (/etc/apache2/sites-enabled/000-default:57)
_default_:443          hostname.com (/etc/apache2/sites-enabled/default-ssl:2)
*:20001                hostname.com (/etc/apache2/sites-enabled/default-ssl:163)
*:30000                hostname.com (/etc/apache2/sites-enabled/default-ssl:178)
Syntax OK

Notice how at the beginning of the output are a couple of warning lines. These will indicate which ports are creating the problems (however you probably already knew that).

Next, look at the end of the output and you can see exactly which files and lines the virtualhosts are defined that are creating the problem. In the above example, port 20001 is assigned both in /etc/apache2/sites-enabled/000-default on line 33 and /etc/apache2/sites-enabled/default-ssl on line 163. Likewise *:30000 is listed in 2 places. The solution (in my case) was simply to delete one of the entries.

Permutations between two lists of unequal length

Answering the question "given two lists, find all possible permutations of pairs of one item from each list" and using basic Python functionality (i.e., without itertools) and, hence, making it easy to replicate for other programming languages:

def rec(a, b, ll, size):
    ret = []
    for i,e in enumerate(a):
        for j,f in enumerate(b):
            l = [e+f]
            new_l = rec(a[i+1:], b[:j]+b[j+1:], ll, size)
            if not new_l:
                ret.append(l)
            for k in new_l:
                l_k = l + k
                ret.append(l_k)
                if len(l_k) == size:
                    ll.append(l_k)
    return ret

a = ['a','b','c']
b = ['1','2']
ll = []
rec(a,b,ll, min(len(a),len(b)))
print(ll)

Returns

[['a1', 'b2'], ['a1', 'c2'], ['a2', 'b1'], ['a2', 'c1'], ['b1', 'c2'], ['b2', 'c1']]

Jquery asp.net Button Click Event via ajax

I like Gromer's answer, but it leaves me with a question: What if I have multiple 'btnAwesome's in different controls?

To cater for that possibility, I would do the following:

$(document).ready(function() {
  $('#<%=myButton.ClientID %>').click(function() {
    // Do client side button click stuff here.
  });
});

It's not a regex match, but in my opinion, a regex match isn't what's needed here. If you're referencing a particular button, you want a precise text match such as this.

If, however, you want to do the same action for every btnAwesome, then go with Gromer's answer.

Laravel blade check empty foreach

Using following code, one can first check variable is set or not using @isset of laravel directive and then check that array is blank or not using @unless of laravel directive

@if(@isset($names))
    @unless($names)
        Array has no value
    @else
        Array has value

        @foreach($names as $name)
            {{$name}}
        @endforeach

    @endunless
@else
    Not defined
@endif

Python - Check If Word Is In A String

If you want to find out whether a whole word is in a space-separated list of words, simply use:

def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False

This elegant method is also the fastest. Compared to Hugh Bothwell's and daSong's approaches:

>python -m timeit -s "def contains_word(s, w): return (' ' + w + ' ') in (' ' + s + ' ')" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 0.351 usec per loop

>python -m timeit -s "import re" -s "def contains_word(s, w): return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search(s)" "contains_word('the quick brown fox', 'brown')"
100000 loops, best of 3: 2.38 usec per loop

>python -m timeit -s "def contains_word(s, w): return s.startswith(w + ' ') or s.endswith(' ' + w) or s.find(' ' + w + ' ') != -1" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 1.13 usec per loop

Edit: A slight variant on this idea for Python 3.6+, equally fast:

def contains_word(s, w):
    return f' {w} ' in f' {s} '

What's the difference between align-content and align-items?

according to what I understood from here:

when you use align-item or justify-item, you are adjusting "the content inside a grid item along the column axis or row axis respectively.

But: if you use align-content or justify-content, you are setting the position a grid along the column axis or the row axis. it occurs when you have a grid in a bigger container and width or height are inflexible (using px).

Setting Icon for wpf application (VS 08)

@742's answer works pretty well, but as outlined in the comments when running from the VS debugger the generic icon is still shown.

If you want to have your icon even when you're pressing F5, you can add in the Main Window:

<Window x:Class="myClass"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Icon="./Resources/Icon/myIcon.png">

where you indicate the path to your icon (the icon can be *.png, *.ico.)

(Note you will still need to set the Application Icon or it'll still be the default in Explorer).

How to repair a serialized string which has been corrupted by an incorrect byte count length?

After having tried some things on this page without success I had a look in the page-source and remarked that all quotes in the serialized string have been replaced by html-entities. Decoding these entities helps avoiding much headache:

$myVar = html_entity_decode($myVar);

Android Activity as a dialog

Some times you can get the Exception which is given below

Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

So for resolving you can use simple solution

add theme of you activity in manifest as dialog for appCompact.

android:theme="@style/Theme.AppCompat.Dialog"

It can be helpful for somebody.

How to pause for specific amount of time? (Excel/VBA)

You can use Application.wait now + timevalue("00:00:01") or Application.wait now + timeserial(0,0,1)

How do I calculate someone's age in Java?

The fields birth and effect are both date fields:

Calendar bir = Calendar.getInstance();
bir.setTime(birth);
int birthNm = bir.get(Calendar.DAY_OF_YEAR);
int birthYear = bir.get(Calendar.YEAR);
Calendar eff = Calendar.getInstance();
eff.setTime(effect);

This basically a modification of John O's solution without using depreciated methods. I spent a fair amount of time trying to get his code to work in in my code. Maybe this will save others that time.

How to index characters in a Golang string?

Try this to get the charecters by their index

package main

import (
      "fmt"
      "strings"
)

func main() {
   str := strings.Split("HELLO","")
    fmt.Print(str[1])
}

How to get first record in each group using Linq

Use it to achieve what you want. Then decide which properties you want to return.

yourList.OrderBy(l => l.Id).GroupBy(l => new { GroupName = l.F1}).Select(r => r.Key.GroupName)

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

I tried all of the above and nothing worked for me.

Then I followed Gradle Settings > Build Execution, Deployment > Gradle > Android Studio and checked "Disable embedded Maven repository".

Did a build with this checked and the problem was solved.

jQuery - getting custom attribute from selected option

Here is the entire script with an AJAX call to target a single list within a page with multiple lists. None of the other stuff above worked for me until I used the "id" attribute even though my attribute name is "ItemKey". By using the debugger

Chrome Debug

I was able to see that the selected option had attributes: with a map to the JQuery "id" and the value.

<html>
<head>
<script type="text/JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<select id="List1"></select>
<select id="List2">
<option id="40000">List item #1</option>
<option id="27888">List item #2</option>
</select>

<div></div>
</body>
<script type="text/JavaScript">
//get a reference to the select element
$select = $('#List1');

//request the JSON data and parse into the select element
$.ajax({
url: 'list.json',
dataType:'JSON',
success:function(data){

//clear the current content of the select
$select.html('');

//iterate over the data and append a select option
$.each(data.List, function(key, val){
$select.append('<option id="' + val.ItemKey + '">' + val.ItemText + '</option>');
})
},

error:function(){

//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});

$( "#List1" ).change(function () {
var optionSelected = $('#List1 option:selected').attr('id');
$( "div" ).text( optionSelected );
});
</script>
</html>

Here is the JSON File to create...

{  
"List":[  
{  
"Sort":1,
"parentID":0,
"ItemKey":100,
"ItemText":"ListItem-#1"
},
{  
"Sort":2,
"parentID":0,
"ItemKey":200,
"ItemText":"ListItem-#2"
},
{  
"Sort":3,
"parentID":0,
"ItemKey":300,
"ItemText":"ListItem-#3"
},
{  
"Sort":4,
"parentID":0,
"ItemKey":400,
"ItemText":"ListItem-#4"
}
]
}

Hope this helps, thank you all above for getting me this far.

Position of a string within a string using Linux shell script?

You can use grep to get the byte-offset of the matching part of a string:

echo $str | grep -b -o str

As per your example:

[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
4:cat

you can pipe that to awk if you just want the first part

echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'

SSL "Peer Not Authenticated" error with HttpClient 4.1

This is thrown when

... the peer was not able to identify itself (for example; no certificate, the particular cipher suite being used does not support authentication, or no peer authentication was established during SSL handshaking) this exception is thrown.

Probably the cause of this exception (where is the stacktrace) will show you why this exception is thrown. Most likely the default keystore shipped with Java does not contain (and trust) the root certificate of the TTP that is being used.

The answer is to retrieve the root certificate (e.g. from your browsers SSL connection), import it into the cacerts file and trust it using keytool which is shipped by the Java JDK. Otherwise you will have to assign another trust store programmatically.

What range of values can integer types store in C++

The minimum ranges you can rely on are:

  • short int and int: -32,767 to 32,767
  • unsigned short int and unsigned int: 0 to 65,535
  • long int: -2,147,483,647 to 2,147,483,647
  • unsigned long int: 0 to 4,294,967,295

This means that no, long int cannot be relied upon to store any 10 digit number. However, a larger type long long int was introduced to C in C99 and C++ in C++11 (this type is also often supported as an extension by compilers built for older standards that did not include it). The minimum range for this type, if your compiler supports it, is:

  • long long int: -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807
  • unsigned long long int: 0 to 18,446,744,073,709,551,615

So that type will be big enough (again, if you have it available).


A note for those who believe I've made a mistake with these lower bounds - I haven't. The C requirements for the ranges are written to allow for ones' complement or sign-magnitude integer representations, where the lowest representable value and the highest representable value differ only in sign. It is also allowed to have a two's complement representation where the value with sign bit 1 and all value bits 0 is a trap representation rather than a legal value. In other words, int is not required to be able to represent the value -32,768.

Should I add the Visual Studio .suo and .user files to source control?

By default Microsoft's Visual SourceSafe does not include these files in the source control because they are user-specific settings files. I would follow that model if you're using SVN as source control.

How to sort by two fields in Java?

I'm not sure if it's ugly to write the compartor inside the Person class in this case. Did it like this:

public class Person implements Comparable <Person> {

    private String lastName;
    private String firstName;
    private int age;

    public Person(String firstName, String lastName, int BirthDay) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = BirthDay;
    }

    public int getAge() {
        return age;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    @Override
    public int compareTo(Person o) {
        // default compareTo
    }

    @Override
    public String toString() {
        return firstName + " " + lastName + " " + age + "";
    }

    public static class firstNameComperator implements Comparator<Person> {
        @Override
        public int compare(Person o1, Person o2) {
            return o1.firstName.compareTo(o2.firstName);
        }
    }

    public static class lastNameComperator implements Comparator<Person> {
        @Override
        public int compare(Person o1, Person o2) {
            return o1.lastName.compareTo(o2.lastName);
        }
    }

    public static class ageComperator implements Comparator<Person> {
        @Override
        public int compare(Person o1, Person o2) {
            return o1.age - o2.age;
        }
    }
}
public class Test {
    private static void print() {
       ArrayList<Person> list = new ArrayList();
        list.add(new Person("Diana", "Agron", 31));
        list.add(new Person("Kay", "Panabaker", 27));
        list.add(new Person("Lucy", "Hale", 28));
        list.add(new Person("Ashley", "Benson", 28));
        list.add(new Person("Megan", "Park", 31));
        list.add(new Person("Lucas", "Till", 27));
        list.add(new Person("Nicholas", "Hoult", 28));
        list.add(new Person("Aly", "Michalka", 28));
        list.add(new Person("Adam", "Brody", 38));
        list.add(new Person("Chris", "Pine", 37));
        Collections.sort(list, new Person.lastNameComperator());
        Iterator<Person> it = list.iterator();
        while(it.hasNext()) 
            System.out.println(it.next().toString()); 
     }  
}    

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

How to open Emacs inside Bash

Emacs takes many launch options. The one that you are looking for is emacs -nw. This will open Emacs inside the terminal disregarding the DISPLAY environment variable even if it is set. The long form of this flag is emacs --no-window-system.

More information about Emacs launch options can be found in the manual.

HTML button onclick event

<body>
"button" value="Add Students" onclick="window.location.href='Students.html';"> 
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';"> 
<input type="button" value="Student Payments" onclick="window.location.href='Payments.html';">
</body>

Check table exist or not before create it in Oracle

I know this topic is a bit old, but I think I did something that may be useful for someone, so I'm posting it.

I compiled suggestions from this thread's answers into a procedure:

CREATE OR REPLACE PROCEDURE create_table_if_doesnt_exist(
  p_table_name VARCHAR2,
  create_table_query VARCHAR2
) AUTHID CURRENT_USER IS
  n NUMBER;
BEGIN
  SELECT COUNT(*) INTO n FROM user_tables WHERE table_name = UPPER(p_table_name);
  IF (n = 0) THEN
    EXECUTE IMMEDIATE create_table_query;
  END IF;
END;

You can then use it in a following way:

call create_table_if_doesnt_exist('my_table', 'CREATE TABLE my_table (
        id NUMBER(19) NOT NULL PRIMARY KEY,
        text VARCHAR2(4000),
        modified_time TIMESTAMP
  )'
);

I know that it's kinda redundant to pass table name twice, but I think that's the easiest here.

Hope somebody finds above useful :-).

C++ template constructor

try doing something like

template<class T, int i> class A{

    A(){
          A(this)
    }

    A( A<int, 1>* a){
          //do something
    }
    A( A<float, 1>* a){
         //do something
    }
.
.
.
};

Email and phone Number Validation in android

Try this

public class Validation {

    public final static boolean isValidEmail(CharSequence target) {
        if (target == null) {
        return false;
        } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
        }
    } 

    public static final boolean isValidPhoneNumber(CharSequence target) {
        if (target.length()!=10) {
            return false;
        } else {
            return android.util.Patterns.PHONE.matcher(target).matches();
        }
    }

}

ASP.net page without a code behind

By default Sharepoint does not allow server-side code to be executed in ASPX files. See this for how to resolve that.

However, I would raise that having a code-behind is not necessarily difficult to deploy in Sharepoint (we do it extensively) - just compile your code-behind classes into an assembly and deploy it using a solution.

If still no, you can include all the code you'd normally place in a codebehind like so:

<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
  //hello, world!
}
</script>

LINQ order by null column where order is ascending and nulls should be last

Try putting both columns in the same orderby.

orderby p.LowestPrice.HasValue descending, p.LowestPrice

Otherwise each orderby is a separate operation on the collection re-ordering it each time.

This should order the ones with a value first, "then" the order of the value.

How to delete an element from an array in C#

If you want to remove all instances of 4 without needing to know the index:

LINQ: (.NET Framework 3.5)

int[] numbers = { 1, 3, 4, 9, 2 };
int numToRemove = 4;
numbers = numbers.Where(val => val != numToRemove).ToArray();

Non-LINQ: (.NET Framework 2.0)

static bool isNotFour(int n)
{
    return n != 4;
}

int[] numbers = { 1, 3, 4, 9, 2 };
numbers = Array.FindAll(numbers, isNotFour).ToArray();

If you want to remove just the first instance:

LINQ: (.NET Framework 3.5)

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIndex = Array.IndexOf(numbers, numToRemove);
numbers = numbers.Where((val, idx) => idx != numIndex).ToArray();

Non-LINQ: (.NET Framework 2.0)

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIdx = Array.IndexOf(numbers, numToRemove);
List<int> tmp = new List<int>(numbers);
tmp.RemoveAt(numIdx);
numbers = tmp.ToArray();

Edit: Just in case you hadn't already figured it out, as Malfist pointed out, you need to be targetting the .NET Framework 3.5 in order for the LINQ code examples to work. If you're targetting 2.0 you need to reference the Non-LINQ examples.

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

I found it working for me by setting this variable directly on Azure platorm (if you use it). Just select your web app -> configuration -> application settings and add the variable and its value, then press Save button.

X-Frame-Options Allow-From multiple domains

YES. This method allowed multiple domain.

VB.NET

response.headers.add("X-Frame-Options", "ALLOW-FROM " & request.urlreferer.tostring())

Running command line silently with VbScript and getting output?

Dim path As String = GetFolderPath(SpecialFolder.ApplicationData)
 Dim filepath As String = path + "\" + "your.bat"
    ' Create the file if it does not exist. 
    If File.Exists(filepath) = False Then
        File.Create(filepath)
    Else
    End If
    Dim attributes As FileAttributes
    attributes = File.GetAttributes(filepath)
    If (attributes And FileAttributes.ReadOnly) = FileAttributes.ReadOnly Then
        ' Remove from Readonly the file.
        attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly)
        File.SetAttributes(filepath, attributes)
        Console.WriteLine("The {0} file is no longer RO.", filepath)
    Else
    End If
    If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
        ' Show the file.
        attributes = RemoveAttribute(attributes, FileAttributes.Hidden)
        File.SetAttributes(filepath, attributes)
        Console.WriteLine("The {0} file is no longer Hidden.", filepath)
    Else
    End If
    Dim sr As New StreamReader(filepath)
    Dim input As String = sr.ReadToEnd()
    sr.Close()
    Dim output As String = "@echo off"
    Dim output1 As String = vbNewLine + "your 1st cmd code"
    Dim output2 As String = vbNewLine + "your 2nd cmd code "
    Dim output3 As String = vbNewLine + "exit"
    Dim sw As New StreamWriter(filepath)
    sw.Write(output)
    sw.Write(output1)
    sw.Write(output2)
    sw.Write(output3)
    sw.Close()
    If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
    Else
        ' Hide the file.
        File.SetAttributes(filepath, File.GetAttributes(filepath) Or FileAttributes.Hidden)
        Console.WriteLine("The {0} file is now hidden.", filepath)
    End If
    Dim procInfo As New ProcessStartInfo(path + "\" + "your.bat")
    procInfo.WindowStyle = ProcessWindowStyle.Minimized
    procInfo.WindowStyle = ProcessWindowStyle.Hidden
    procInfo.CreateNoWindow = True
    procInfo.FileName = path + "\" + "your.bat"
    procInfo.Verb = "runas"
    Process.Start(procInfo)

it saves your .bat file to "Appdata of current user" ,if it does not exist and remove the attributes and after that set the "hidden" attributes to file after writing your cmd code and run it silently and capture all output saves it to file so if u wanna save all output of cmd to file just add your like this

code > C:\Users\Lenovo\Desktop\output.txt

just replace word "code" with your .bat file code or command and after that the directory of output file I found one code recently after searching alot if u wanna run .bat file in vb or c# or simply just add this in the same manner in which i have written

Expression must have class type

Allow an analysis.

#include <iostream>   // not #include "iostream"
using namespace std;  // in this case okay, but never do that in header files

class A
{
 public:
  void f() { cout<<"f()\n"; }
};

int main()
{
 /*
 // A a; //this works
 A *a = new A(); //this doesn't
 a.f(); // "f has not been declared"
 */ // below


 // system("pause");  <-- Don't do this. It is non-portable code. I guess your 
 //                       teacher told you this?
 //                       Better: In your IDE there is prolly an option somewhere
 //                               to not close the terminal/console-window.
 //                       If you compile on a CLI, it is not needed at all.
}

As a general advice:

0) Prefer automatic variables
  int a;
  MyClass myInstance;
  std::vector<int> myIntVector;

1) If you need data sharing on big objects down 
   the call hierarchy, prefer references:

  void foo (std::vector<int> const &input) {...}
  void bar () { 
       std::vector<int> something;
       ...
       foo (something);
  }


2) If you need data sharing up the call hierarchy, prefer smart-pointers
   that automatically manage deletion and reference counting.

3) If you need an array, use std::vector<> instead in most cases.
   std::vector<> is ought to be the one default container.

4) I've yet to find a good reason for blank pointers.

   -> Hard to get right exception safe

       class Foo {
           Foo () : a(new int[512]), b(new int[512]) {}
           ~Foo() {
               delete [] b;
               delete [] a;
           }
       };

       -> if the second new[] fails, Foo leaks memory, because the
          destructor is never called. Avoid this easily by using 
          one of the standard containers, like std::vector, or
          smart-pointers.

As a rule of thumb: If you need to manage memory on your own, there is generally a superiour manager or alternative available already, one that follows the RAII principle.

Basic calculator in Java

CompareStrings with equals(..) not with ==

if (operation.equals("+")
{
    System.out.println("your answer is" + (num1 + num2));
}
if (operation.equals("-"))
{
    System.out.println("your answer is" + (num1 - num2));
}
if (operation.equals("/"))
{
    System.out.println("your answer is" + (num1 / num2));
}
if (operation .equals( "*"))
{
    System.out.println("your answer is" + (num1 * num2));
}

And the ; after the conditions was an empty statement so the conditon had no effect at all.

If you use java 7 you can also replace the if statements with a switch.
In java <7 you can test, if operation has length 1 and than make a switch for the char [switch (operation.charAt(0))]

Java URL encoding of query string parameters

  1. Use this: URLEncoder.encode(query, StandardCharsets.UTF_8.displayName()); or this:URLEncoder.encode(query, "UTF-8");
  2. You can use the follwing code.

    String encodedUrl1 = UriUtils.encodeQuery(query, "UTF-8");//not change 
    String encodedUrl2 = URLEncoder.encode(query, "UTF-8");//changed
    String encodedUrl3 = URLEncoder.encode(query, StandardCharsets.UTF_8.displayName());//changed
    
    System.out.println("url1 " + encodedUrl1 + "\n" + "url2=" + encodedUrl2 + "\n" + "url3=" + encodedUrl3);
    

Count the number of occurrences of a character in a string in Javascript

What about string.split(desiredCharecter).length-1

Example:

var str = "hellow how is life"; var len = str.split("h").length-1; will give count 2 for character "h" in the above string;

Primitive type 'short' - casting in Java

EDIT: Okay, now we know it's Java...

Section 4.2.2 of the Java Language Specification states:

The Java programming language provides a number of operators that act on integral values:

[...]

  • The numerical operators, which result in a value of type int or long:
  • [...]
  • The additive operators + and - (§15.18)

  • In other words, it's like C# - the addition operator (when applied to integral types) only ever results in int or long, which is why you need to cast to assign to a short variable.

    Original answer (C#)

    In C# (you haven't specified the language, so I'm guessing), the only addition operators on primitive types are:

    int operator +(int x, int y);
    uint operator +(uint x, uint y);
    long operator +(long x, long y);
    ulong operator +(ulong x, ulong y);
    float operator +(float x, float y);
    double operator +(double x, double y);
    

    These are in the C# 3.0 spec, section 7.7.4. In addition, decimal addition is defined:

    decimal operator +(decimal x, decimal y);
    

    (Enumeration addition, string concatenation and delegate combination are also defined there.)

    As you can see, there's no short operator +(short x, short y) operator - so both operands are implicitly converted to int, and the int form is used. That means the result is an expression of type "int", hence the need to cast.

    How to set space between listView Items in Android

    @Asahi pretty much hit the nail on the head, but I just wanted to add a bit of XML for anyone maybe floating in here later via google:

    <ListView android:id="@+id/MyListView"
      android:layout_height="match_parent"
      android:layout_width="match_parent"
      android:divider="@android:color/transparent"
      android:dividerHeight="10.0sp"/>
    

    For some reason, values such as "10", "10.0", and "10sp" all are rejected by Android for the dividerHeight value. It wants a floating point number and a unit, such as "10.0sp". As @Goofyahead notes, you can also use display-independent pixels for this value (ie, "10dp").

    Pythonic way of checking if a condition holds for any element of a list

    any():

    if any(t < 0 for t in x):
        # do something
    

    Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:

    if True in (t < 0 for t in x):
    

    Find if value in column A contains value from column B?

    You could try this

    =IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),FALSE, TRUE)
    

    -or-

    =IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),"FALSE", "File found in row "   & MATCH(<single column I value>,<entire column E range>,0))
    

    you could replace <single column I value> and <entire column E range> with named ranged. That'd probably be the easiest.

    Just drag that formula all the way down the length of your I column in whatever column you want.

    How to add subject alernative name to ssl certs?

    When generating CSR is possible to specify -ext attribute again to have it inserted in the CSR

    keytool -certreq -file test.csr -keystore test.jks -alias testAlias -ext SAN=dns:test.example.com
    

    complete example here: How to create CSR with SANs using keytool

    Removing duplicates from a SQL query (not just "use distinct")

    If I understand you correctly, you want a list of all pictures with the same name (and their different ids) such that their name occurs more than once in the table. I think this will do the trick:

    SELECT U.NAME, P.PIC_ID
    FROM USERS U, PICTURES P, POSTINGS P1
    WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND U.Name IN (
    SELECT U.Name 
    FROM USERS U, PICTURES P, POSTINGS P1
    WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND P.CAPTION LIKE '%car%';
    GROUP BY U.Name HAVING COUNT(U.Name) > 1)
    

    I haven't executed it, so there may be a syntax error or two there.

    Simple bubble sort c#

    int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
    
    int temp = 0;
    
    for (int write = 0; write < arr.Length; write++)
    {
        for (int sort = 0; sort < arr.Length - 1 - write ; sort++)
        {
            if (arr[sort] > arr[sort + 1])
            {
                temp = arr[sort + 1];
                arr[sort + 1] = arr[sort];
                arr[sort] = temp;
            }
        }
    }
    
    for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");
    
    Console.ReadKey();
    

    HTML favicon won't show on google chrome

    I moved ico file to root folder and link it. It worked for me. Also, in chrome, I have to wait 30 mins to get cache cleared and new changes to take affect.

    How to launch an Activity from another Application in Android

    If you want to open specific activity of another application we can use this.

    Intent intent = new Intent(Intent.ACTION_MAIN, null);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.fuelgauge.PowerUsageSummary");
    intent.setComponent(cn);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try 
    {
        startActivity(intent)
    }catch(ActivityNotFoundException e){
        Toast.makeText(context,"Activity Not Found",Toast.LENGTH_SHORT).show()
    }
    

    If you must need other application, instead of showing Toast you can show a dialog. Using dialog you can bring the user to Play-Store to download required application.

    Add text to textarea - Jquery

    Just append() the text nodes:

    $('#replyBox').append(quote); 
    

    http://jsfiddle.net/nQErc/

    How do I sort a Set to a List in Java?

    @Jeremy Stein I wanted to implement same code. As well I wanted to sort the set to list, So instead of using Set I converted set values into List and sort that list by it's one the variable. This code helped me,

    set.stream().sorted(Comparator.comparing(ModelClassName::sortingVariableName)).collect(Collectors.toList());
    

    TypeError: unsupported operand type(s) for -: 'str' and 'int'

    1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

    2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

      def cat_n_times(s, n):
          for i in range(n):
              print(s) 
      
      text = input("What would you like the computer to repeat back to you: ")
      num = int(input("How many times: ")) # Convert to an int immediately.
      
      cat_n_times(text, num)
      
    3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

    How can I get onclick event on webview in android?

    I think you can also use MotionEvent.ACTION_UP state, example:

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()) {
        case R.id.iv:
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (isheadAndFootShow == false) {
                    headLayout.setVisibility(View.VISIBLE);
                    footLayout.setVisibility(View.VISIBLE);
                    isheadAndFootShow = true;
                } else {
                    headLayout.setVisibility(View.INVISIBLE);
                    footLayout.setVisibility(View.INVISIBLE);
                    isheadAndFootShow = false;
                }
                return true;
            }
            break;
        }
    
        return false;
    }
    

    checked = "checked" vs checked = true

    checked attribute is a boolean value so "checked" value of other "string" except boolean false converts to true.

    Any string value will be true. Also presence of attribute make it true:

    <input type="checkbox" checked>
    

    You can make it uncheked only making boolean change in DOM using JS.

    So the answer is: they are equal.

    w3c

    Detect the Enter key in a text input field

    It may be too late to answer this question. But the following code simply prevents the enter key. Just copy and paste should work.

            <script type="text/javascript"> 
            function stopRKey(evt) { 
              var evt = (evt) ? evt : ((event) ? event : null); 
              var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
              if ((evt.keyCode == 13) && (node.type=="text"))  {return false;} 
            } 
    
            document.onkeypress = stopRKey; 
    
            </script>
    

    Looking for simple Java in-memory cache

    Another option for an in-memory java cache is cache2k. The in-memory performance is superior to EHCache and google guava, see the cache2k benchmarks page.

    The usage pattern is similar to other caches. Here is an example:

    Cache<String,String> cache = new Cache2kBuilder<String, String>() {}
      .expireAfterWrite(5, TimeUnit.MINUTES)    // expire/refresh after 5 minutes
      .resilienceDuration(30, TimeUnit.SECONDS) // cope with at most 30 seconds
                                              // outage before propagating 
                                              // exceptions
      .refreshAhead(true)                       // keep fresh when expiring
      .loader(new CacheLoader<String, String>() {
        @Override
        public String load(final String key) throws Exception {
          return ....;
        }
      })
      .build();
    String val = cache.peek("something");
    cache.put("something", "hello");
    val = cache.get("something");
    

    If you have google guava as dependency then trying out guava cache, may be a good alternative.

    Aren't Python strings immutable? Then why does a + " " + b work?

    A variable is just a label pointing to an object. The object is immutable, but you can make the label point to a completely different object if you want to.

    I can’t find the Android keytool

    If you're using Android Studio for Windows to create a release keystore and signed .apk, just follow these steps:

    1) Build > Generate Signed APK

    2) Choose "Create New...", choose the path to the keystore, and enter all the required data

    3) After your keystore (your_keystore_name.jks) has been created, you will then use it to create your first signed apk at a destination of your choosing

    I haven't seen a need to use the command tool if you have an IDE like Android Studio.

    How to convert a string of bytes into an int?

    A decently speedy method utilizing array.array I've been using for some time:

    predefined variables:

    offset = 0
    size = 4
    big = True # endian
    arr = array('B')
    arr.fromstring("\x00\x00\xff\x00") # 5 bytes (encoding issues) [0, 0, 195, 191, 0]
    

    to int: (read)

    val = 0
    for v in arr[offset:offset+size][::pow(-1,not big)]: val = (val<<8)|v
    

    from int: (write)

    val = 16384
    arr[offset:offset+size] = \
        array('B',((val>>(i<<3))&255 for i in range(size)))[::pow(-1,not big)]
    

    It's possible these could be faster though.

    EDIT:
    For some numbers, here's a performance test (Anaconda 2.3.0) showing stable averages on read in comparison to reduce():

    ========================= byte array to int.py =========================
    5000 iterations; threshold of min + 5000ns:
    ______________________________________code___|_______min______|_______max______|_______avg______|_efficiency
    ????????????????????????????????????????????????????????????????
    ????????????????????????????????????????????????????????????????
        val = 0 \nfor v in arr: val = (val<<8)|v |     5373.848ns |   850009.965ns |     ~8649.64ns |  62.128%
    ????????????????????????????????????????????????????????????????
    ????????????????????????????????????????????????????????????????
                      val = reduce( shift, arr ) |     6489.921ns |  5094212.014ns |   ~12040.269ns |  53.902%
    

    This is a raw performance test, so the endian pow-flip is left out.
    The shift function shown applies the same shift-oring operation as the for loop, and arr is just array.array('B',[0,0,255,0]) as it has the fastest iterative performance next to dict.

    I should probably also note efficiency is measured by accuracy to the average time.

    Lazy Loading vs Eager Loading

    Consider the below situation

    public class Person{
        public String Name{get; set;}
        public String Email {get; set;}
        public virtual Employer employer {get; set;}
    }
    
    public List<EF.Person> GetPerson(){
        using(EF.DbEntities db = new EF.DbEntities()){
           return db.Person.ToList();
        }
    }
    

    Now after this method is called, you cannot lazy load the Employer entity anymore. Why? because the db object is disposed. So you have to do Person.Include(x=> x.employer) to force that to be loaded.

    What is .Net Framework 4 extended?

    Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.

    To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)

    The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:

    * ASP.NET
    * Advanced Windows Communication Foundation (WCF) functionality
    * .NET Framework Data Provider for Oracle
    * MSBuild for compiling
    

    How do I read any request header in PHP

    This small PHP snippet can be helpful to you:

    <?php
    foreach($_SERVER as $key => $value){
    echo '$_SERVER["'.$key.'"] = '.$value."<br />";
    }
    ?>
    

    How can I easily switch between PHP versions on Mac OSX?

    If you have both versions of PHP installed, you can switch between versions using the link and unlink brew commands.

    For example, to switch between PHP 7.4 and PHP 7.3

    brew unlink [email protected]
    brew link [email protected]
    

    PS: both versions of PHP have be installed for these commands to work.

    Adding backslashes without escaping [Python]

    The result '\\&' is only displayed - actually the string is \&:

    >>> str = '&'
    >>> new_str = str.replace('&', '\&')
    >>> new_str
    '\\&'
    >>> print new_str
    \&
    

    Try it in a shell.

    How to generate keyboard events?

    user648852's idea at least for me works great for OS X, here is the code to do it:

    #!/usr/bin/env python
    
    import time
    from Quartz.CoreGraphics import CGEventCreateKeyboardEvent
    from Quartz.CoreGraphics import CGEventPost
    
    # Python releases things automatically, using CFRelease will result in a scary error
    #from Quartz.CoreGraphics import CFRelease
    
    from Quartz.CoreGraphics import kCGHIDEventTap
    
    # From http://stackoverflow.com/questions/281133/controlling-the-mouse-from-python-in-os-x
    # and from https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/index.html#//apple_ref/c/func/CGEventCreateKeyboardEvent
    
    
    def KeyDown(k):
        keyCode, shiftKey = toKeyCode(k)
    
        time.sleep(0.0001)
    
        if shiftKey:
            CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
            time.sleep(0.0001)
    
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
        time.sleep(0.0001)
    
        if shiftKey:
            CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
            time.sleep(0.0001)
    
    def KeyUp(k):
        keyCode, shiftKey = toKeyCode(k)
    
        time.sleep(0.0001)
    
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
        time.sleep(0.0001)
    
    def KeyPress(k):
        keyCode, shiftKey = toKeyCode(k)
    
        time.sleep(0.0001)
    
        if shiftKey:
            CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
            time.sleep(0.0001)
    
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
        time.sleep(0.0001)
    
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
        time.sleep(0.0001)
    
        if shiftKey:
            CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
            time.sleep(0.0001)
    
    
    
    # From http://stackoverflow.com/questions/3202629/where-can-i-find-a-list-of-mac-virtual-key-codes
    
    def toKeyCode(c):
        shiftKey = False
        # Letter
        if c.isalpha():
            if not c.islower():
                shiftKey = True
                c = c.lower()
    
        if c in shiftChars:
            shiftKey = True
            c = shiftChars[c]
        if c in keyCodeMap:
            keyCode = keyCodeMap[c]
        else:
            keyCode = ord(c)
        return keyCode, shiftKey
    
    shiftChars = {
        '~': '`',
        '!': '1',
        '@': '2',
        '#': '3',
        '$': '4',
        '%': '5',
        '^': '6',
        '&': '7',
        '*': '8',
        '(': '9',
        ')': '0',
        '_': '-',
        '+': '=',
        '{': '[',
        '}': ']',
        '|': '\\',
        ':': ';',
        '"': '\'',
        '<': ',',
        '>': '.',
        '?': '/'
    }
    
    
    keyCodeMap = {
        'a'                 : 0x00,
        's'                 : 0x01,
        'd'                 : 0x02,
        'f'                 : 0x03,
        'h'                 : 0x04,
        'g'                 : 0x05,
        'z'                 : 0x06,
        'x'                 : 0x07,
        'c'                 : 0x08,
        'v'                 : 0x09,
        'b'                 : 0x0B,
        'q'                 : 0x0C,
        'w'                 : 0x0D,
        'e'                 : 0x0E,
        'r'                 : 0x0F,
        'y'                 : 0x10,
        't'                 : 0x11,
        '1'                 : 0x12,
        '2'                 : 0x13,
        '3'                 : 0x14,
        '4'                 : 0x15,
        '6'                 : 0x16,
        '5'                 : 0x17,
        '='                 : 0x18,
        '9'                 : 0x19,
        '7'                 : 0x1A,
        '-'                 : 0x1B,
        '8'                 : 0x1C,
        '0'                 : 0x1D,
        ']'                 : 0x1E,
        'o'                 : 0x1F,
        'u'                 : 0x20,
        '['                 : 0x21,
        'i'                 : 0x22,
        'p'                 : 0x23,
        'l'                 : 0x25,
        'j'                 : 0x26,
        '\''                : 0x27,
        'k'                 : 0x28,
        ';'                 : 0x29,
        '\\'                : 0x2A,
        ','                 : 0x2B,
        '/'                 : 0x2C,
        'n'                 : 0x2D,
        'm'                 : 0x2E,
        '.'                 : 0x2F,
        '`'                 : 0x32,
        'k.'                : 0x41,
        'k*'                : 0x43,
        'k+'                : 0x45,
        'kclear'            : 0x47,
        'k/'                : 0x4B,
        'k\n'               : 0x4C,
        'k-'                : 0x4E,
        'k='                : 0x51,
        'k0'                : 0x52,
        'k1'                : 0x53,
        'k2'                : 0x54,
        'k3'                : 0x55,
        'k4'                : 0x56,
        'k5'                : 0x57,
        'k6'                : 0x58,
        'k7'                : 0x59,
        'k8'                : 0x5B,
        'k9'                : 0x5C,
    
        # keycodes for keys that are independent of keyboard layout
        '\n'                : 0x24,
        '\t'                : 0x30,
        ' '                 : 0x31,
        'del'               : 0x33,
        'delete'            : 0x33,
        'esc'               : 0x35,
        'escape'            : 0x35,
        'cmd'               : 0x37,
        'command'           : 0x37,
        'shift'             : 0x38,
        'caps lock'         : 0x39,
        'option'            : 0x3A,
        'ctrl'              : 0x3B,
        'control'           : 0x3B,
        'right shift'       : 0x3C,
        'rshift'            : 0x3C,
        'right option'      : 0x3D,
        'roption'           : 0x3D,
        'right control'     : 0x3E,
        'rcontrol'          : 0x3E,
        'fun'               : 0x3F,
        'function'          : 0x3F,
        'f17'               : 0x40,
        'volume up'         : 0x48,
        'volume down'       : 0x49,
        'mute'              : 0x4A,
        'f18'               : 0x4F,
        'f19'               : 0x50,
        'f20'               : 0x5A,
        'f5'                : 0x60,
        'f6'                : 0x61,
        'f7'                : 0x62,
        'f3'                : 0x63,
        'f8'                : 0x64,
        'f9'                : 0x65,
        'f11'               : 0x67,
        'f13'               : 0x69,
        'f16'               : 0x6A,
        'f14'               : 0x6B,
        'f10'               : 0x6D,
        'f12'               : 0x6F,
        'f15'               : 0x71,
        'help'              : 0x72,
        'home'              : 0x73,
        'pgup'              : 0x74,
        'page up'           : 0x74,
        'forward delete'    : 0x75,
        'f4'                : 0x76,
        'end'               : 0x77,
        'f2'                : 0x78,
        'page down'         : 0x79,
        'pgdn'              : 0x79,
        'f1'                : 0x7A,
        'left'              : 0x7B,
        'right'             : 0x7C,
        'down'              : 0x7D,
        'up'                : 0x7E
    }
    

    Add Keypair to existing EC2 instance

    On your local machine, run command:

    ssh-keygen -t rsa -C "SomeAlias"
    

    After that command runs, a file ending in *.pub will be generated. Copy the contents of that file.

    On the Amazon machine, edit ~/.ssh/authorized_keys and paste the contents of the *.pub file (and remove any existing contents first).

    You can then SSH using the other file that was generated from the ssh-keygen command (the private key).

    Most efficient way to prepend a value to an array

    If you would like to prepend array (a1 with an array a2) you could use the following:

    var a1 = [1, 2];
    var a2 = [3, 4];
    Array.prototype.unshift.apply(a1, a2);
    console.log(a1);
    // => [3, 4, 1, 2]
    

    How to check the differences between local and github before the pull

    git pull is really equivalent to running git fetch and then git merge. The git fetch updates your so-called "remote-tracking branches" - typically these are ones that look like origin/master, github/experiment, etc. that you see with git branch -r. These are like a cache of the state of branches in the remote repository that are updated when you do git fetch (or a successful git push).

    So, suppose you've got a remote called origin that refers to your GitHub repository, you would do:

    git fetch origin
    

    ... and then do:

    git diff master origin/master
    

    ... in order to see the difference between your master, and the one on GitHub. If you're happy with those differences, you can merge them in with git merge origin/master, assuming master is your current branch.

    Personally, I think that doing git fetch and git merge separately is generally a good idea.

    ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

    For forms, use the [FromForm] attribute instead of the [FromBody] attribute.

    The below controller works with ASP.NET Core 1.1:

    public class MyController : Controller
    {
        [HttpPost]
        public async Task<IActionResult> Submit([FromForm] MyModel model)
        {
            //...
        }
    }
    

    Note: [FromXxx] is required if your controller is annotated with [ApiController]. For normal view controllers it can be omitted.

    PHP function overloading

    It may be hackish to some, but I learned this way from how Cakephp does some functions and have adapted it because I like the flexibility it creates

    The idea is you have different type of arguments, arrays, objects etc, then you detect what you were passed and go from there

    function($arg1, $lastname) {
        if(is_array($arg1)){
            $lastname = $arg1['lastname'];
            $firstname = $arg1['firstname'];
        } else {
            $firstname = $arg1;
        }
        ...
    }
    

    Replace all whitespace characters

    You could use the function trim

    let str = ' Hello World ';

    alert (str.trim());

    All the front and back spaces around Hello World would be removed.

    Converting String Array to an Integer Array

    Java has a method for this, "convertStringArrayToIntArray".

    String numbers = sc.nextLine();
    int[] intArray = convertStringArrayToIntArray(numbers.split(", "));
    

    Finding all positions of substring in a larger string in C#

    I found this example and incorporated it into a function:

        public static int solution1(int A, int B)
        {
            // Check if A and B are in [0...999,999,999]
            if ( (A >= 0 && A <= 999999999) && (B >= 0 && B <= 999999999))
            {
                if (A == 0 && B == 0)
                {
                    return 0;
                }
                // Make sure A < B
                if (A < B)
                {                    
                    // Convert A and B to strings
                    string a = A.ToString();
                    string b = B.ToString();
                    int index = 0;
    
                    // See if A is a substring of B
                    if (b.Contains(a))
                    {
                        // Find index where A is
                        if (b.IndexOf(a) != -1)
                        {                            
                            while ((index = b.IndexOf(a, index)) != -1)
                            {
                                Console.WriteLine(A + " found at position " + index);
                                index++;
                            }
                            Console.ReadLine();
                            return b.IndexOf(a);
                        }
                        else
                            return -1;
                    }
                    else
                    {
                        Console.WriteLine(A + " is not in " + B + ".");
                        Console.ReadLine();
    
                        return -1;
                    }
                }
                else
                {
                    Console.WriteLine(A + " must be less than " + B + ".");
                   // Console.ReadLine();
    
                    return -1;
                }                
            }
            else
            {
                Console.WriteLine("A or B is out of range.");
                //Console.ReadLine();
    
                return -1;
            }
        }
    
        static void Main(string[] args)
        {
            int A = 53, B = 1953786;
            int C = 78, D = 195378678;
            int E = 57, F = 153786;
    
            solution1(A, B);
            solution1(C, D);
            solution1(E, F);
    
            Console.WriteLine();
        }
    

    Returns:

    53 found at position 2

    78 found at position 4
    78 found at position 7

    57 is not in 153786

    Installing Bower on Ubuntu

    on Ubuntu 12.04 and the packaged version of NodeJs is too old to install Bower using the PPA

    sudo add-apt-repository ppa:chris-lea/node.js 
    sudo apt-get update
    sudo apt-get -y install nodejs
    

    When this has installed, check the version:

    npm --version
    1.4.3
    

    Now install Bower:

    sudo npm install -g bower
    

    This will fetch and install Bower globally.

    Java: Simplest way to get last word in a string

    String testString = "This is a sentence";
    String[] parts = testString.split(" ");
    String lastWord = parts[parts.length - 1];
    System.out.println(lastWord); // "sentence"
    

    How can I force division to be floating point? Division keeps rounding down to 0?

    If you want to use "true" (floating point) division by default, there is a command line flag:

    python -Q new foo.py
    

    There are some drawbacks (from the PEP):

    It has been argued that a command line option to change the default is evil. It can certainly be dangerous in the wrong hands: for example, it would be impossible to combine a 3rd party library package that requires -Qnew with another one that requires -Qold.

    You can learn more about the other flags values that change / warn-about the behavior of division by looking at the python man page.

    For full details on division changes read: PEP 238 -- Changing the Division Operator

    Hibernate Auto Increment ID

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    

    and you leave it null (0) when persisting. (null if you use the Integer / Long wrappers)

    In some cases the AUTO strategy is resolved to SEQUENCE rathen than to IDENTITY or TABLE, so you might want to manually set it to IDENTITY or TABLE (depending on the underlying database).

    It seems SEQUENCE + specifying the sequence name worked for you.

    Add or change a value of JSON key with jquery or javascript

    Once you have decoded the JSON, the result is a JavaScript object. Just manipulate it as you would any other object. For example:

    data.busNum = 12345;
    ...
    

    Combine two tables for one output

    You'll need to use UNION to combine the results of two queries. In your case:

    SELECT ChargeNum, CategoryID, SUM(Hours)
    FROM KnownHours
    GROUP BY ChargeNum, CategoryID
    UNION ALL
    SELECT ChargeNum, 'Unknown' AS CategoryID, SUM(Hours)
    FROM UnknownHours
    GROUP BY ChargeNum
    

    Note - If you use UNION ALL as in above, it's no slower than running the two queries separately as it does no duplicate-checking.

    How to pass params with history.push/Link/Redirect in react-router v4?

    If you need to pass URL params

    theres a great post explanation by Tyler McGinnis on his site, Link to the post

    here are code examples:

    1. on the history.push component:

      this.props.history.push(`/home:${this.state.userID}`)

    2. on the router component you define the route:

      <Route path='/home:myKey' component={Home} />

    3. on the Home component:

    componentDidMount(){
        const { myKey } = this.props.match.params
        console.log(myKey )
    }
    

    Angular 2.0 router not working on reloading the browser

    For those of us struggling through life in IIS: use the following PowerShell code to fix this issue based on the official Angular 2 docs (that someone posted in this thread? http://blog.angular-university.io/angular2-router/)

    Import-WebAdministration
    # Grab the 404 handler and update it to redirect to index.html.
    $redirect = Get-WebConfiguration -filter "/system.WebServer/httperrors/error[@statusCode='404']" -PSPath IIS:\Sites\LIS 
    $redirect.path = "/index.html"
    $redirect.responseMode = 1
    # shove the updated config back into IIS
    Set-WebConfiguration -filter "/system.WebServer/httperrors/error[@statusCode='404']" -PSPath IIS:\Sites\LIS -value $redirect
    

    This redirects the 404 to the /index.html file as per the suggestion in the Angular 2 docs (link above).

    creating a table in ionic

    You should consider using an angular plug-in to handle the heavy lifting for you, unless you particularly enjoy typing hundreds of lines of knarly error prone ion-grid code. Simon Grimm has a cracking step by step tutorial that anyone can follow: https://devdactic.com/ionic-datatable-ngx-datatable/. This shows how to use ngx-datatable. But there are many other options (ng2-table is good).

    The dead simple example goes like this:

    <ion-content>
      <ngx-datatable class="fullscreen" [ngClass]="tablestyle" [rows]="rows" [columnMode]="'force'" [sortType]="'multi'" [reorderable]="false">
        <ngx-datatable-column name="Name"></ngx-datatable-column>
        <ngx-datatable-column name="Gender"></ngx-datatable-column>
        <ngx-datatable-column name="Age"></ngx-datatable-column>
      </ngx-datatable>
    </ion-content>
    

    And the ts:

    rows = [
        {
          "name": "Ethel Price",
          "gender": "female",
          "age": 22
        },
        {
          "name": "Claudine Neal",
          "gender": "female",
          "age": 55
        },
        {
          "name": "Beryl Rice",
          "gender": "female",
          "age": 67
        },
        {
          "name": "Simon Grimm",
          "gender": "male",
          "age": 28
        }
      ];
    

    Since the original poster expressed their frustration of how difficult it is to achieve this with ion-grid, I think the correct answer should not be constrained by this as a prerequisite. You would be nuts to roll your own, given how good this is!

    Is there a better way to refresh WebView?

    Why not to try this?

    Swift code to call inside class:

    self.mainFrame.reload()
    

    or external call

    myWebV.mainFrame.reload()
    

    django templates: include and extends

    Added for reference to future people who find this via google: You might want to look at the {% overextend %} tag provided by the mezzanine library for cases like this.

    Finding all possible permutations of a given string in python

    With recursive approach.

    def permute(word):
        if len(word) == 1:
            return [word]
        permutations = permute(word[1:])
        character = word[0]
        result = []
        for p in permutations:
            for i in range(len(p)+1):
                result.append(p[:i] + character + p[i:])
        return result
    
    
    
    
    running code.
    
    >>> permute('abc')
    ['abc', 'bac', 'bca', 'acb', 'cab', 'cba']
    

    Custom thread pool in Java 8 parallel stream

    If you don't want to rely on implementation hacks, there's always a way to achieve the same by implementing custom collectors that will combine map and collect semantics... and you wouldn't be limited to ForkJoinPool:

    list.stream()
      .collect(parallel(i -> process(i), executor, 4))
      .join()
    

    Luckily, it's done already here and available on Maven Central: http://github.com/pivovarit/parallel-collectors

    Disclaimer: I wrote it and take responsibility for it.

    Find nginx version?

    If you don't know where it is, locate nginx first.

    ps -ef | grep nginx
    

    Then you will see something like this:

    root      4801     1  0 May23 ?        00:00:00 nginx: master process /opt/nginx/sbin/nginx -c /opt/nginx/conf/nginx.conf
    root     12427 11747  0 03:53 pts/1    00:00:00 grep --color=auto nginx
    nginx    24012  4801  0 02:30 ?        00:00:00 nginx: worker process                              
    nginx    24013  4801  0 02:30 ?        00:00:00 nginx: worker process
    

    So now you already know where nginx is. You can use the -v or -V. Something like:

    /opt/nginx/sbin/nginx -v
    

    How to set session timeout in web.config

    If you want to set the timeout to 20 minutes, use something like this:

        <configuration>
          <system.web>
             <sessionState timeout="20"></sessionState>
          </system.web>
        </configuration>
    

    Why are primes important in cryptography?

    There are some good resources for ramping up on crypto. Here's one:

    From that page:

    In the most commonly used public-key cryptography system, invented by Ron Rivest, Adi Shamir, and Len Adleman in 1977, both the public and the private keys are derived from a pair of large prime numbers according to a relatively simple mathematical formula. In theory, it might be possible to derive the private key from the public key by working the formula backwards. But only the product of the large prime numbers is public, and factoring numbers of that size into primes is so hard that even the most powerful supercomputers in the world cant break an ordinary public key.

    Bruce Schneier's book Applied Cryptography is another. I highly recommend that book; it's fun reading.

    Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

    It looks like you have a certificate in DER format instead of PEM. This is why it works correctly when you provide the -inform PEM command line argument (which tells openssl what input format to expect).

    It's likely that your private key is using the same encoding. It looks as if the openssl rsa command also accepts a -inform argument, so try:

    openssl rsa -text -in file.key -inform DER
    

    A PEM encoded file is a plain-text encoding that looks something like:

    -----BEGIN RSA PRIVATE KEY-----
    MIGrAgEAAiEA0tlSKz5Iauj6ud3helAf5GguXeLUeFFTgHrpC3b2O20CAwEAAQIh
    ALeEtAIzebCkC+bO+rwNFVORb0bA9xN2n5dyTw/Ba285AhEA9FFDtx4VAxMVB2GU
    QfJ/2wIRANzuXKda/nRXIyRw1ArE2FcCECYhGKRXeYgFTl7ch7rTEckCEQDTMShw
    8pL7M7DsTM7l3HXRAhAhIMYKQawc+Y7MNE4kQWYe
    -----END RSA PRIVATE KEY-----
    

    While DER is a binary encoding format.

    Update

    Sometimes keys are distributed in PKCS#8 format (which can be either PEM or DER encoded). Try this and see what you get:

    openssl pkcs8 -in file.key -inform der
    

    Send File Attachment from Form Using phpMailer and PHP

    Try:

    if (isset($_FILES['uploaded_file']) &&
        $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
        $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
                             $_FILES['uploaded_file']['name']);
    }
    

    Basic example can also be found here.

    The function definition for AddAttachment is:

    public function AddAttachment($path,
                                  $name = '',
                                  $encoding = 'base64',
                                  $type = 'application/octet-stream')
    

    How to convert password into md5 in jquery?

    <script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
    <script>
        var passhash = CryptoJS.MD5(password).toString();
    
        $.post(
          'includes/login.php', 
          { user: username, pass: passhash },
          onLogin, 
          'json' );
    </script>
    

    jQuery add required to input fields

    Using .attr method

    .attr(attribute,value); // syntax
    
    .attr("required", true);
    // required="required"
    
    .attr("required", false);
    // 
    

    Using .prop

    .prop(property,value) // syntax
    
    .prop("required", true);
    // required=""
    
    .prop("required", false);
    //
    

    Read more from here

    https://stackoverflow.com/a/5876747/5413283

    Get number days in a specified month using JavaScript?

    Another possible option would be to use Datejs

    Then you can do

    Date.getDaysInMonth(2009, 9)     
    

    Although adding a library just for this function is overkill, it's always nice to know all the options you have available to you :)

    Can't connect to local MySQL server through socket '/tmp/mysql.sock

    If it's socket related read this file

    /etc/mysql/my.cnf
    

    and see what is the standard socket location. It's a line like:

    socket = /var/run/mysqld/mysqld.sock
    

    now create an alias for your shell like:

    alias mysql="mysql --socket=/var/run/mysqld/mysqld.sock"
    

    This way you don't need root privileges.

    Convert int to string?

    string myString = myInt.ToString();
    

    Check Postgres access for a user

    You could query the table_privileges table in the information schema:

    SELECT table_catalog, table_schema, table_name, privilege_type
    FROM   information_schema.table_privileges 
    WHERE  grantee = 'MY_USER'
    

    .NET Console Application Exit Event

    You can use the ProcessExit event of the AppDomain:

    class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);           
            // do some work
    
        }
    
        static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            Console.WriteLine("exit");
        }
    }
    

    Update

    Here is a full example program with an empty "message pump" running on a separate thread, that allows the user to input a quit command in the console to close down the application gracefully. After the loop in MessagePump you will probably want to clean up resources used by the thread in a nice manner. It's better to do that there than in ProcessExit for several reasons:

    • Avoid cross-threading problems; if external COM objects were created on the MessagePump thread, it's easier to deal with them there.
    • There is a time limit on ProcessExit (3 seconds by default), so if cleaning up is time consuming, it may fail if pefromed within that event handler.

    Here is the code:

    class Program
    {
        private static bool _quitRequested = false;
        private static object _syncLock = new object();
        private static AutoResetEvent _waitHandle = new AutoResetEvent(false);
    
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
            // start the message pumping thread
            Thread msgThread = new Thread(MessagePump);
            msgThread.Start();
            // read input to detect "quit" command
            string command = string.Empty;
            do
            {
                command = Console.ReadLine();
            } while (!command.Equals("quit", StringComparison.InvariantCultureIgnoreCase));
            // signal that we want to quit
            SetQuitRequested();
            // wait until the message pump says it's done
            _waitHandle.WaitOne();
            // perform any additional cleanup, logging or whatever
        }
    
        private static void SetQuitRequested()
        {
            lock (_syncLock)
            {
                _quitRequested = true;
            }
        }
    
        private static void MessagePump()
        {
            do
            {
                // act on messages
            } while (!_quitRequested);
            _waitHandle.Set();
        }
    
        static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            Console.WriteLine("exit");
        }
    }
    

    Converting from signed char to unsigned char and back again?

    There are two ways to interpret the input data; either -128 is the lowest value, and 127 is the highest (i.e. true signed data), or 0 is the lowest value, 127 is somewhere in the middle, and the next "higher" number is -128, with -1 being the "highest" value (that is, the most significant bit already got misinterpreted as a sign bit in a two's complement notation.

    Assuming you mean the latter, the formally correct way is

    signed char in = ...
    unsigned char out = (in < 0)?(in + 256):in;
    

    which at least gcc properly recognizes as a no-op.

    In Visual Studio C++, what are the memory allocation representations?

    There's actually quite a bit of useful information added to debug allocations. This table is more complete:

    http://www.nobugs.org/developer/win32/debug_crt_heap.html#table

    Address  Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments
    0x00320FD8  -40    0x01090009    0x01090009     0x01090009    0x0109005A     Win32 heap info
    0x00320FDC  -36    0x01090009    0x00180700     0x01090009    0x00180400     Win32 heap info
    0x00320FE0  -32    0xBAADF00D    0x00320798     0xDDDDDDDD    0x00320448     Ptr to next CRT heap block (allocated earlier in time)
    0x00320FE4  -28    0xBAADF00D    0x00000000     0xDDDDDDDD    0x00320448     Ptr to prev CRT heap block (allocated later in time)
    0x00320FE8  -24    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Filename of malloc() call
    0x00320FEC  -20    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Line number of malloc() call
    0x00320FF0  -16    0xBAADF00D    0x00000008     0xDDDDDDDD    0xFEEEFEEE     Number of bytes to malloc()
    0x00320FF4  -12    0xBAADF00D    0x00000001     0xDDDDDDDD    0xFEEEFEEE     Type (0=Freed, 1=Normal, 2=CRT use, etc)
    0x00320FF8  -8     0xBAADF00D    0x00000031     0xDDDDDDDD    0xFEEEFEEE     Request #, increases from 0
    0x00320FFC  -4     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
    0x00321000  +0     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
    0x00321004  +4     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
    0x00321008  +8     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
    0x0032100C  +12    0xBAADF00D    0xBAADF00D     0xDDDDDDDD    0xFEEEFEEE     Win32 heap allocations are rounded up to 16 bytes
    0x00321010  +16    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
    0x00321014  +20    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
    0x00321018  +24    0x00000010    0x00000010     0x00000010    0xFEEEFEEE     Win32 heap bookkeeping
    0x0032101C  +28    0x00000000    0x00000000     0x00000000    0xFEEEFEEE     Win32 heap bookkeeping
    0x00321020  +32    0x00090051    0x00090051     0x00090051    0xFEEEFEEE     Win32 heap bookkeeping
    0x00321024  +36    0xFEEE0400    0xFEEE0400     0xFEEE0400    0xFEEEFEEE     Win32 heap bookkeeping
    0x00321028  +40    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping
    0x0032102C  +44    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping
    

    Bulk insert with SQLAlchemy ORM

    Direct support was added to SQLAlchemy as of version 0.8

    As per the docs, connection.execute(table.insert().values(data)) should do the trick. (Note that this is not the same as connection.execute(table.insert(), data) which results in many individual row inserts via a call to executemany). On anything but a local connection the difference in performance can be enormous.

    Inline for loop

    you can use enumerate keeping the ind/index of the elements is in vm, if you make vm a set you will also have 0(1) lookups:

    vm = {-1, -1, -1, -1}
    
    print([ind if q in vm else 9999 for ind,ele in enumerate(vm) ])
    

    The module ".dll" was loaded but the entry-point was not found

    I found the answer: I need to add a new application to the service components in my computer and then add the right DLL's.

    Thanks! If anyone has the same problem, I'll be happy to help.

    how to check confirm password field in form without reloading page

    Solution Using jQuery

     <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    
     <style>
        #form label{float:left; width:140px;}
        #error_msg{color:red; font-weight:bold;}
     </style>
    
     <script>
        $(document).ready(function(){
            var $submitBtn = $("#form input[type='submit']");
            var $passwordBox = $("#password");
            var $confirmBox = $("#confirm_password");
            var $errorMsg =  $('<span id="error_msg">Passwords do not match.</span>');
    
            // This is incase the user hits refresh - some browsers will maintain the disabled state of the button.
            $submitBtn.removeAttr("disabled");
    
            function checkMatchingPasswords(){
                if($confirmBox.val() != "" && $passwordBox.val != ""){
                    if( $confirmBox.val() != $passwordBox.val() ){
                        $submitBtn.attr("disabled", "disabled");
                        $errorMsg.insertAfter($confirmBox);
                    }
                }
            }
    
            function resetPasswordError(){
                $submitBtn.removeAttr("disabled");
                var $errorCont = $("#error_msg");
                if($errorCont.length > 0){
                    $errorCont.remove();
                }  
            }
    
    
            $("#confirm_password, #password")
                 .on("keydown", function(e){
                    /* only check when the tab or enter keys are pressed
                     * to prevent the method from being called needlessly  */
                    if(e.keyCode == 13 || e.keyCode == 9) {
                        checkMatchingPasswords();
                    }
                 })
                 .on("blur", function(){                    
                    // also check when the element looses focus (clicks somewhere else)
                    checkMatchingPasswords();
                })
                .on("focus", function(){
                    // reset the error message when they go to make a change
                    resetPasswordError();
                })
    
        });
      </script>
    

    And update your form accordingly:

    <form id="form" name="form" method="post" action="registration.php"> 
        <label for="username">Username : </label>
        <input name="username" id="username" type="text" /></label><br/>
    
        <label for="password">Password :</label> 
        <input name="password" id="password" type="password" /><br/>
    
        <label for="confirm_password">Confirm Password:</label>
        <input type="password" name="confirm_password" id="confirm_password" /><br/>
    
        <input type="submit" name="submit"  value="registration"  />
    </form>
    

    This will do precisely what you asked for:

    • validate that the password and confirm fields are equal without clicking the register button
    • If password and confirm password field will not match it will place an error message at the side of confirm password field and disable registration button

    It is advisable not to use a keyup event listener for every keypress because really you only need to evaluate it when the user is done entering information. If someone types quickly on a slow machine, they may perceive lag as each keystroke will kick off the function.

    Also, in your form you are using labels wrong. The label element has a "for" attribute which should correspond with the id of the form element. This is so that when visually impaired people use a screen reader to call out the form field, it will know text belongs to which field.

    Spring Boot default H2 jdbc connection (and H2 console)

    For Spring Boot 2.3.3.RELEASE straight from Spring Initialzr:

    POM: data jpa, h2, web

    application properties: spring.h2.console.enabled=true

    When you run the application look for line like below in the run console:

    2020-08-18 21:12:32.664  INFO 63256 --- [           main] o.s.b.a.h2.H2ConsoleAutoConfiguration    : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:eaa9d6da-aa2e-4ad3-9e5b-2b60eb2fcbc5'
    

    Now use the above JDBC URL for h2-console and click on Connect.

    Calling another method java GUI

    I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

    public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

    How to access global js variable in AngularJS directive

    I have tried these methods and find that they dont work for my needs. In my case, I needed to inject json rendered server side into the main template of the page, so when it loads and angular inits, the data is already there and doesnt have to be retrieved (large dataset).

    The easiest solution that I have found is to do the following:

    In your angular code outside of the app, module and controller definitions add in a global javascript value - this definition MUST come before the angular stuff is defined.

    Example:

    'use strict';
    
    //my data variable that I need access to.
    var data = null;
    
    angular.module('sample', [])
    

    Then in your controller:

    .controller('SampleApp', function ($scope, $location) {
    
    $scope.availableList = [];
    
    $scope.init = function () {
        $scope.availableList = data;
    }
    

    Finally, you have to init everything (order matters):

      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
      <script src="/path/to/your/angular/js/sample.js"></script>
      <script type="text/javascript">
          data = <?= json_encode($cproducts); ?>
      </script>
    

    Finally initialize your controller and init function.

      <div ng-app="samplerrelations" ng-controller="SamplerApp" ng-init="init();">
    

    By doing this you will now have access to whatever data you stuffed into the global variable.

    Print Pdf in C#

    You can create the PDF document using PdfSharp. It is an open source .NET library.

    When trying to print the document it get worse. I have looked allover for a open source way of doing it. There are some ways do do it using AcroRd32.exe but it all depends on the version, and it cannot be done without acrobat reader staying open.

    I finally ended up using VintaSoftImaging.NET SDK. It costs some money but is much cheaper than the alternative and it solves the problem really easy.

    var doc = new Vintasoft.Imaging.Print.ImagePrintDocument { DocumentName = @"C:\Test.pdf" };
    doc.Print();
    

    That just prints to the default printer without showing. There are several alternatives and options.

    Differences between time complexity and space complexity?

    The way in which the amount of storage space required by an algorithm varies with the size of the problem it is solving. Space complexity is normally expressed as an order of magnitude, e.g. O(N^2) means that if the size of the problem (N) doubles then four times as much working storage will be needed.

    Maven plugins can not be found in IntelliJ

    If an artefact is not resolvable Go in the ditectory of your .m2/repository and check that you DON'T have that kind of file :

    build-helper-maven-plugin-1.10.pom.lastUpdated

    If you don't have any artefact in the folder, just deleted it, and try again to re-import in IntelliJ.

    the content of those file is like :

    #NOTE: This is an Aether internal implementation file, its format can be changed without prior notice.
    #Fri Mar 10 10:36:12 CET 2017
    @default-central-https\://repo.maven.apache.org/maven2/.lastUpdated=1489138572430
    https\://repo.maven.apache.org/maven2/.error=Could not transfer artifact org.codehaus.mojo\:build-helper-maven-plugin\:pom\:1.10 from/to central (https\://repo.maven.apache.org/maven2)\: connect timed out
    

    Without the *.lastUpdated file, IntelliJ (or Eclipse by the way) is enable to reload what is missing.

    How to access array elements in a Django template?

    when you render a request tou coctext some information: for exampel:

    return render(request, 'path to template',{'username' :username , 'email'.email})
    

    you can acces to it on template like this : for variabels :

    {% if username %}{{ username }}{% endif %}
    

    for array :

    {% if username %}{{ username.1 }}{% endif %}
    {% if username %}{{ username.2 }}{% endif %}
    

    you can also name array objects in views.py and ten use it like:

    {% if username %}{{ username.first }}{% endif %}
    

    if there is other problem i wish to help you

    Create a global variable in TypeScript

    I needed to make lodash global to use an existing .js file that I could not change, only require.

    I found that this worked:

    import * as lodash from 'lodash';
    
    (global as any)._ = lodash;
    

    How to do left join in Doctrine?

    If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

    public function getHistory($users) {
        $qb = $this->entityManager->createQueryBuilder();
        $qb
            ->select('a', 'u')
            ->from('Credit\Entity\UserCreditHistory', 'a')
            ->leftJoin('a.user', 'u')
            ->where('u = :user')
            ->setParameter('user', $users)
            ->orderBy('a.created_at', 'DESC');
    
        return $qb->getQuery()->getResult();
    }
    

    Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

    If no association is available, then the query looks like following

    public function getHistory($users) {
        $qb = $this->entityManager->createQueryBuilder();
        $qb
            ->select('a', 'u')
            ->from('Credit\Entity\UserCreditHistory', 'a')
            ->leftJoin(
                'User\Entity\User',
                'u',
                \Doctrine\ORM\Query\Expr\Join::WITH,
                'a.user = u.id'
            )
            ->where('u = :user')
            ->setParameter('user', $users)
            ->orderBy('a.created_at', 'DESC');
    
        return $qb->getQuery()->getResult();
    }
    

    This will produce a resultset that looks like following:

    array(
        array(
            0 => UserCreditHistory instance,
            1 => Userinstance,
        ),
        array(
            0 => UserCreditHistory instance,
            1 => Userinstance,
        ),
        // ...
    )
    

    Creating an array from a text file in Bash

    You can simply read each line from the file and assign it to an array.

    #!/bin/bash
    i=0
    while read line 
    do
            arr[$i]="$line"
            i=$((i+1))
    done < file.txt
    

    Find if current time falls in a time range

    The TimeOfDay property returns a TimeSpan value.

    Try the following code:

    TimeSpan time = DateTime.Now.TimeOfDay;
    
    if (time > new TimeSpan(11, 59, 00)        //Hours, Minutes, Seconds
     && time < new TimeSpan(13, 01, 00)) {
        //match found
    }
    

    Also, new DateTime() is the same as DateTime.MinValue and will always be equal to 1/1/0001 12:00:00 AM. (Value types cannot have non-empty default values) You want to use DateTime.Now.

    Combine two tables that have no common fields

    This is a very strange request, and almost certainly something you'd never want to do in a real-world application, but from a purely academic standpoint it's an interesting challenge. With SQL Server 2005 you could use common table expressions and the row_number() functions and join on that:

    with OrderedFoos as (
        select row_number() over (order by FooName) RowNum, *
        from Foos (nolock)
    ),
    OrderedBars as (
        select row_number() over (order by BarName) RowNum, *
        from Bars (nolock)
    )
    select * 
    from OrderedFoos f
        full outer join OrderedBars u on u.RowNum = f.RowNum
    

    This works, but it's supremely silly and I offer it only as a "community wiki" answer because I really wouldn't recommend it.

    How to use shell commands in Makefile

    With:

    FILES = $(shell ls)
    

    indented underneath all like that, it's a build command. So this expands $(shell ls), then tries to run the command FILES ....

    If FILES is supposed to be a make variable, these variables need to be assigned outside the recipe portion, e.g.:

    FILES = $(shell ls)
    all:
            echo $(FILES)
    

    Of course, that means that FILES will be set to "output from ls" before running any of the commands that create the .tgz files. (Though as Kaz notes the variable is re-expanded each time, so eventually it will include the .tgz files; some make variants have FILES := ... to avoid this, for efficiency and/or correctness.1)

    If FILES is supposed to be a shell variable, you can set it but you need to do it in shell-ese, with no spaces, and quoted:

    all:
            FILES="$(shell ls)"
    

    However, each line is run by a separate shell, so this variable will not survive to the next line, so you must then use it immediately:

            FILES="$(shell ls)"; echo $$FILES
    

    This is all a bit silly since the shell will expand * (and other shell glob expressions) for you in the first place, so you can just:

            echo *
    

    as your shell command.

    Finally, as a general rule (not really applicable to this example): as esperanto notes in comments, using the output from ls is not completely reliable (some details depend on file names and sometimes even the version of ls; some versions of ls attempt to sanitize output in some cases). Thus, as l0b0 and idelic note, if you're using GNU make you can use $(wildcard) and $(subst ...) to accomplish everything inside make itself (avoiding any "weird characters in file name" issues). (In sh scripts, including the recipe portion of makefiles, another method is to use find ... -print0 | xargs -0 to avoid tripping over blanks, newlines, control characters, and so on.)


    1The GNU Make documentation notes further that POSIX make added ::= assignment in 2012. I have not found a quick reference link to a POSIX document for this, nor do I know off-hand which make variants support ::= assignment, although GNU make does today, with the same meaning as :=, i.e., do the assignment right now with expansion.

    Note that VAR := $(shell command args...) can also be spelled VAR != command args... in several make variants, including all modern GNU and BSD variants as far as I know. These other variants do not have $(shell) so using VAR != command args... is superior in both being shorter and working in more variants.

    Changing project port number in Visual Studio 2013

    Steps to resolve this:

    1. Open the solution file.
    2. Find the Port tag against your project name.
    3. Assign any different port as current.
    4. Right click on your project and select Property Pages.
    5. Click on Start Options tab and checked Start URL: option.
    6. Assign the start URL in front of Start URL option like:
      localhost:8080/login.aspx

    Filter Java Stream to 1 and only 1 element

    An alternative is to use reduction: (this example uses strings but could easily apply to any object type including User)

    List<String> list = ImmutableList.of("one", "two", "three", "four", "five", "two");
    String match = list.stream().filter("two"::equals).reduce(thereCanBeOnlyOne()).get();
    //throws NoSuchElementException if there are no matching elements - "zero"
    //throws RuntimeException if duplicates are found - "two"
    //otherwise returns the match - "one"
    ...
    
    //Reduction operator that throws RuntimeException if there are duplicates
    private static <T> BinaryOperator<T> thereCanBeOnlyOne()
    {
        return (a, b) -> {throw new RuntimeException("Duplicate elements found: " + a + " and " + b);};
    }
    

    So for the case with User you would have:

    User match = users.stream().filter((user) -> user.getId() < 0).reduce(thereCanBeOnlyOne()).get();
    

    How can I use Async with ForEach?

    The simple answer is to use the foreach keyword instead of the ForEach() method of List().

    using (DataContext db = new DataLayer.DataContext())
    {
        foreach(var i in db.Groups)
        {
            await GetAdminsFromGroup(i.Gid);
        }
    }
    

    Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

    I actually prefer to use the display name for the placeholder text majority of the time. Here is an example of using the DisplayName:

      @Html.TextBoxFor(x => x.FirstName, true, null, new { @class = "form-control", placeholder = Html.DisplayNameFor(x => x.FirstName) })
    

    How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

    I'll add the data.table version for anyone else Googling it (i.e., @BondedDust's solution translated to data.table and pared down a tad):

    library(data.table)
    setDT(temp)
    temp[ , quartile := cut(value,
                            breaks = quantile(value, probs = 0:4/4),
                            labels = 1:4, right = FALSE)]
    

    Which is much better (cleaner, faster) than what I had been doing:

    temp[ , quartile := 
            as.factor(ifelse(value < quantile(value, .25), 1,
                             ifelse(value < quantile(value, .5), 2,
                                    ifelse(value < quantile(value, .75), 3, 4))]
    

    Note, however, that this approach requires the quantiles to be distinct, e.g. it will fail on rep(0:1, c(100, 1)); what to do in this case is open ended so I leave it up to you.

    What does OpenCV's cvWaitKey( ) function do?

    cvWaitKey(0) stops your program until you press a button.

    cvWaitKey(10) doesn't stop your program but wake up and alert to end your program when you press a button. Its used into loops because cvWaitkey doesn't stop loop.

    Normal use

    char k;
    
    k=cvWaitKey(0);
    
    if(k == 'ESC')
    

    with k you can see what key was pressed.

    What does %>% function mean in R?

    %...% operators

    %>% has no builtin meaning but the user (or a package) is free to define operators of the form %whatever% in any way they like. For example, this function will return a string consisting of its left argument followed by a comma and space and then it's right argument.

    "%,%" <- function(x, y) paste0(x, ", ", y)
    
    # test run
    
    "Hello" %,% "World"
    ## [1] "Hello, World"
    

    The base of R provides %*% (matrix mulitiplication), %/% (integer division), %in% (is lhs a component of the rhs?), %o% (outer product) and %x% (kronecker product). It is not clear whether %% falls in this category or not but it represents modulo.

    expm The R package, expm, defines a matrix power operator %^%. For an example see Matrix power in R .

    operators The operators R package has defined a large number of such operators such as %!in% (for not %in%). See http://cran.r-project.org/web/packages/operators/operators.pdf

    igraph This package defines %--% , %->% and %<-% to select edges.

    lubridate This package defines %m+% and %m-% to add and subtract months and %--% to define an interval. igraph also defines %--% .

    Pipes

    magrittr In the case of %>% the magrittr R package has defined it as discussed in the magrittr vignette. See http://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html

    magittr has also defined a number of other such operators too. See the Additional Pipe Operators section of the prior link which discusses %T>%, %<>% and %$% and http://cran.r-project.org/web/packages/magrittr/magrittr.pdf for even more details.

    dplyr The dplyr R package used to define a %.% operator which is similar; however, it has been deprecated and dplyr now recommends that users use %>% which dplyr imports from magrittr and makes available to the dplyr user. As David Arenburg has mentioned in the comments this SO question discusses the differences between it and magrittr's %>% : Differences between %.% (dplyr) and %>% (magrittr)

    pipeR The R package, pipeR, defines a %>>% operator that is similar to magrittr's %>% and can be used as an alternative to it. See http://renkun.me/pipeR-tutorial/

    The pipeR package also has defined a number of other such operators too. See: http://cran.r-project.org/web/packages/pipeR/pipeR.pdf

    postlogic The postlogic package defined %if% and %unless% operators.

    wrapr The R package, wrapr, defines a dot pipe %.>% that is an explicit version of %>% in that it does not do implicit insertion of arguments but only substitutes explicit uses of dot on the right hand side. This can be considered as another alternative to %>%. See https://winvector.github.io/wrapr/articles/dot_pipe.html

    Bizarro pipe. This is not really a pipe but rather some clever base syntax to work in a way similar to pipes without actually using pipes. It is discussed in http://www.win-vector.com/blog/2017/01/using-the-bizarro-pipe-to-debug-magrittr-pipelines-in-r/ The idea is that instead of writing:

    1:8 %>% sum %>% sqrt
    ## [1] 6
    

    one writes the following. In this case we explicitly use dot rather than eliding the dot argument and end each component of the pipeline with an assignment to the variable whose name is dot (.) . We follow that with a semicolon.

    1:8 ->.; sum(.) ->.; sqrt(.)
    ## [1] 6
    

    Update Added info on expm package and simplified example at top. Added postlogic package.

    What exactly does stringstream do?

    From C++ Primer:

    The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.

    I come across some cases where it is both convenient and concise to use stringstream.

    case 1

    It is from one of the solutions for this leetcode problem. It demonstrates a very suitable case where the use of stringstream is efficient and concise.

    Suppose a and b are complex numbers expressed in string format, we want to get the result of multiplication of a and b also in string format. The code is as follows:

    string a = "1+2i", b = "1+3i";
    istringstream sa(a), sb(b);
    ostringstream out;
    
    int ra, ia, rb, ib;
    char buff;
    // only read integer values to get the real and imaginary part of 
    // of the original complex number
    sa >> ra >> buff >> ia >> buff;
    sb >> rb >> buff >> ib >> buff;
    
    out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';
    
    // final result in string format
    string result = out.str() 
    

    case 2

    It is also from a leetcode problem that requires you to simplify the given path string, one of the solutions using stringstream is the most elegant that I have seen:

    string simplifyPath(string path) {
        string res, tmp;
        vector<string> stk;
        stringstream ss(path);
        while(getline(ss,tmp,'/')) {
            if (tmp == "" or tmp == ".") continue;
            if (tmp == ".." and !stk.empty()) stk.pop_back();
            else if (tmp != "..") stk.push_back(tmp);
        }
        for(auto str : stk) res += "/"+str;
        return res.empty() ? "/" : res; 
     }
    

    Without the use of stringstream, it would be difficult to write such concise code.

    Method to Add new or update existing item in Dictionary

    Old question but i feel i should add the following, even more because .net 4.0 had already launched at the time the question was written.

    Starting with .net 4.0 there is the namespace System.Collections.Concurrent which includes collections that are thread-safe.

    The collection System.Collections.Concurrent.ConcurrentDictionary<> does exactly what you want. It has the AddOrUpdate() method with the added advantage of being thread-safe.

    If you're in a high-performance scenario and not handling multiple threads the already given answers of map[key] = value are faster.

    In most scenarios this performance benefit is insignificant. If so i'd advise to use the ConcurrentDictionary because:

    1. It is in the framework - It is more tested and you are not the one who has to maintain the code
    2. It is scalable: if you switch to multithreading your code is already prepared for it

    What's onCreate(Bundle savedInstanceState)

    onCreate(Bundle) is called when the activity first starts up. You can use it to perform one-time initialization such as creating the user interface. onCreate() takes one parameter that is either null or some state information previously saved by the onSaveInstanceState.

    File Not Found when running PHP with Nginx

    The error message “Primary script unknown or in your case is file not found.” is almost always related to a wrongly set in line SCRIPT_FILENAME in the Nginx fastcgi_param directive (Quote from https://serverfault.com/a/517327/560171).

    In my case, I use Nginx 1.17.10 and my configuration is:

        location ~ \.php$ {
          fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
          fastcgi_index index.php;
          fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
          include fastcgi_params;
          fastcgi_read_timeout 600;
        }
    

    You just change $document_root to $realpath_root, so whatever your root location, like /var/www/html/project/, you don't need write fastcgi_param SCRIPT_FILENAME /var/www/html/project$fastcgi_script_name; each time your root is changes. This configuration is more flexible. May this helps.

    =================================================================================

    For more information, if you got unix:/run/php/php7.2-fpm.sock failed (13: Permission denied) while connecting to upstream, just change in /etc/nginx/nginx.conf, from user nginx; to user www-data;.

    Because the default user and group of PHP-FPM process is www-data as can be seen in /etc/php/7.2/fpm/pool.d/www.conf file (Qoute from https://www.linuxbabe.com/ubuntu/install-nginx-latest-version-ubuntu-18-04):

    user = www-data
    group = www-data
    

    May this information gives a big help

    grep using a character vector with multiple patterns

    Based on Brian Digg's post, here are two helpful functions for filtering lists:

    #Returns all items in a list that are not contained in toMatch
    #toMatch can be a single item or a list of items
    exclude <- function (theList, toMatch){
      return(setdiff(theList,include(theList,toMatch)))
    }
    
    #Returns all items in a list that ARE contained in toMatch
    #toMatch can be a single item or a list of items
    include <- function (theList, toMatch){
      matches <- unique (grep(paste(toMatch,collapse="|"), 
                              theList, value=TRUE))
      return(matches)
    }
    

    How to use pip with python 3.4 on windows?

    I had the same problem when I install python3.5.3. And finally I find the pip.exe in this folder: ~/python/scripts/pip.exe. Hope that help.

    Slide right to left Android Animations

    You can make your own animations. For example create xml file in res/anim like this

    <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"
         android:interpolator="@android:anim/linear_interpolator">
        <translate
                android:fromXDelta="100%p"
                android:toXDelta="0"
                android:startOffset="0"
                android:duration="500"
                /> </set>
    

    Then override animations in selected activity:

       overridePendingTransition(R.anim.animationIN, R.anim.animationOUT);
    

    How to read file binary in C#?

    using (FileStream fs = File.OpenRead(binarySourceFile.Path))
        using (BinaryReader reader = new BinaryReader(fs))
        {              
            // Read in all pairs.
            while (reader.BaseStream.Position != reader.BaseStream.Length)
            {
                Item item = new Item();
                item.UniqueId = reader.ReadString();
                item.StringUnique = reader.ReadString();
                result.Add(item);
            }
        }
        return result;  
    

    How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

    The last argument of CONVERT seems to determine the format used for parsing. Consult MSDN docs for CONVERT.

    111 - the one you are using is Japan yy/mm/dd.

    I guess the one you are looking for is 103, that is dd/mm/yyyy.

    So you should try:

     SELECT convert(datetime, '23/07/2009', 103)
    

    Python check if list items are integers?

    You can use exceptional handling as str.digit will only work for integers and can fail for something like this too:

    >>> str.isdigit(' 1')
    False
    

    Using a generator function:

    def solve(lis):                                        
        for x in lis:
            try:
                yield float(x)
            except ValueError:    
                pass
    
    >>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
    >>> list(solve(mylist))                                    
    [1.0, 2.0, 3.0, 4.0, 1.5, 2.6]   #returns converted values
    

    or may be you wanted this:

    def solve(lis):
        for x in lis:
            try:
                float(x)
                return True
            except:
                return False
    ...         
    >>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
    >>> [x for x in mylist if solve(x)]
    ['1', '2', '3', '4', '1.5', '2.6']
    

    or using ast.literal_eval, this will work for all types of numbers:

    >>> from ast import literal_eval
    >>> def solve(lis):
        for x in lis:
            try:
                literal_eval(x)
                return True
            except ValueError:   
                 return False
    ...         
    >>> mylist=['1','orange','2','3','4','apple', '1.5', '2.6', '1+0j']
    >>> [x for x in mylist if solve(x)]                               
    ['1', '2', '3', '4', '1.5', '2.6', '1+0j']
    

    How to check if an environment variable exists and get its value?

    There is no difference between environment variables and variables in a script. Environment variables are just defined earlier, outside the script, before the script is called. From the script's point of view, a variable is a variable.

    You can check if a variable is defined:

    if [ -z "$a" ]
    then
        echo "not defined"
    else 
        echo "defined"
    fi
    

    and then set a default value for undefined variables or do something else.

    The -z checks for a zero-length (i.e. empty) string. See man bash and look for the CONDITIONAL EXPRESSIONS section.

    You can also use set -u at the beginning of your script to make it fail once it encounters an undefined variable, if you want to avoid having an undefined variable breaking things in creative ways.

    Required attribute HTML5

    Okay. The same time I was writing down my question one of my colleagues made me aware this is actually HTML5 behavior. See http://dev.w3.org/html5/spec/Overview.html#the-required-attribute

    Seems in HTML5 there is a new attribute "required". And Safari 5 already has an implementation for this attribute.

    Removing duplicates from a String in Java

    public class StringTest {
    
        public static String dupRemove(String str) {
    
            Set<Character> s1 = new HashSet<Character>();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < str.length(); i++) {
    
                Character c = str.charAt(i);
    
                if (!s1.contains(c)) {
                    s1.add(c);
                    sb.append(c);
                }
    
    
            }
    
            System.out.println(sb.toString());
    
            return sb.toString();
    
        }
    
        public static void main(String[] args) {
    
            dupRemove("AAAAAAAAAAAAAAAAA BBBBBBBB");
        }
    
    }
    

    Bootstrap Collapse not Collapsing

    You need jQuery see bootstrap's basic template

    Zero-pad digits in string

    Solution using str_pad:

    str_pad($digit,2,'0',STR_PAD_LEFT);
    

    Benchmark on php 5.3

    Result str_pad : 0.286863088608

    Result sprintf : 0.234171152115

    Code:

    $start = microtime(true);
    for ($i=0;$i<100000;$i++) {
        str_pad(9,2,'0',STR_PAD_LEFT);
        str_pad(15,2,'0',STR_PAD_LEFT);
        str_pad(100,2,'0',STR_PAD_LEFT);
    }
    $end = microtime(true);
    echo "Result str_pad : ",($end-$start),"\n";
    
    $start = microtime(true);
    for ($i=0;$i<100000;$i++) {
        sprintf("%02d", 9);
        sprintf("%02d", 15);
        sprintf("%02d", 100);
    }
    $end = microtime(true);
    echo "Result sprintf : ",($end-$start),"\n";
    

    Threading Example in Android

    One of Androids powerful feature is the AsyncTask class.

    To work with it, you have to first extend it and override doInBackground(...). doInBackground automatically executes on a worker thread, and you can add some listeners on the UI Thread to get notified about status update, those functions are called: onPreExecute(), onPostExecute() and onProgressUpdate()

    You can find a example here.

    Refer to below post for other alternatives:

    Handler vs AsyncTask vs Thread

    Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

    The Bootstrap Collapse has some Events that you can react to:

    $(document).ready(function(){    
        $('#accordProfile').on('shown', function () {
           $(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-up");
        });
    
        $('#accordProfile').on('hidden', function () {
           $(".icon-chevron-up").removeClass("icon-chevron-up").addClass("icon-chevron-down");
        });
    });
    

    How to remove rows with any zero value

    There are a few different ways of doing this. I prefer using apply, since it's easily extendable:

    ##Generate some data
    dd = data.frame(a = 1:4, b= 1:0, c=0:3)
    
    ##Go through each row and determine if a value is zero
    row_sub = apply(dd, 1, function(row) all(row !=0 ))
    ##Subset as usual
    dd[row_sub,]
    

    Safest way to convert float to integer in python?

    Use int(your non integer number) will nail it.

    print int(2.3) # "2"
    print int(math.sqrt(5)) # "2"
    

    Most simple code to populate JTable from ResultSet

    I think the simplest way to build a model from an instance of ResultSet, could be as follows.

    public static void main(String[] args) throws Exception {
        // The Connection is obtained
    
        ResultSet rs = stmt.executeQuery("select * from product_info");
    
        // It creates and displays the table
        JTable table = new JTable(buildTableModel(rs));
    
        // Closes the Connection
    
        JOptionPane.showMessageDialog(null, new JScrollPane(table));
    
    }
    

    The method buildTableModel:

    public static DefaultTableModel buildTableModel(ResultSet rs)
            throws SQLException {
    
        ResultSetMetaData metaData = rs.getMetaData();
    
        // names of columns
        Vector<String> columnNames = new Vector<String>();
        int columnCount = metaData.getColumnCount();
        for (int column = 1; column <= columnCount; column++) {
            columnNames.add(metaData.getColumnName(column));
        }
    
        // data of the table
        Vector<Vector<Object>> data = new Vector<Vector<Object>>();
        while (rs.next()) {
            Vector<Object> vector = new Vector<Object>();
            for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
                vector.add(rs.getObject(columnIndex));
            }
            data.add(vector);
        }
    
        return new DefaultTableModel(data, columnNames);
    
    }
    

    UPDATE

    Do you like to use javax.swing.SwingWorker? Do you like to use the try-with-resources statement?

    public class GUI extends JFrame {
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new GUI().setVisible(true);
                }
            });
        }
    
        private final JButton button;
        private final JTable table;
        private final DefaultTableModel tableModel = new DefaultTableModel();
    
        public GUI() throws HeadlessException {
    
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
            table = new JTable(tableModel);
            add(new JScrollPane(table), BorderLayout.CENTER);
    
            button = new JButton("Load Data");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    new SwingWorker<Void, Void>() {
                        @Override
                        protected Void doInBackground() throws Exception {
                            loadData();
                            return null;
                        }
                    }.execute();
                }
            });
            add(button, BorderLayout.PAGE_START);
    
            setSize(640, 480);
        }
    
        private void loadData() {
            LOG.info("START loadData method");
    
            button.setEnabled(false);
    
            try (Connection conn = DriverManager.getConnection(url, usr, pwd);
                    Statement stmt = conn.createStatement()) {
    
                ResultSet rs = stmt.executeQuery("select * from customer");
                ResultSetMetaData metaData = rs.getMetaData();
    
                // Names of columns
                Vector<String> columnNames = new Vector<String>();
                int columnCount = metaData.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    columnNames.add(metaData.getColumnName(i));
                }
    
                // Data of the table
                Vector<Vector<Object>> data = new Vector<Vector<Object>>();
                while (rs.next()) {
                    Vector<Object> vector = new Vector<Object>();
                    for (int i = 1; i <= columnCount; i++) {
                        vector.add(rs.getObject(i));
                    }
                    data.add(vector);
                }
    
                tableModel.setDataVector(data, columnNames);
            } catch (Exception e) {
                LOG.log(Level.SEVERE, "Exception in Load Data", e);
            }
            button.setEnabled(true);
    
            LOG.info("END loadData method");
        }
    
    }
    

    How to force a web browser NOT to cache images

    Simple fix: Attach a random query string to the image:

    <img src="foo.cgi?random=323527528432525.24234" alt="">
    

    What the HTTP RFC says:

    Cache-Control: no-cache
    

    But that doesn't work that well :)

    Best Practices for securing a REST API / web service

    OWASP(Open Web Application Security Project) has some cheat sheets covering about all aspects of Web Application development. This Project is a very valuable and reliable source of information. Regarding REST services you can check this: https://www.owasp.org/index.php/REST_Security_Cheat_Sheet

    How can I find the product GUID of an installed MSI setup?

    There is also a very helpful GUI tool called Product Browser which appears to be made by Microsoft or at least an employee of Microsoft.

    It can be found on Github here Product Browser

    I personally had a very easy time locating the GUID I needed with this.

    Java: How to convert a File object to a String object in java?

    You can copy all contents of myhtml to String as follows:

    Scanner myScanner = null;
    try
    {
        myScanner = new Scanner(myhtml);
        String contents = myScanner.useDelimiter("\\Z").next(); 
    }
    finally
    {
        if(myScanner != null)
        {
            myScanner.close(); 
        }
    }
    

    Ofcourse, you can add a catch block to handle exceptions properly.

    Angularjs - simple form submit

    Sending data to some service page.

    <form class="form-horizontal" role="form" ng-submit="submit_form()">
        <input type="text" name="user_id" ng-model = "formAdata.user_id">
        <input type="text" id="name" name="name" ng-model = "formAdata.name">
    </form>
    
    $scope.submit_form = function()
                {
                    $http({
                            url: "http://localhost/services/test.php",
                            method: "POST",
                            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                            data: $.param($scope.formAdata)
                        }).success(function(data, status, headers, config) {
                            $scope.status = status;
                        }).error(function(data, status, headers, config) {
                            $scope.status = status;
                        });
                }
    

    What's the @ in front of a string in C#?

    This is a verbatim string, and changes the escaping rules - the only character that is now escaped is ", escaped to "". This is especially useful for file paths and regex:

    var path = @"c:\some\location";
    var tsql = @"SELECT *
                FROM FOO
                WHERE Bar = 1";
    var escaped = @"a "" b";
    

    etc

    How do I skip an iteration of a `foreach` loop?

    foreach ( int number in numbers )
    {
        if ( number < 0 )
        {
            continue;
        }
    
        //otherwise process number
    }
    

    Visual studio code terminal, how to run a command with administrator rights?

    Running as admin didn't help me. (also got errors with syscall: rename)

    Turns out this error can also occur if files are locked by Windows.

    This can occur if :

    • You are actually running the project
    • You have files open in both Visual Studio and VSCode.

    Running as admin doesn't get around windows file locking.

    I created a new project in VS2017 and then switched to VSCode to try to add more packages. After stopping the project from running and closing VS2017 it was able to complete without error

    Disclaimer: I'm not exactly sure if this means running as admin isn't necessary, but try to avoid it if possible to avoid the possibility of some rogue package doing stuff it isn't meant to.

    JetBrains / IntelliJ keyboard shortcut to collapse all methods

    You Can Go To setting > editor > general > code folding and check "show code folding outline" .