Programs & Examples On #Poset

Flex-box: Align last row to grid

Assuming:

  • You want 4 column grid layout with wrapping
  • The number of items is not necessarily a multiple of 4

Set a left margin on every item except 1st, 5th and 9th item and so on. If the left margin is 10px then each row will have 30px margin distributed among 4 items. The percentage width for item is calculated as follows:

100% / 4 - horizontal-border - horizontal-padding - left-margin * (4 - 1) / 4

This is a decent workaround for issues involving last row of flexbox.

_x000D_
_x000D_
.flex {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  flex-wrap: wrap;_x000D_
  margin: 1em 0 3em;_x000D_
  background-color: peachpuff;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  margin-left: 10px;_x000D_
  border: 1px solid;_x000D_
  padding: 10px;_x000D_
  width: calc(100% / 4 - 2px - 20px - 10px * (4 - 1) / 4);_x000D_
  background-color: papayawhip;_x000D_
}_x000D_
_x000D_
.item:nth-child(4n + 1) {_x000D_
  margin-left: 0;_x000D_
}_x000D_
_x000D_
.item:nth-child(n + 5) {_x000D_
  margin-top: 10px;_x000D_
}
_x000D_
<div class="flex">_x000D_
  <div class="item">1</div>_x000D_
  <div class="item">2</div>_x000D_
  <div class="item">3</div>_x000D_
  <div class="item">4</div>_x000D_
</div>_x000D_
<div class="flex">_x000D_
  <div class="item">1</div>_x000D_
  <div class="item">2</div>_x000D_
  <div class="item">3</div>_x000D_
  <div class="item">4</div>_x000D_
  <div class="item">5</div>_x000D_
  <div class="item">6</div>_x000D_
</div>_x000D_
<div class="flex">_x000D_
  <div class="item">1</div>_x000D_
  <div class="item">2</div>_x000D_
  <div class="item">3</div>_x000D_
  <div class="item">4</div>_x000D_
  <div class="item">5</div>_x000D_
  <div class="item">6</div>_x000D_
  <div class="item">7</div>_x000D_
  <div class="item">8</div>_x000D_
  <div class="item">9</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Eclipse keyboard shortcut to indent source code to the left?

For Left indent Shift + Tab

For Right indent simple Tab

How do I obtain a list of all schemas in a Sql Server database

SELECT s.name + '.' + ao.name
       , s.name
FROM sys.all_objects ao
INNER JOIN sys.schemas s ON s.schema_id = ao.schema_id
WHERE ao.type='u';

Get the current fragment object

If you are defining the fragment in the activity's XML layour then in the Activity make sure you call setContentView() before calling findFragmentById().

This project references NuGet package(s) that are missing on this computer

In my case, I had to remove the following from the .csproj file:

<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
  <PropertyGroup>
    <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
  </PropertyGroup>
  <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>

In fact, in this snippet you can see where the error message is coming from.

I was converting from MSBuild-Integrated Package Restore to Automatic Package Restore (http://docs.nuget.org/docs/workflows/migrating-to-automatic-package-restore)

Delete the last two characters of the String

It was almost correct just change your last line like:

String stopEnd = stop.substring(0, stop.length() - 1); //replace stopName with stop.

OR

you can replace your last two lines;

String stopEnd =   stopName.substring(0, stopName.length() - 2);

Resizing an image in an HTML5 canvas

Try pica - that's a highly optimized resizer with selectable algorythms. See demo.

For example, original image from first post is resized in 120ms with Lanczos filter and 3px window or 60ms with Box filter and 0.5px window. For huge 17mb image 5000x3000px resize takes ~1s on desktop and 3s on mobile.

All resize principles were described very well in this thread, and pica does not add rocket science. But it's optimized very well for modern JIT-s, and is ready to use out of box (via npm or bower). Also, it use webworkers when available to avoid interface freezes.

I also plan to add unsharp mask support soon, because it's very useful after downscale.

How to use index in select statement?

If you want to test the index to see if it works, here is the syntax:

SELECT *
FROM Table WITH(INDEX(Index_Name))

The WITH statement will force the index to be used.

Differences between Microsoft .NET 4.0 full Framework and Client Profile

A list of assemblies is available at Assemblies in the .NET Framework Client Profile on MSDN (the list is too long to include here).

If you're more interested in features, .NET Framework Client Profile on MSDN lists the following as being included:

  • common language runtime (CLR)
  • ClickOnce
  • Windows Forms
  • Windows Presentation Foundation (WPF)
  • Windows Communication Foundation (WCF)
  • Entity Framework
  • Windows Workflow Foundation
  • Speech
  • XSLT support
  • LINQ to SQL
  • Runtime design libraries for Entity Framework and WCF Data Services
  • Managed Extensibility Framework (MEF)
  • Dynamic types
  • Parallel-programming features, such as Task Parallel Library (TPL), Parallel LINQ (PLINQ), and Coordination Data Structures (CDS)
  • Debugging client applications

And the following as not being included:

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

How do I perform the SQL Join equivalent in MongoDB?

$lookup (aggregation)

Performs a left outer join to an unsharded collection in the same database to filter in documents from the “joined” collection for processing. To each input document, the $lookup stage adds a new array field whose elements are the matching documents from the “joined” collection. The $lookup stage passes these reshaped documents to the next stage. The $lookup stage has the following syntaxes:

Equality Match

To perform an equality match between a field from the input documents with a field from the documents of the “joined” collection, the $lookup stage has the following syntax:

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

The operation would correspond to the following pseudo-SQL statement:

SELECT *, <output array field>
FROM collection
WHERE <output array field> IN (SELECT <documents as determined from the pipeline>
                               FROM <collection to join>
                               WHERE <pipeline> );

Mongo URL

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

For code . to work in OSX terminal append code as described here https://code.visualstudio.com/Docs/setup but instead of to .bashrc, in OSX try .profile which is loaded at terminal session start.

How to prevent long words from breaking my div?

Two fixes:

  1. overflow:scroll -- this makes sure your content can be seen at the cost of design (scrollbars are ugly)
  2. overflow:hidden -- just cuts off any overflow. It means people can't read the content though.

If (in the SO example) you want to stop it overlapping the padding, you'd probably have to create another div, inside the padding, to hold your content.

Edit: As the other answers state, there are a variety of methods for truncating the words, be that working out the render width on the client side (never attempt to do this server-side as it will never work reliably, cross platform) through JS and inserting break-characters, or using non-standard and/or wildly incompatible CSS tags (word-wrap: break-word doesn't appear to work in Firefox).

You will always need an overflow descriptor though. If your div contains another too-wide block-type piece of content (image, table, etc), you'll need overflow to make it not destroy the layout/design.

So by all means use another method (or a combination of them) but remember to add overflow too so you cover all browsers.

Edit 2 (to address your comment below):

Start off using the CSS overflow property isn't perfect but it stops designs breaking. Apply overflow:hidden first. Remember that overflow might not break on padding so either nest divs or use a border (whatever works best for you).

This will hide overflowing content and therefore you might lose meaning. You could use a scrollbar (using overflow:auto or overflow:scroll instead of overflow:hidden) but depending on the dimensions of the div, and your design, this might not look or work great.

To fix it, we can use JS to pull things back and do some form of automated truncation. I was half-way through writing out some pseudo code for you but it gets seriously complicated about half-way through. If you need to show as much as possible, give hyphenator a look in (as mentioned below).

Just be aware that this comes at the cost of user's CPUs. It could result in pages taking a long time to load and/or resize.

Calling stored procedure from another stored procedure SQL Server

First of all, if table2's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT on that table

SET IDENTITY_INSERT table2 ON;

before the insert.

So one of two, you modify your second stored and call it with only the parameters productName and productDescription and then get the new ID

EXEC test2 'productName', 'productDescription'
SET @newID = SCOPE_IDENTIY()

or you already have the ID of the product and you don't need to call SCOPE_IDENTITY() and can make the insert on table1 with that ID

String variable interpolation Java

If you're using Java 5 or higher, you can use String.format:

urlString += String.format("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4);

See Formatter for details.

PHP shell_exec() vs exec()

shell_exec returns all of the output stream as a string. exec returns the last line of the output by default, but can provide all output as an array specifed as the second parameter.

See

Splitting a table cell into two columns in HTML

is that what your looking for?

<table border="1">
<tr>
 <th scope="col">Header</th>
 <th scope="col">Header</th>
 <th scope="col" colspan="2">Header</th>
</tr>
<tr>
 <th scope="row">&nbsp;</th>
 <td>&nbsp;</td>
 <td>Split this one</td>
 <td>into two columns</td>
</tr>
</table>  

Why does PEP-8 specify a maximum line length of 79 characters?

Since whitespace has semantic meaning in Python, some methods of word wrapping could produce incorrect or ambiguous results, so there needs to be some limit to avoid those situations. An 80 character line length has been standard since we were using teletypes, so 79 characters seems like a pretty safe choice.

How do I find out my python path using python?

import subprocess
python_path = subprocess.check_output("which python", shell=True).strip()
python_path = python_path.decode('utf-8')

JavaScript: get code to run every minute

You could use setInterval for this.

<script type="text/javascript">
function myFunction () {
    console.log('Executed!');
}

var interval = setInterval(function () { myFunction(); }, 60000);
</script>

Disable the timer by setting clearInterval(interval).

See this Fiddle: http://jsfiddle.net/p6NJt/2/

Installation of VB6 on Windows 7 / 8 / 10

VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.

Here is how to install it:

  • Before proceeding with the installation process below, create a zero-byte file in C:\Windows called MSJAVA.DLL. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.
  • Turn off UAC.
  • Insert Visual Studio 6 CD.
  • Exit from the Autorun setup.
  • Browse to the root folder of the VS6 CD.
  • Right-click SETUP.EXE, select Run As Administrator.
  • On this and other Program Compatibility Assistant warnings, click Run Program.
  • Click Next.
  • Click "I accept agreement", then Next.
  • Enter name and company information, click Next.
  • Select Custom Setup, click Next.
  • Click Continue, then Ok.
  • Setup will "think to itself" for about 2 minutes. Processing can be verified by starting Task Manager, and checking the CPU usage of ACMSETUP.EXE.
  • On the options list, select the following:
    • Microsoft Visual Basic 6.0
    • ActiveX
    • Data Access
    • Graphics
    • All other options should be unchecked.
  • Click Continue, setup will continue.
  • Finally, a successful completion dialog will appear, at which click Ok. At this point, Visual Basic 6 is installed.
  • If you do not have the MSDN CD, clear the checkbox on the next dialog, and click next. You'll be warned of the lack of MSDN, but just click Yes to accept.
  • Click Next to skip the installation of Installshield. This is a really old version you don't want anyway.
  • Click Next again to skip the installation of BackOffice, VSS, and SNA Server. Not needed!
  • On the next dialog, clear the checkbox for "Register Now", and click Finish.
  • The wizard will exit, and you're done. You can find VB6 under Start, All Programs, Microsoft Visual Studio 6. Enjoy!
  • Turn On UAC again

  • You might notice after successfully installing VB6 on Windows 7 that working in the IDE is a bit, well, sluggish. For example, resizing objects on a form is a real pain.
  • After installing VB6, you'll want to change the compatibility settings for the IDE executable.
  • Using Windows Explorer, browse the location where you installed VB6. By default, the path is C:\Program Files\Microsoft Visual Studio\VB98\
  • Right click the VB6.exe program file, and select properties from the context menu.
  • Click on the Compatibility tab.
  • Place a check in each of these checkboxes:
  • Run this program in compatibility mode for Windows XP (Service Pack 3)
    • Disable Visual Themes
    • Disable Desktop Composition
    • Disable display scaling on high DPI settings
    • If you have UAC turned on, it is probably advisable to check the 'Run this program as an Administrator' box

After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.

Edit: Updated dead link to point to a different page with the same instructions

Edit: Updated the answer with the actual instructions in the post as the link kept dying

C++ Remove new line from multiline string

If the newline is expected to be at the end of the string, then:

if (!s.empty() && s[s.length()-1] == '\n') {
    s.erase(s.length()-1);
}

If the string can contain many newlines anywhere in the string:

std::string::size_type i = 0;
while (i < s.length()) {
    i = s.find('\n', i);
    if (i == std::string:npos) {
        break;
    }
    s.erase(i);
}

How should I use try-with-resources with JDBC?

Here is a concise way using lambdas and JDK 8 Supplier to fit everything in the outer try:

try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
    PreparedStatement stmt = ((Supplier<PreparedStatement>)() -> {
    try {
        PreparedStatement s = con.prepareStatement("SELECT userid, name, features FROM users WHERE userid = ?");
        s.setInt(1, userid);
        return s;
    } catch (SQLException e) { throw new RuntimeException(e); }
    }).get();
    ResultSet resultSet = stmt.executeQuery()) {
}

Get User Selected Range

Selection is its own object within VBA. It functions much like a Range object.

Selection and Range do not share all the same properties and methods, though, so for ease of use it might make sense just to create a range and set it equal to the Selection, then you can deal with it programmatically like any other range.

Dim myRange as Range
Set myRange = Selection

For further reading, check out the MSDN article.

Angular JS break ForEach

$scope.arr = [0, 1, 2];  
$scope.dict = {}
for ( var i=0; i < $scope.arr.length; i++ ) {
    if ( $scope.arr[i] == 1 ) {
        $scope.exists = 'yes, 1 exists';
        break;
    }
 }
 if ( $scope.exists ) {
     angular.forEach ( $scope.arr, function ( value, index ) {
                      $scope.dict[index] = value;
     });
 }

How to convert JSON to XML or XML to JSON?

Thanks for David Brown's answer. In my case of JSON.Net 3.5, the convert methods are under the JsonConvert static class:

XmlNode myXmlNode = JsonConvert.DeserializeXmlNode(myJsonString); // is node not note
// or .DeserilizeXmlNode(myJsonString, "root"); // if myJsonString does not have a root
string jsonString = JsonConvert.SerializeXmlNode(myXmlNode);

Convert a number range to another range, maintaining ratio

I used this solution in a problem I was solving in js, so I thought I would share the translation. Thanks for the explanation and solution.

function remap( x, oMin, oMax, nMin, nMax ){
//range check
if (oMin == oMax){
    console.log("Warning: Zero input range");
    return None;
};

if (nMin == nMax){
    console.log("Warning: Zero output range");
    return None
}

//check reversed input range
var reverseInput = false;
oldMin = Math.min( oMin, oMax );
oldMax = Math.max( oMin, oMax );
if (oldMin != oMin){
    reverseInput = true;
}

//check reversed output range
var reverseOutput = false;  
newMin = Math.min( nMin, nMax )
newMax = Math.max( nMin, nMax )
if (newMin != nMin){
    reverseOutput = true;
};

var portion = (x-oldMin)*(newMax-newMin)/(oldMax-oldMin)
if (reverseInput){
    portion = (oldMax-x)*(newMax-newMin)/(oldMax-oldMin);
};

var result = portion + newMin
if (reverseOutput){
    result = newMax - portion;
}

return result;
}

Python DNS module import error

I faced the same problem and solved this like i described below: As You have downloaded and installed dnspython successfully so

  1. Enter into folder dnspython
  2. You will find dns directory, now copy it
  3. Then paste it to inside site-packages directory

That's all. Now your problem will go

If dnspython isn't installed you can install it this way :

  1. go to your python installation folder site-packages directory
  2. open cmd here and enter the command : pip install dnspython

Now, dnspython will be installed successfully.

How to export data with Oracle SQL Developer?

In version 3, they changed "export" to "unload". It still functions more or less the same.

Can you blur the content beneath/behind a div?

you can do this with css3, this blurs the whole element

div (or whatever element) {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}

Fiddle: http://jsfiddle.net/H4DU4/

Open local folder from link

Linking to local resources is disabled in all modern browsers due to security restrictions.

For Firefox:

For security purposes, Mozilla applications block links to local files (and directories) from remote files. This includes linking to files on your hard drive, on mapped network drives, and accessible via Uniform Naming Convention (UNC) paths. This prevents a number of unpleasant possibilities, including:

  • Allowing sites to detect your operating system by checking default installation paths
  • Allowing sites to exploit system vulnerabilities (e.g., C:\con\con in Windows 95/98)
  • Allowing sites to detect browser preferences or read sensitive data

for IE:

Internet Explorer 6 Service Pack 1 (SP1) no longer allows browsing a local machine from the Internet zone. For instance, if an Internet site contains a link to a local file, Internet Explorer 6 SP1 displays a blank page when a user clicks on the link. Previous versions of Windows Internet Explorer followed the link to the local file.

for Opera (in the context of a security advisory, I'm sure there is a more canonical link for this):

As a security precaution, Opera does not allow Web pages to link to files on the user's local disk

How do you select the entire excel sheet with Range using VBA?

Another way to select all cells within a range, as long as the data is contiguous, is to use Range("A1", Range("A1").End(xlDown).End(xlToRight)).Select.

Remove Top Line of Text File with PowerShell

Another approach to remove the first line from file, using multiple assignment technique. Refer Link

 $firstLine, $restOfDocument = Get-Content -Path $filename 
 $modifiedContent = $restOfDocument 
 $modifiedContent | Out-String | Set-Content $filename

How to convert View Model into JSON object in ASP.NET MVC?

In mvc3 with razor @Html.Raw(Json.Encode(object)) seems to do the trick.

Creating all possible k combinations of n items in C++

Here is an algorithm i came up with for solving this problem. You should be able to modify it to work with your code.

void r_nCr(const unsigned int &startNum, const unsigned int &bitVal, const unsigned int &testNum) // Should be called with arguments (2^r)-1, 2^(r-1), 2^(n-1)
{
    unsigned int n = (startNum - bitVal) << 1;
    n += bitVal ? 1 : 0;

    for (unsigned int i = log2(testNum) + 1; i > 0; i--) // Prints combination as a series of 1s and 0s
        cout << (n >> (i - 1) & 1);
    cout << endl;

    if (!(n & testNum) && n != startNum)
        r_nCr(n, bitVal, testNum);

    if (bitVal && bitVal < testNum)
        r_nCr(startNum, bitVal >> 1, testNum);
}

You can see an explanation of how it works here.

Input type number "only numeric value" validation

You need to use regular expressions in your custom validator. For example, here's the code that allows only 9 digits in the input fields:

function ssnValidator(control: FormControl): {[key: string]: any} {
  const value: string = control.value || '';
  const valid = value.match(/^\d{9}$/);
  return valid ? null : {ssn: true};
}

Take a look at a sample app here:

https://github.com/Farata/angular2typescript/tree/master/Angular4/form-samples/src/app/reactive-validator

Select From all tables - MySQL

As Suhel Meman said in the comments:

SELECT column1, column2, column3 FROM table 1
UNION
SELECT column1, column2, column3 FROM table 2
...

would work.

But all your SELECTS would have to consist of the same amount of columns. And because you are displaying it in one resulting table they should contain the same information.

What you might want to do, is a JOIN on Product ID or something like that. This way you would get more columns, which makes more sense most of the time.

Clear dropdown using jQuery Select2

This is the proper one, select2 will clear the selected value and show the placeholder back .

$remote.select2('data', null)

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

Oracle's security model is such that when executing dynamic SQL using Execute Immediate (inside the context of a PL/SQL block or procedure), the user does not have privileges to objects or commands that are granted via role membership. Your user likely has "DBA" role or something similar. You must explicitly grant "drop table" permissions to this user. The same would apply if you were trying to select from tables in another schema (such as sys or system) - you would need to grant explicit SELECT privileges on that table to this user.

Change all files and folders permissions of a directory to 644/755

Do both in a single pass with:

find -type f ... -o -type d ...

As in, find type f OR type d, and do the first ... for files and the second ... for dirs. Specifically:

find -type f -exec chmod --changes 644 {} + -o -type d -exec chmod --changes 755 {} +

Leave off the --changes if you want it to work silently.

Form Submit jQuery does not work

Since every control element gets referenced with its name on the form element (see forms specs), controls with name "submit" will override the build-in submit function.

Which leads to the error mentioned in comments above:

Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function

As in the accepted answer above the simplest solution would be to change the name of that control element.

However another solution could be to use dispatchEvent method on form element:

$("#form_id")[0].dispatchEvent(new Event('submit')); 

sqlalchemy: how to join several tables by one query?

Try this

q = Session.query(
         User, Document, DocumentPermissions,
    ).filter(
         User.email == Document.author,
    ).filter(
         Document.name == DocumentPermissions.document,
    ).filter(
        User.email == 'someemail',
    ).all()

How Should I Set Default Python Version In Windows?

Now that Python 3.3 is released it is easiest to use the py.exe utility described here: http://www.python.org/dev/peps/pep-0397/

It allows you to specify a Python version in your script file using a UNIX style directive. There are also command line and environment variable options for controlling which version of Python is run.

The easiest way to get this utility is to install Python 3.3 or later.

How to check that a string is parseable to a double?

Google's Guava library provides a nice helper method to do this: Doubles.tryParse(String). You use it like Double.parseDouble but it returns null rather than throwing an exception if the string does not parse to a double.

Bootstrap 4 Dropdown Menu not working?

Assuming Bootstrap and Popper libraries were installed using Nuget package manager, for a web application using Visual Studio, in the Master page file (Site.Master), right below where body tag begins, include the reference to popper.min.js by typing:

<script src="Scripts/umd/popper.min.js"></script>

Here is an image to better display the location:

enter image description here

Notice the reference of the popper library to be added should be the one inside umd folder and not the one outside on Scripts folder.

This should fix the problem.

What is the syntax meaning of RAISERROR()

16 is severity and 1 is state, more specifically following example might give you more detail on syntax and usage:

BEGIN TRY
    -- RAISERROR with severity 11-19 will cause execution to 
    -- jump to the CATCH block.
    RAISERROR ('Error raised in TRY block.', -- Message text.
               16, -- Severity.
               1 -- State.
               );
END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;

You can follow and try out more examples from http://msdn.microsoft.com/en-us/library/ms178592.aspx

C# looping through an array

Not too difficult. Just increment the counter of the for loop by 3 each iteration and then offset the indexer to get the batch of 3 at a time:

for(int i=0; i < theData.Length; i+=3)
{
    var item1 = theData[i];
    var item2 = theData[i+1];
    var item3 = theData[i+2];
}

If the length of the array wasn't garuanteed to be a multiple of three, you would need to check the upper bound with theData.Length - 2 instead.

No newline after div?

<div style="display: inline">Is this what you meant?</div>

Android SharedPreferences in Fragment

To define the preference in Fragment: SharedPreferences pref = getActivity().getSharedPreferences("CargaDatosCR",Context.MODE_PRIVATE); editor.putString("credi_credito",cre); editor.commit();

To call another activity or fragment the preference data: SharedPreferences pref = getActivity().getSharedPreferences("CargaDatosCR", Context.MODE_PRIVATE); credit=pref.getString("credi_credito",""); if(credit.isNotEmpty)...

Make virtualenv inherit specific packages from your global site-packages

Create the environment with virtualenv --system-site-packages . Then, activate the virtualenv and when you want things installed in the virtualenv rather than the system python, use pip install --ignore-installed or pip install -I . That way pip will install what you've requested locally even though a system-wide version exists. Your python interpreter will look first in the virtualenv's package directory, so those packages should shadow the global ones.

How do I get the picture size with PIL?

This is a complete example loading image from URL, creating with PIL, printing the size and resizing...

import requests
h = { 'User-Agent': 'Neo'}
r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)

from PIL import Image
from io import BytesIO
# create image from binary content
i = Image.open(BytesIO(r.content))


width, height = i.size
print(width, height)
i = i.resize((100,100))
display(i)

How to hide underbar in EditText

If you are using the EditText inside TextInputLayout use app:boxBackgroundMode="none" as following:

<com.google.android.material.textfield.TextInputLayout
    app:boxBackgroundMode="none"
    ...
    >

    <EditText
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</com.google.android.material.textfield.TextInputLayout>

add elements to object array

You can try

Subject[] subjects = new Subject[2];
subjects[0] = new Subject{....};
subjects[1] = new Subject{....};

alternatively you can use List

List<Subject> subjects = new List<Subject>();
subjects.add(new Subject{....});
subjects.add(new Subject{....});

Create a Maven project in Eclipse complains "Could not resolve archetype"

I fixed this problem by following the solution to this other StackOverflow question

I had the same problem. I fixed it by adding the maven archetype catalog to eclipse. Steps are provided below: (Please note the https protocol)

  1. Open Window > Preferences
  2. Open Maven > Archetypes
  3. Click 'Add Remote Catalog' and add the following:

How to select an element inside "this" in jQuery?

I use this to get the Parent, similarly for child

$( this ).children( 'li.target' ).css("border", "3px double red");

Good Luck

ASP.NET MVC - passing parameters to the controller

Using the ASP.NET Core Tag Helper feature:

<a asp-controller="Home" asp-action="SetLanguage" asp-route-yourparam1="@item.Value">@item.Text</a>

Git pull - Please move or remove them before you can merge

I just faced the same issue and solved it using the following.First clear tracked files by using :

git clean -d -f

then try git pull origin master

You can view other git clean options by typing git clean -help

C compile : collect2: error: ld returned 1 exit status

If you are using Dev C++ then your .exe or mean to say your program already running and you are trying to run it again.

How is a JavaScript hash map implemented?

Here is an easy and convenient way of using something similar to the Java map:

var map= {
    'map_name_1': map_value_1,
    'map_name_2': map_value_2,
    'map_name_3': map_value_3,
    'map_name_4': map_value_4
    }

And to get the value:

alert( map['map_name_1'] );    // fives the value of map_value_1

......  etc  .....

How to use Select2 with JSON via Ajax request?

for select2 v4.0.0 slightly different

$(".itemSearch").select2({
    tags: true,
    multiple: true,
    tokenSeparators: [',', ' '],
    minimumInputLength: 2,
    minimumResultsForSearch: 10,
    ajax: {
        url: URL,
        dataType: "json",
        type: "GET",
        data: function (params) {

            var queryParameters = {
                term: params.term
            }
            return queryParameters;
        },
        processResults: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.tag_value,
                        id: item.tag_id
                    }
                })
            };
        }
    }
});

Getting an error "fopen': This function or variable may be unsafe." when compling

This is not an error, it is a warning from your Microsoft compiler.

Select your project and click "Properties" in the context menu.

In the dialog, chose Configuration Properties -> C/C++ -> Preprocessor

In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS to turn those warnings off.

How do I find the authoritative name-server for a domain name?

You'll want the SOA (Start of Authority) record for a given domain name, and this is how you accomplish it using the universally available nslookup command line tool:

command line> nslookup
> set querytype=soa
> stackoverflow.com
Server:         217.30.180.230
Address:        217.30.180.230#53

Non-authoritative answer:
stackoverflow.com
        origin = ns51.domaincontrol.com # ("primary name server" on Windows)
        mail addr = dns.jomax.net       # ("responsible mail addr" on Windows)
        serial = 2008041300
        refresh = 28800
        retry = 7200
        expire = 604800
        minimum = 86400
Authoritative answers can be found from:
stackoverflow.com       nameserver = ns52.domaincontrol.com.
stackoverflow.com       nameserver = ns51.domaincontrol.com.

The origin (or primary name server on Windows) line tells you that ns51.domaincontrol is the main name server for stackoverflow.com.

At the end of output all authoritative servers, including backup servers for the given domain, are listed.

Disable vertical sync for glxgears

If you're using the NVIDIA closed-source drivers you can vary the vertical sync mode on the fly using the __GL_SYNC_TO_VBLANK environment variable:

~$ __GL_SYNC_TO_VBLANK=1 glxgears
Running synchronized to the vertical refresh.  The framerate should be
approximately the same as the monitor refresh rate.
299 frames in 5.0 seconds = 59.631 FPS

~$ __GL_SYNC_TO_VBLANK=0 glxgears
123259 frames in 5.0 seconds = 24651.678 FPS

This works for me on Ubuntu 14.04 using the 346.46 NVIDIA drivers.

Inline style to act as :hover in CSS

I put together a quick solution for anyone wanting to create hover popups without CSS using the onmouseover and onmouseout behaviors.

http://jsfiddle.net/Lk9w1mkv/

<div style="position:relative;width:100px;background:#ddffdd;overflow:hidden;" onmouseover="this.style.overflow='';" onmouseout="this.style.overflow='hidden';">first hover<div style="width:100px;position:absolute;top:5px;left:110px;background:white;border:1px solid gray;">stuff inside</div></div>

Java Byte Array to String to Byte Array

[JDK8]

import java.util.Base64;

To string:

String str = Base64.getEncoder().encode(new byte[]{ -47, 1, 16, ... });

To byte array:

byte[] bytes = Base64.getDecoder().decode("JVBERi0xLjQKMyAwIG9iago8P...");

Material UI and Grid system

I looked around for an answer to this and the best way I found was to use Flex and inline styling on different components.

For example, to make two paper components divide my full screen in 2 vertical components (in ration of 1:4), the following code works fine.

const styles = {
  div:{
    display: 'flex',
    flexDirection: 'row wrap',
    padding: 20,
    width: '100%'
  },
  paperLeft:{
    flex: 1,
    height: '100%',
    margin: 10,
    textAlign: 'center',
    padding: 10
  },
  paperRight:{
    height: 600,
    flex: 4,
    margin: 10,
    textAlign: 'center',
  }
};

class ExampleComponent extends React.Component {
  render() {
    return (
      <div>
        <div style={styles.div}>
          <Paper zDepth={3} style={styles.paperLeft}>
            <h4>First Vertical component</h4>
          </Paper>
          <Paper zDepth={3} style={styles.paperRight}>
              <h4>Second Vertical component</h4>
          </Paper>
        </div>
      </div>
    )
  }
}

Now, with some more calculations, you can easily divide your components on a page.

Further Reading on flex

View array in Visual Studio debugger?

If you have a large array and only want to see a subsection of the array you can type this into the watch window;

ptr+100,10

to show a list of the 10 elements starting at ptr[100]. Beware that the displayed array subscripts will start at [0], so you will have to remember that ptr[0] is really ptr[100] and ptr[1] is ptr[101] etc.

HTML: How to limit file upload to be only images?

HTML5 says <input type="file" accept="image/*">. Of course, never trust client-side validation: Always check again on the server-side...

How to Check if value exists in a MySQL database

For Matching the ID:

Select * from table_name where 1=1

For Matching the Pattern:

Select * from table_name column_name Like '%string%'

Javascript Iframe innerHTML

This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.

<div id='myframe'>

  <?php 
   /* 
    Use below function to display final HTML inside this div
   */

   //Display Frame
   echo displayFrame(); 
  ?>

</div>

<?php

/* 
  Function to display frame from another domain 
*/

function displayFrame()
{
  $webUrl = 'http://[external-web-domain.com]/';

  //Get HTML from the URL
  $content = file_get_contents($webUrl);

  //Add custom JS to returned HTML content
  $customJS = "
  <script>

      /* Here I am writing a sample jQuery to hide the navigation menu
         You can write your own jQuery for this content
      */
    //Hide Navigation bar
    jQuery(\".navbar\").hide();

  </script>";

  //Append Custom JS with HTML
  $html = $content . $customJS;

  //Return customized HTML
  return $html;
}

Fully custom validation error message with Rails

I recommend installing the custom_error_message gem (or as a plugin) originally written by David Easley

It lets you do stuff like:

validates_presence_of :non_friendly_field_name, :message => "^Friendly field name is blank"

How to print in C

try this:

printf("%d", addNumber(a,b))

Here's the documentation for printf.

how to call a function from another function in Jquery

wrap you shared code into another function:

<script>
  function myFun () {
      //do something
  }

  $(document).ready(function(){
    //Load City by State
    $(document).on('change', '#billing_state_id', function() {
       myFun ();
    });   
    $(document).on('click', '#click_me', function() {
       //do something
       myFun();
    });   
  });
</script>

How to inject a Map using the @Value Spring Annotation?

Here is how we did it. Two sample classes as follow:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
@EnableKafka
@Configuration
@EnableConfigurationProperties(KafkaConsumerProperties.class)
public class KafkaContainerConfig {

    @Autowired
    protected KafkaConsumerProperties kafkaConsumerProperties;

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(kafkaConsumerProperties.getKafkaConsumerConfig());
    }
...

@Configuration
@ConfigurationProperties
public class KafkaConsumerProperties {
    protected Map<String, Object> kafkaConsumerConfig = new HashMap<>();

    @ConfigurationProperties("kafkaConsumerConfig")
    public Map<String, Object> getKafkaConsumerConfig() {
        return (kafkaConsumerConfig);
    }
...

To provide the kafkaConsumer config from a properties file, you can use: mapname[key]=value

//application.properties
kafkaConsumerConfig[bootstrap.servers]=localhost:9092, localhost:9093, localhost:9094
kafkaConsumerConfig[group.id]=test-consumer-group-local
kafkaConsumerConfig[value.deserializer]=org.apache.kafka.common.serialization.StringDeserializer
kafkaConsumerConfig[key.deserializer=org.apache.kafka.common.serialization.StringDeserializer

To provide the kafkaConsumer config from a yaml file, you can use "[key]": value In application.yml file:

kafkaConsumerConfig:
  "[bootstrap.servers]": localhost:9092, localhost:9093, localhost:9094
  "[group.id]": test-consumer-group-local
  "[value.deserializer]": org.apache.kafka.common.serialization.StringDeserializer
  "[key.deserializer]": org.apache.kafka.common.serialization.StringDeserializer

SQL SERVER: Get total days between two dates

You can try this MSDN link

DATEDIFF ( datepart , startdate , enddate )
SELECT DATEDIFF(DAY, '1/1/2011', '3/1/2011')

How do I alter the position of a column in a PostgreSQL database table?

"Alter column position" in the PostgreSQL Wiki says:

PostgreSQL currently defines column order based on the attnum column of the pg_attribute table. The only way to change column order is either by recreating the table, or by adding columns and rotating data until you reach the desired layout.

That's pretty weak, but in their defense, in standard SQL, there is no solution for repositioning a column either. Database brands that support changing the ordinal position of a column are defining an extension to SQL syntax.

One other idea occurs to me: you can define a VIEW that specifies the order of columns how you like it, without changing the physical position of the column in the base table.

While loop to test if a file exists in bash

I ran into a similar issue and it lead me here so I just wanted to leave my solution for anyone who experiences the same.

I found that if I ran cat /tmp/list.txt the file would be empty, even though I was certain that there were contents being placed immediately in the file. Turns out if I put a sleep 1; just before the cat /tmp/list.txt it worked as expected. There must have been a delay between the time the file was created and the time it was written, or something along those lines.

My final code:

while [ ! -f /tmp/list.txt ];
do
    sleep 1;
done;
sleep 1;
cat /tmp/list.txt;

Hope this helps save someone a frustrating half hour!

What is "export default" in JavaScript?

export default is used to export a single class, function or primitive from a script file.

The export can also be written as

export default function SafeString(string) {
  this.string = string;
}

SafeString.prototype.toString = function() {
  return "" + this.string;
};

This is used to import this function in another script file

Say in app.js, you can

import SafeString from './handlebars/safe-string';

A little about export

As the name says, it's used to export functions, objects, classes or expressions from script files or modules

Utiliites.js

export function cube(x) {
  return x * x * x;
}
export const foo = Math.PI + Math.SQRT2;

This can be imported and used as

App.js

import { cube, foo } from 'Utilities';
console.log(cube(3)); // 27
console.log(foo);    // 4.555806215962888

Or

import * as utilities from 'Utilities';
console.log(utilities.cube(3)); // 27
console.log(utilities.foo);    // 4.555806215962888

When export default is used, this is much simpler. Script files just exports one thing. cube.js

export default function cube(x) {
  return x * x * x;
};

and used as App.js

import Cube from 'cube';
console.log(Cube(3)); // 27

Python display text with font & color?

I wrote a wrapper, that will cache text surfaces, only re-render when dirty. googlecode/ninmonkey/nin.text/demo/

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

Too many big files all in one go. Windows barfs. Essentially the copying took too long because you asked too much of the computer and the file locking was locked too long and set a flag off, the flag is a semaphore error.

The computer stuffed itself and choked on it. I saw the RAM memory here get progressively filled with a Cache in RAM. Then when filled the subsystem ground to a halt with a semaphore error.

I have a workaround; copy or transfer fewer files not one humongous block. Break it down into sets of blocks and send across the files one at a time, maybe a few at a time, but not never the lot.

References:

https://appuals.com/how-to-fix-the-semaphore-timeout-period-has-expired-0x80070079/

https://www-01.ibm.com/support/docview.wss?uid=swg21094630

How do I put a clear button inside my HTML text input box like the iPhone does?

Of course the best approach is to use the ever-more-supported <input type="search" />.

Anyway for a bit of coding fun I thought that it could be achieved also using the form's reset button, and this is the working result (it is worth noting that you cannot have other inputs in the form but the search field with this approach, or the reset button will erase them too), no javascript needed:

_x000D_
_x000D_
form{
    position: relative;
    width: 200px;
}

form input {
    width: 100%;
    padding-right: 20px;
    box-sizing: border-box;
}

form input:placeholder-shown + button{
  opacity: 0;
  pointer-events: none;
} 

form button {
    position: absolute;
    border: none;
    display: block;
    width: 15px;
    height: 15px;
    line-height: 16px;
    font-size: 12px;
    border-radius: 50%;
    top: 0;
    bottom: 0;
    right: 5px;
    margin: auto;
    background: #ddd;
    padding: 0;
    outline: none;
    cursor: pointer;
    transition: .1s;
}
_x000D_
<form>
        <input type="text" placeholder=" " />
        <button type="reset">&times;</button>
</form>
_x000D_
_x000D_
_x000D_

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

There are two differences between == and === in PHP arrays and objects that I think didn't mention here; two arrays with different key sorts, and objects.

Two arrays with different key sorts

If you have an array with a key sort and another array with a different key sort, they are strictly different (i.e. using ===). That may cause if you key-sort an array, and try to compare the sorted array with the original one.

For instance, consider an empty array. First, we try to push some new indexes to the array without any special sort. A good example would be an array with strings as keys. Now deep into an example:

// Define an array
$arr = [];

// Adding unsorted keys
$arr["I"] = "we";
$arr["you"] = "you";
$arr["he"] = "they";

Now, we have a not-sorted-keys array (e.g., 'he' came after 'you'). Consider the same array, but we sorted its keys alphabetically:

// Declare array
$alphabetArr = [];

// Adding alphabetical-sorted keys
$alphabetArr["I"] = "we";
$alphabetArr["he"] = "they";
$alphabetArr["you"] = "you";

Tip: You can sort an array by key using ksort() function.

Now you have another array with a different key sort from the first one. So, we're going to compare them:

$arr == $alphabetArr; // true
$arr === $alphabetArr; // false

Note: It may be obvious, but comparing two different arrays using strict comparison always results false. However, two arbitrary arrays may be equal using === or not.

You would say: "This difference is negligible". Then I say it's a difference and should be considered and may happen anytime. As mentioned above, sorting keys in an array is a good example of that.

Objects

Keep in mind, two different objects are never strict-equal. These examples would help:

$stdClass1 = new stdClass();
$stdClass2 = new stdClass();
$clonedStdClass1 = clone $stdClass1;

// Comparing
$stdClass1 == $stdClass2; // true
$stdClass1 === $stdClass2; // false
$stdClass1 == $clonedStdClass1; // true
$stdClass1 === $clonedStdClass1; // false

Note: Assigning an object to another variable does not create a copy - rather, it creates a reference to the same memory location as the object. See here.

Note: As of PHP7, anonymous classes was added. From the results, there is no difference between new class {} and new stdClass() in the tests above.

What is setBounds and how do I use it?

There is an answer by @hexafraction , He had specified the x and y to be top right corner which is wrong, those are top left corner .

I have also provided the source please check it.

public void setBounds(int x,
             int y,
             int width,
             int height)

Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height. This method changes layout-related information, and therefore, invalidates the component hierarchy.

Parameters:

x - the new x-coordinate of this component

y - the new y-coordinate of this component

width - the new width of this component

height - the new height of this component

source:- setBounds

git stash -> merge stashed change with current changes

As suggested by @Brandan, here's what I needed to do to get around

error: Your local changes to the following files would be overwritten by merge:
       file.txt
Please, commit your changes or stash them before you can merge.
Aborting

Follow this process:

git status  # local changes to `file`
git stash list  # further changes to `file` we want to merge
git commit -m "WIP" file
git stash pop
git commit -m "WIP2" file
git rebase -i HEAD^^  # I always use interactive rebase -- I'm sure you could do this in a single command with the simplicity of this process -- basically squash HEAD into HEAD^
# mark the second commit to squash into the first using your EDITOR
git reset HEAD^

And you'll be left with fully merged local changes to file, ready to do further work/cleanup or make a single good commit. Or, if you know the merged contents of file will be correct, you could write a fitting message and skip git reset HEAD^.

How can I determine if an image has loaded, using Javascript/jQuery?

I found this worked for me

document.querySelector("img").addEventListener("load", function() { alert('onload!'); });

Credit goes totaly to Frank Schwieterman, who commented on accepted answer. I had to put this here, it's too valuable...

How to add a "sleep" or "wait" to my Lua Script?

This homebrew function have precision down to a 10th of a second or less.

function sleep (a) 
    local sec = tonumber(os.clock() + a); 
    while (os.clock() < sec) do 
    end 
end

C++ Compare char array with string

your thinking about this program below

#include <stdio.h>
#include <string.h>

int main ()
{
char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
int n;
puts ("Looking for R2 astromech droids...");
for (n=0 ; n<3 ; n++)
if (strncmp (str[n],"R2xx",2) == 0)
{
  printf ("found %s\n",str[n]);
}
return 0;
}
//outputs:
//
//Looking for R2 astromech droids...
//found R2D2
//found R2A6

when you should be thinking about inputting something into an array & then use strcmp functions like the program above ... check out a modified program below

#include <iostream>
#include<cctype>
#include <string.h>
#include <string>
using namespace std;

int main()
{
int Students=2;
int Projects=3, Avg2=0, Sum2=0, SumT2=0, AvgT2=0, i=0, j=0;
int Grades[Students][Projects];

for(int j=0; j<=Projects-1; j++){
  for(int i=0; i<=Students; i++) {
 cout <<"Please give grade of student "<< j <<"in project "<< i  <<  ":";
  cin >> Grades[j][i];

  }
  Sum2 = Sum2 + Grades[i][j];
     Avg2 = Sum2/Students;
}
SumT2 = SumT2 + Avg2;
AvgT2 = SumT2/Projects;
cout << "avg is  : " << AvgT2 << " and sum : " << SumT2 << ":";
return 0;
}

change to string except it only reads 1 input and throws the rest out maybe need two for loops and two pointers

#include <cstring>
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
char name[100];
//string userInput[26];
int i=0, n=0, m=0;
cout<<"your name? ";
cin>>name;
cout<<"Hello "<<name<< endl;

char *ptr=name;
for (i = 0; i < 20; i++)
{
cout<<i<<" "<<ptr[i]<<" "<<(int)ptr[i]<<endl;
}   
int length = 0;
while(name[length] != '\0')
{
length++;
}
                    for(n=0; n<4; n++)
                {
                            if (strncmp(ptr, "snit", 4) == 0)
                            {
            cout << "you found the snitch "    <<        ptr[i];
                            }
                }
cout<<name <<"is"<<length<<"chars long";
}

JavaScript or jQuery browser back button click detector

In case of HTML5 this will do the trick

window.onpopstate = function() {
   alert("clicked back button");
}; history.pushState({}, '');

How to resize datagridview control when form resizes

You have to chose 'Fill' in the Dock property.

NullPointerException in Java with no StackTrace

You are probably using the HotSpot JVM (originally by Sun Microsystems, later bought by Oracle, part of the OpenJDK), which performs a lot of optimization. To get the stack traces back, you need to pass the option -XX:-OmitStackTraceInFastThrow to the JVM.

The optimization is that when an exception (typically a NullPointerException) occurs for the first time, the full stack trace is printed and the JVM remembers the stack trace (or maybe just the location of the code). When that exception occurs often enough, the stack trace is not printed anymore, both to achieve better performance and not to flood the log with identical stack traces.

To see how this is implemented in the HotSpot JVM, grab a copy of it and search for the global variable OmitStackTraceInFastThrow. Last time I looked at the code (in 2019), it was in the file graphKit.cpp.

Setting a system environment variable from a Windows batch file?

Just in case you would need to delete a variable, you could use SETENV from Vincent Fatica available at http://barnyard.syr.edu/~vefatica. Not exactly recent ('98) but still working on Windows 7 x64.

How to access local files of the filesystem in the Android emulator?

In Android Studio 3.5.3, the Device File Explorer can be found in View -> Tool Windows.

It can also be opened using the vertical tabs on the right-hand side of the main window.

What are database constraints?

  1. UNIQUE constraint (of which a PRIMARY KEY constraint is a variant). Checks that all values of a given field are unique across the table. This is X-axis constraint (records)

  2. CHECK constraint (of which a NOT NULL constraint is a variant). Checks that a certain condition holds for the expression over the fields of the same record. This is Y-axis constraint (fields)

  3. FOREIGN KEY constraint. Checks that a field's value is found among the values of a field in another table. This is Z-axis constraint (tables).

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

How to match letters only using java regex, matches method?

Three problems here:

  1. Just use String.matches() - if the API is there, use it
  2. In java "matches" means "matches the entire input", which IMHO is counter-intuitive, so let your method's API reflect that by letting callers think about matching part of the input as your example suggests
  3. You regex matches only 1 character

I recommend you use code like this:

public boolean matches(String regex) {
    regex = "^.*" + regex + ".*$"; // pad with regex to allow partial matching
    System.out.println("abcABC   ".matches(regex));
    return "abcABC   ".matches(regex);
}

public static void main(String[] args) {
    HowEasy words = new HowEasy();
    words.matches("[a-zA-Z]+"); // added "+" (ie 1-to-n of) to character class
}

Get selected value in dropdown list using JavaScript

Running example of how it works:

_x000D_
_x000D_
var e = document.getElementById("ddlViewBy");_x000D_
var val1 = e.options[e.selectedIndex].value;_x000D_
var txt = e.options[e.selectedIndex].text;_x000D_
_x000D_
document.write("<br />Selected option Value: "+ val1);_x000D_
document.write("<br />Selected option Text: "+ txt);
_x000D_
<select id="ddlViewBy">_x000D_
  <option value="1">test1</option>_x000D_
  <option value="2">test2</option>_x000D_
  <option value="3"  selected="selected">test3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Note: The values don't change as the dropdown is changed, if you require that functionality then an onClick change is to be implemented.

array.select() in javascript

There's also Array.find() in ES6 which returns the first matching element it finds.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

const myArray = [1, 2, 3]

const myElement = myArray.find((element) => element === 2)

console.log(myElement)
// => 2

How to redirect verbose garbage collection output to a file?

If in addition you want to pipe the output to a separate file, you can do:

On a Sun JVM:

-Xloggc:C:\whereever\jvm.log -verbose:gc -XX:+PrintGCDateStamps

ON an IBM JVM:

-Xverbosegclog:C:\whereever\jvm.log 

How can I hide a TD tag using inline JavaScript or CSS?

What do you expect to happen in it's place? The table can't reflow to fill the space left - this seems like a recipe for buggy browser responses.

Think about hiding the contents of the td, not the td itself.

MVC pattern on Android

I agree with JDPeckham, and I believe that XML alone is not sufficient to implement the UI part of an application.

However, if you consider the Activity as part of the view then implementing MVC is quite straightforward. You can override Application (as returned by getApplication() in Activity) and it's here that you can create a controller that survives for the lifetime of your application.

(Alternatively you can use the singleton pattern as suggested by the Application documentation)

How to exclude property from Json Serialization

You can use [ScriptIgnore]:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    [ScriptIgnore]
    public bool IsComplete
    {
        get { return Id > 0 && !string.IsNullOrEmpty(Name); }
    }
}

Reference here

In this case the Id and then name will only be serialized

Convert xlsx to csv in Linux with command line

If you are OK to run Java command line then you can do it with Apache POI HSSF's Excel Extractor. It has a main method that says to be the command line extractor. This one seems to just dump everything out. They point out to this example that converts to CSV. You would have to compile it before you can run it but it too has a main method so you should not have to do much coding per se to make it work.

Another option that might fly but will require some work on the other end is to make your Excel files come to you as Excel XML Data or XML Spreadsheet of whatever MS calls that format these days. It will open a whole new world of opportunities for you to slice and dice it the way you want.

Change R default library path using .libPaths in Rprofile.site fails to work

If you do not have admin-rights, it can also be helpful to open the Rprofile.site-file located in \R-3.1.0\etc and add:

.First <- function(){
  .libPaths("your path here")
}

This evaluates the .libPath() command directly at start

php.ini & SMTP= - how do you pass username & password

Use Mail::factory in the Mail PEAR package. Example.

Convert a double to a QString

Building on @Kristian's answer, I had a desire to display a fixed number of decimal places. That can be accomplished with other arguments in the QString::number(...) function. For instance, I wanted 3 decimal places:

double value = 34.0495834;
QString strValue = QString::number(value, 'f', 3);
// strValue == "34.050"

The 'f' specifies decimal format notation (more info here, you can also specify scientific notation) and the 3 specifies the precision (number of decimal places). Probably already linked in other answers, but more info about the QString::number function can be found here in the QString documentation

Find all matches in workbook using Excel VBA

Based on Ahmed's answer, after some cleaning up and generalization, including the other "Find" parameters, so we can use this function in any situation:

'Uses Range.Find to get a range of all find results within a worksheet
' Same as Find All from search dialog box
'
Function FindAll(rng As Range, What As Variant, Optional LookIn As XlFindLookIn = xlValues, Optional LookAt As XlLookAt = xlWhole, Optional SearchOrder As XlSearchOrder = xlByColumns, Optional SearchDirection As XlSearchDirection = xlNext, Optional MatchCase As Boolean = False, Optional MatchByte As Boolean = False, Optional SearchFormat As Boolean = False) As Range
    Dim SearchResult As Range
    Dim firstMatch As String
    With rng
        Set SearchResult = .Find(What, , LookIn, LookAt, SearchOrder, SearchDirection, MatchCase, MatchByte, SearchFormat)
        If Not SearchResult Is Nothing Then
            firstMatch = SearchResult.Address
            Do
                If FindAll Is Nothing Then
                    Set FindAll = SearchResult
                Else
                    Set FindAll = Union(FindAll, SearchResult)
                End If
                Set SearchResult = .FindNext(SearchResult)
            Loop While Not SearchResult Is Nothing And SearchResult.Address <> firstMatch
        End If
    End With
End Function

How do I change the owner of a SQL Server database?

to change the object owner try the following

EXEC sp_changedbowner 'sa'

that however is not your problem, to see diagrams the Da Vinci Tools objects have to be created (you will see tables and procs that start with dt_) after that

What is the best practice for creating a favicon on a web site?

There are several ways to create a favicon. The best way for you depends on various factors:

  • The time you can spend on this task. For many people, this is "as quick as possible".
  • The efforts you are willing to make. Like, drawing a 16x16 icon by hand for better results.
  • Specific constraints, like supporting a specific browser with odd specs.

First method: Use a favicon generator

If you want to get the job done well and quickly, you can use a favicon generator. This one creates the pictures and HTML code for all major desktop and mobiles browsers. Full disclosure: I'm the author of this site.

Advantages of such solution: it's quick and all compatibility considerations were already addressed for you.

Second method: Create a favicon.ico (desktop browsers only)

As you suggest, you can create a favicon.ico file which contains 16x16 and 32x32 pictures (note that Microsoft recommends 16x16, 32x32 and 48x48).

Then, declare it in your HTML code:

<link rel="shortcut icon" href="/path/to/icons/favicon.ico">

This method will work with all desktop browsers, old and new. But most mobile browsers will ignore the favicon.

About your suggestion of placing the favicon.ico file in the root and not declaring it: beware, although this technique works on most browsers, it is not 100% reliable. For example Windows Safari cannot find it (granted: this browser is somehow deprecated on Windows, but you get the point). This technique is useful when combined with PNG icons (for modern browsers).

Third method: Create a favicon.ico, a PNG icon and an Apple Touch icon (all browsers)

In your question, you do not mention the mobile browsers. Most of them will ignore the favicon.ico file. Although your site may be dedicated to desktop browsers, chances are that you don't want to ignore mobile browsers altogether.

You can achieve a good compatibility with:

  • favicon.ico, see above.
  • A 192x192 PNG icon for Android Chrome
  • A 180x180 Apple Touch icon (for iPhone 6 Plus; other device will scale it down as needed).

Declare them with

<link rel="shortcut icon" href="/path/to/icons/favicon.ico">
<link rel="icon" type="image/png" href="/path/to/icons/favicon-192x192.png" sizes="192x192">
<link rel="apple-touch-icon" sizes="180x180" href="/path/to/icons/apple-touch-icon-180x180.png">

This is not the full story, but it's good enough in most cases.

How to concatenate two MP4 files using FFmpeg?

Here's a fast (takes less than 1 minute) and lossless way to do this without needing intermediate files:

ls Movie_Part_1.mp4 Movie_Part_2.mp4 | \
perl -ne 'print "file $_"' | \
ffmpeg -f concat -i - -c copy Movie_Joined.mp4

The "ls" contains the files to join The "perl" creates the concatenation file on-the-fly into a pipe The "-i -" part tells ffmpeg to read from the pipe

(note - my files had no spaces or weird stuff in them - you'll need appropriate shell-escaping if you want to do this idea with "hard" files).

How can I make XSLT work in chrome?

At the time of writing, there was a bug in chrome which required an xmlns attribute in order to trigger rendering:

<xsl:stylesheet xmlns="http://www.w3.org/1999/xhtml" ... >

This was the problem I was running into when serving the xml file from a server.


If unlike me, you are viewing the xml file from a file:/// url, then the solutions mentioning --allow-file-access-from-files are the ones you want

NVIDIA NVML Driver/library version mismatch

So I was having this problem, none of the other remedies worked. The error message was opaque, but checking dmesg was key:

[   10.118255] NVRM: API mismatch: the client has the version 410.79, but
           NVRM: this kernel module has the version 384.130.  Please
           NVRM: make sure that this kernel module and all NVIDIA driver
           NVRM: components have the same version.

However I had completely removed the 384 version, and removed any remaining kernel drivers nvidia-384*. But even after reboot, I was still getting this. Seeing this meant that the kernel was still compiled to reference 384, but was only finding 410. So I recompiled my kernel:

# uname -a # find the kernel it's using
Linux blah 4.13.0-43-generic #48~16.04.1-Ubuntu SMP Thu May 17 12:56:46 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
# update-initramfs -c -k 4.13.0-43-generic #recompile it
# reboot

And then it worked.

After removing 384, I still had 384 files in: /var/lib/dkms/nvidia-XXX/XXX.YY/4.13.0-43-generic/x86_64/module /lib/modules/4.13.0-43-generic/kernel/drivers

I recommend using the locate command (not installed by default) rather than searching the filesystem every time.

Requested registry access is not allowed

You Could Do The same as abatishchev but without the UAC

<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
 <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
   <security>
    <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
    </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>

Scroll to element on click in Angular 4

You can scroll to any element ref on your view by using the code block below. Note that the target (elementref id) could be on any valid html tag.

On the view(html file)

<div id="target"> </div>
<button (click)="scroll()">Button</button>
 

  

on the .ts file,

scroll() {
   document.querySelector('#target').scrollIntoView({ behavior: 'smooth', block: 'center' });
}

how to properly display an iFrame in mobile safari

Don't scroll the IFrame page or its content, scroll the parent page. If you control the IFrame content, you can use the iframe-resizer library to turn the iframe element itself into a proper block level element, with a natural/correct/native height. Also, don't attempt to position (fixed, absolute) your iframe in the parent page, or present an iframe in a modal window, especially if it has form elements.

I also suspect that iOS Safari has a non-standards behavior that expands your iframe's height to its natural height, much like the iframe-resizer library will do for desktop browsers, which seem to render responsive iframe content at height 0px or 150px or some other not useful default. If you need to contrain width, try a max-width style inside the iframe.

How to get the nth element of a python list or a default if not available

Combining @Joachim's with the above, you could use

next(iter(my_list[index:index+1]), default)

Examples:

next(iter(range(10)[8:9]), 11)
8
>>> next(iter(range(10)[12:13]), 11)
11

Or, maybe more clear, but without the len

my_list[index] if my_list[index:index + 1] else default

How to _really_ programmatically change primary and accent color in Android Lollipop?

I've created some solution to make any-color themes, maybe this can be useful for somebody. API 9+

1. first create "res/values-v9/" and put there this file: styles.xml and regular "res/values" folder will be used with your styles.

2. put this code in your res/values/styles.xml:

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">#000</item>
        <item name="colorPrimaryDark">#000</item>
        <item name="colorAccent">#000</item>
        <item name="android:windowAnimationStyle">@style/WindowAnimationTransition</item>
    </style>

    <style name="AppThemeDarkActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">#000</item>
        <item name="colorPrimaryDark">#000</item>
        <item name="colorAccent">#000</item>
        <item name="android:windowAnimationStyle">@style/WindowAnimationTransition</item>
    </style>

    <style name="WindowAnimationTransition">
        <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
        <item name="android:windowExitAnimation">@android:anim/fade_out</item>
    </style>
</resources>

3. in to AndroidManifest:

<application android:theme="@style/AppThemeDarkActionBar">

4. create a new class with name "ThemeColors.java"

public class ThemeColors {

    private static final String NAME = "ThemeColors", KEY = "color";

    @ColorInt
    public int color;

    public ThemeColors(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        String stringColor = sharedPreferences.getString(KEY, "004bff");
        color = Color.parseColor("#" + stringColor);

        if (isLightActionBar()) context.setTheme(R.style.AppTheme);
        context.setTheme(context.getResources().getIdentifier("T_" + stringColor, "style", context.getPackageName()));
    }

    public static void setNewThemeColor(Activity activity, int red, int green, int blue) {
        int colorStep = 15;
        red = Math.round(red / colorStep) * colorStep;
        green = Math.round(green / colorStep) * colorStep;
        blue = Math.round(blue / colorStep) * colorStep;

        String stringColor = Integer.toHexString(Color.rgb(red, green, blue)).substring(2);
        SharedPreferences.Editor editor = activity.getSharedPreferences(NAME, Context.MODE_PRIVATE).edit();
        editor.putString(KEY, stringColor);
        editor.apply();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) activity.recreate();
        else {
            Intent i = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName());
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            activity.startActivity(i);
        }
    }

    private boolean isLightActionBar() {// Checking if title text color will be black
        int rgb = (Color.red(color) + Color.green(color) + Color.blue(color)) / 3;
        return rgb > 210;
    }
}

5. MainActivity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new ThemeColors(this);
        setContentView(R.layout.activity_main);
    }

    public void buttonClick(View view){
        int red= new Random().nextInt(255);
        int green= new Random().nextInt(255);
        int blue= new Random().nextInt(255);
        ThemeColors.setNewThemeColor(MainActivity.this, red, green, blue);
    }
}

To change color, just replace Random with your RGB, Hope this helps.

enter image description here

There is a complete example: ColorTest.zip

Upgrading PHP on CentOS 6.5 (Final)

IUS offers an installation script for subscribing to their repository and importing associated GPG keys. Make sure you’re in your home directory, and retrieve the script using curl:

curl 'https://setup.ius.io/' -o setup-ius.sh
sudo bash setup-ius.sh

Install Required Packages-:

sudo yum install -y mod_php70u php70u-cli php70u-mysqlnd php70u-json php70u-gd php70u-dom php70u-simplexml php70u-mcrypt php70u-intl

POST unchecked HTML checkboxes

There is a better workaround. First of all provide name attribute to only those checkboxes that are checked. Then on click submit, through a JavaScript function you check all unchecked boxes . So when you submit only those will be retrieved in form collection those who have name property.

  //removing name attribute from all checked checkboxes
                  var a = $('input:checkbox:checked');
                   $(a).each(function () {
                       $(this).removeAttr("name");        
                   });

   // checking all unchecked checkboxes
                   var b = $("input:checkbox:not(:checked)");
                   $(b).each(function () {
                       $(this).attr("checked", true);
                   });

Advantage: No need to create extra hidden boxes,and manipulate them.

Use curly braces to initialize a Set in Python

There are two obvious issues with the set literal syntax:

my_set = {'foo', 'bar', 'baz'}
  1. It's not available before Python 2.7

  2. There's no way to express an empty set using that syntax (using {} creates an empty dict)

Those may or may not be important to you.

The section of the docs outlining this syntax is here.

Tkinter understanding mainloop

I'm using an MVC / MVA design pattern, with multiple types of "views". One type is a "GuiView", which is a Tk window. I pass a view reference to my window object which does things like link buttons back to view functions (which the adapter / controller class also calls).

In order to do that, the view object constructor needed to be completed prior to creating the window object. After creating and displaying the window, I wanted to do some initial tasks with the view automatically. At first I tried doing them post mainloop(), but that didn't work because mainloop() blocked!

As such, I created the window object and used tk.update() to draw it. Then, I kicked off my initial tasks, and finally started the mainloop.

import Tkinter as tk

class Window(tk.Frame):
    def __init__(self, master=None, view=None ):
        tk.Frame.__init__( self, master )
        self.view_ = view       
        """ Setup window linking it to the view... """

class GuiView( MyViewSuperClass ):

    def open( self ):
        self.tkRoot_ = tk.Tk()
        self.window_ = Window( master=None, view=self )
        self.window_.pack()
        self.refresh()
        self.onOpen()
        self.tkRoot_.mainloop()         

    def onOpen( self ):        
        """ Do some initial tasks... """

    def refresh( self ):        
        self.tkRoot_.update()

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.

A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt and jshint.

These lines add more meaning

Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.

Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:

  1. Zipping some files (e.g. zipup plugin)
  2. Linting on js files (jshint)
  3. Compiling less files (grunt-contrib-less)

There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.

Please Note that grunt plugin is also an npm package.

Question-1

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.

Question-2

When should I ever install packages explicitly like that without adding them to the file that manages dependencies

It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request, then you have two options:

  • Edit the package.json file and add a dependency on 'request'
  • npm install

OR

  • Use commandline: npm install --save request

--save options adds the dependency to package.json file as well. If you don't specify --save option, it will only download the package but the json file will be unaffected.

You can do this either way, there will not be a substantial difference.

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

On MongoDB 4.4+ and on CentOS 8, I found the path by running:

grep dbPath /etc/mongod.conf

cleanup php session files

To handle session properly, take a look at http://php.net/manual/en/session.configuration.php.

There you'll find these variables:

  • session.gc_probability
  • session.gc_divisor
  • session.gc_maxlifetime

These control the garbage collector (GC) probability of running with each page request.

You could set those with ini_set() at the beginning of your script or .htaccess file so you get certainty to some extent they will get deleted sometime.

How to download excel (.xls) file from API in postman?

You can Just save the response(pdf,doc etc..) by option on the right side of the response in postman check this image postman save response

For more Details check this

https://learning.getpostman.com/docs/postman/sending_api_requests/responses/

Add padding on view programmatically

Write Following Code to set padding, it may help you.

TextView ApplyPaddingTextView = (TextView)findViewById(R.id.textView1);
final LayoutParams layoutparams = (RelativeLayout.LayoutParams) ApplyPaddingTextView.getLayoutParams();

layoutparams.setPadding(50,50,50,50);

ApplyPaddingTextView.setLayoutParams(layoutparams);

Use LinearLayout.LayoutParams or RelativeLayout.LayoutParams according to parent layout of the child view

TabLayout tab selection

you should use a viewPager to use viewPager.setCurrentItem()

 viewPager.setCurrentItem(n);
 tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

List all virtualenv

This works on Windows only:

If you are trying to find all envs created using virtualenv
search for "activate_this.py" or "pip-selfcheck.json"

How do I bind a List<CustomObject> to a WPF DataGrid?

if you do not expect that your list will be recreated then you can use the same approach as you've used for Asp.Net (instead of DataSource this property in WPF is usually named ItemsSource):

this.dataGrid1.ItemsSource = list;

But if you would like to replace your list with new collection instance then you should consider using databinding.

StringUtils.isBlank() vs String.isEmpty()

The accepted answer from @arshajii is totally correct. However just being more explicit by saying below,

StringUtils.isBlank()

 StringUtils.isBlank(null)      = true
 StringUtils.isBlank("")        = true  
 StringUtils.isBlank(" ")       = true  
 StringUtils.isBlank("bob")     = false  
 StringUtils.isBlank("  bob  ") = false

StringUtils.isEmpty

 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true  
 StringUtils.isEmpty(" ")       = false  
 StringUtils.isEmpty("bob")     = false  
 StringUtils.isEmpty("  bob  ") = false

What is an API key?

An API key is a unique value that is assigned to a user of this service when he's accepted as a user of the service.

The service maintains all the issued keys and checks them at each request.

By looking at the supplied key at the request, a service checks whether it is a valid key to decide on whether to grant access to a user or not.

Differences between MySQL and SQL Server

@abdu

The main thing I've found that MySQL has over MSSQL is timezone support - the ability to nicely change between timezones, respecting daylight savings is fantastic.

Compare this:

mysql> SELECT CONVERT_TZ('2008-04-01 12:00:00', 'UTC', 'America/Los_Angeles');
+-----------------------------------------------------------------+
| CONVERT_TZ('2008-04-01 12:00:00', 'UTC', 'America/Los_Angeles') |
+-----------------------------------------------------------------+
| 2008-04-01 05:00:00                                             |
+-----------------------------------------------------------------+

to the contortions involved at this answer.

As for the 'easier to use' comment, I would say that the point is that they are different, and if you know one, there will be an overhead in learning the other.

Sending emails in Node.js?

@JimBastard's accepted answer appears to be dated, I had a look and that mailer lib hasn't been touched in over 7 months, has several bugs listed, and is no longer registered in npm.

nodemailer certainly looks like the best option, however the url provided in other answers on this thread are all 404'ing.

nodemailer claims to support easy plugins into gmail, hotmail, etc. and also has really beautiful documentation.

Angular is automatically adding 'ng-invalid' class on 'required' fields

Since the inputs are empty and therefore invalid when instantiated, Angular correctly adds the ng-invalid class.

A CSS rule you might try:

input.ng-dirty.ng-invalid {
  color: red
}

Which basically states when the field has had something entered into it at some point since the page loaded and wasn't reset to pristine by $scope.formName.setPristine(true) and something wasn't yet entered and it's invalid then the text turns red.

Other useful classes for Angular forms (see input for future reference )

ng-valid-maxlength - when ng-maxlength passes
ng-valid-minlength - when ng-minlength passes
ng-valid-pattern - when ng-pattern passes
ng-dirty - when the form has had something entered since the form loaded
ng-pristine - when the form input has had nothing inserted since loaded (or it was reset via setPristine(true) on the form)
ng-invalid - when any validation fails (required, minlength, custom ones, etc)

Likewise there is also ng-invalid-<name> for all these patterns and any custom ones created.

What does the arrow operator, '->', do in Java?

It's a lambda expression.

It means that, from the listOfCars, arg0 is one of the items of that list. With that item he is going to do, hence the ->, whatever is inside of the brackets.

In this example, he's going to return a list of cars that fit the condition

Car.SEDAN == ((Car)arg0).getStyle();

How should I log while using multiprocessing in Python?

If you have deadlocks occurring in a combination of locks, threads and forks in the logging module, that is reported in bug report 6721 (see also related SO question).

There is a small fixup solution posted here.

However, that will just fix any potential deadlocks in logging. That will not fix that things are maybe garbled up. See the other answers presented here.

How do you overcome the HTML form nesting limitation?

Alternatively you could assign the form actiob on the fly...might not be the best solution, but sure does relieve the server-side logic...

<form name="frm" method="post">  
    <input type="submit" value="One" onclick="javascript:this.form.action='1.htm'" />  
    <input type="submit" value="Two" onclick="javascript:this.form.action='2.htm'" />  
</form>

When should one use a spinlock instead of mutex?

Using spinlocks on a single-core/single-CPU system makes usually no sense, since as long as the spinlock polling is blocking the only available CPU core, no other thread can run and since no other thread can run, the lock won't be unlocked either. IOW, a spinlock wastes only CPU time on those systems for no real benefit

This is wrong. There is no wastage of cpu cycles in using spinlocks on uni processor systems, because once a process takes a spin lock , preemption is disabled , so as such, there could be no one else spinning! It's just that using it doesn't make any sense! Hence, spinlocks on Uni systems are replaced by preempt_disable at compile time by the kernel!

InputStream from a URL

Here is a full example which reads the contents of the given web page. The web page is read from an HTML form. We use standard InputStream classes, but it could be done more easily with JSoup library.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>

</dependency>

<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.6</version>
</dependency>  

These are the Maven dependencies. We use Apache Commons library to validate URL strings.

package com.zetcode.web;

import com.zetcode.service.WebPageReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "ReadWebPage", urlPatterns = {"/ReadWebPage"})
public class ReadWebpage extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/plain;charset=UTF-8");

        String page = request.getParameter("webpage");

        String content = new WebPageReader().setWebPageName(page).getWebPageContent();

        ServletOutputStream os = response.getOutputStream();
        os.write(content.getBytes(StandardCharsets.UTF_8));
    }
}

The ReadWebPage servlet reads the contents of the given web page and sends it back to the client in plain text format. The task of reading the page is delegated to WebPageReader.

package com.zetcode.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.apache.commons.validator.routines.UrlValidator;

public class WebPageReader {

    private String webpage;
    private String content;

    public WebPageReader setWebPageName(String name) {

        webpage = name;
        return this;
    }

    public String getWebPageContent() {

        try {

            boolean valid = validateUrl(webpage);

            if (!valid) {

                content = "Invalid URL; use http(s)://www.example.com format";
                return content;
            }

            URL url = new URL(webpage);

            try (InputStream is = url.openStream();
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(is, StandardCharsets.UTF_8))) {

                content = br.lines().collect(
                      Collectors.joining(System.lineSeparator()));
            }

        } catch (IOException ex) {

            content = String.format("Cannot read webpage %s", ex);
            Logger.getLogger(WebPageReader.class.getName()).log(Level.SEVERE, null, ex);
        }

        return content;
    }

    private boolean validateUrl(String webpage) {

        UrlValidator urlValidator = new UrlValidator();

        return urlValidator.isValid(webpage);
    }
}

WebPageReader validates the URL and reads the contents of the web page. It returns a string containing the HTML code of the page.

<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <form action="ReadWebPage">

            <label for="page">Enter a web page name:</label>
            <input  type="text" id="page" name="webpage">

            <button type="submit">Submit</button>

        </form>
    </body>
</html>

Finally, this is the home page containing the HTML form. This is taken from my tutorial about this topic.

Suppress console output in PowerShell

Try redirecting the output to Out-Null. Like so,

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

JavaScript validation for empty input field

Just add an ID tag to the input element... ie:

and check the value of the element in you javascript:

document.getElementById("question").value

Oh ya, get get firefox/firebug. It's the only way to do javascript.

Java Could not reserve enough space for object heap error

Double click Liferay CE Server -> add -XX:MaxHeapSize=512m to Memory args -> Start server! Enjoy...

It's work for me!

Internet Explorer cache location

If you want to find the folder in a platform independent way, you should query the registry key:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cache

Server configuration by allow_url_fopen=0 in

If you do not have the ability to modify your php.ini file, use cURL: PHP Curl And Cookies

Here is an example function I created:

function get_web_page( $url, $cookiesIn = '' ){
        $options = array(
            CURLOPT_RETURNTRANSFER => true,     // return web page
            CURLOPT_HEADER         => true,     //return headers in addition to content
            CURLOPT_FOLLOWLOCATION => true,     // follow redirects
            CURLOPT_ENCODING       => "",       // handle all encodings
            CURLOPT_AUTOREFERER    => true,     // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
            CURLOPT_TIMEOUT        => 120,      // timeout on response
            CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
            CURLINFO_HEADER_OUT    => true,
            CURLOPT_SSL_VERIFYPEER => true,     // Validate SSL Cert
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_COOKIE         => $cookiesIn
        );

        $ch      = curl_init( $url );
        curl_setopt_array( $ch, $options );
        $rough_content = curl_exec( $ch );
        $err     = curl_errno( $ch );
        $errmsg  = curl_error( $ch );
        $header  = curl_getinfo( $ch );
        curl_close( $ch );

        $header_content = substr($rough_content, 0, $header['header_size']);
        $body_content = trim(str_replace($header_content, '', $rough_content));
        $pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m"; 
        preg_match_all($pattern, $header_content, $matches); 
        $cookiesOut = implode("; ", $matches['cookie']);

        $header['errno']   = $err;
        $header['errmsg']  = $errmsg;
        $header['headers']  = $header_content;
        $header['content'] = $body_content;
        $header['cookies'] = $cookiesOut;
    return $header;
}

NOTE: In revisiting this function I noticed that I had disabled SSL checks in this code. That is generally a BAD thing even though in my particular case the site I was using it on was local and was safe. As a result I've modified this code to have SSL checks on by default. If for some reason you need to change that, you can simply update the value for CURLOPT_SSL_VERIFYPEER, but I wanted the code to be secure by default if someone uses this.

jQuery: Count number of list elements?

var listItems = $("#myList").children();

var count = listItems.length;

Of course you can condense this with

var count = $("#myList").children().length;

For more help with jQuery, http://docs.jquery.com/Main_Page is a good place to start.

Adding image inside table cell in HTML

You have a TH floating at the top of your table which isn't within a TR. Fix that.

With regards to your image problem you;re referencing the image absolutely from your computer's hard drive. Don't do that.

You also have a closing tag which shouldn't be there.

It should be:

<img src="h.gif" alt="" border="3" height="100" width="100" />

Also this:

<table border = 5 bordercolor = red align = center>

Your colspans are also messed up. You only seem to have three columns but have colspans of 14 and 4 in your code.

Should be:

<table border="5" bordercolor="red" align="center">

Also you have no DOCTYPE declared. You should at least add:

<!DOCTYPE html> 

How to find whether a ResultSet is empty or not in Java?

Immediately after your execute statement you can have an if statement. For example

ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
}

Subversion ignoring "--password" and "--username" options

I had a similar problem, I wanted to use a different user name for a svn+ssh repository. In the end, I used svn relocate (as described in in this answer. In my case, I'm using svn 1.6.11 and did the following:

svn switch --relocate \
    svn+ssh://olduser@svnserver/path/to/repo \
    svn+ssh://newuser@svnserver/path/to/repo

where svn+ssh://olduser@svnserver/path/to/repo can be found in the URL: line output of svn info command. This command asked me for the password of newuser.

Note that this change is persistent, i.e. if you want only temporarily switch to the new username with this method, you'll have to issue a similar command again after svn update etc.

Difference between clean, gradlew clean

  1. ./gradlew clean

    Uses your project's gradle wrapper to execute your project's clean task. Usually, this just means the deletion of the build directory.

  2. ./gradlew clean assembleDebug

    Again, uses your project's gradle wrapper to execute the clean and assembleDebug tasks, respectively. So, it will clean first, then execute assembleDebug, after any non-up-to-date dependent tasks.

  3. ./gradlew clean :assembleDebug

    Is essentially the same as #2. The colon represents the task path. Task paths are essential in gradle multi-project's, not so much in this context. It means run the root project's assembleDebug task. Here, the root project is the only project.

  4. Android Studio --> Build --> Clean

    Is essentially the same as ./gradlew clean. See here.

For more info, I suggest taking the time to read through the Android docs, especially this one.

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

SQL Server: Maximum character length of object names

128 characters. This is the max length of the sysname datatype (nvarchar(128)).

How to check if keras tensorflow backend is GPU or CPU version?

Also you can check using Keras backend function:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

I test this on Keras (2.1.1)

How do I get sed to read from standard input?

To make sed catch from stdin , instead of from a file, you should use -e.

Like this:

curl -k -u admin:admin https://$HOSTNAME:9070/api/tm/3.8/status/$HOSTNAME/statistics/traffic_ips/trafc_ip/ | sed -e 's/["{}]//g' |sed -e 's/[]]//g' |sed -e 's/[\[]//g' |awk  'BEGIN{FS=":"} {print $4}'

Better way to sort array in descending order

Sure, You can customize the sort.

You need to give the Sort() a delegate to a comparison method which it will use to sort.

Using an anonymous method:

Array.Sort<int>( array,
delegate(int a, int b)
  {
    return b - a; //Normal compare is a-b
  }); 

Read more about it:

Sorting arrays
MSDN - Array.Sort Method (T[], Comparison)

What is the difference between "expose" and "publish" in Docker?

See the official documentation reference: https://docs.docker.com/engine/reference/builder/#expose

The EXPOSE allow you to define private (container) and public (host) ports to expose at image build time for when the container is running if you run the container with -P.

$ docker help run
...
  -P, --publish-all                    Publish all exposed ports to random ports
...

The public port and protocol are optional, if not a public port is specified, a random port will be selected on host by docker to expose the specified container port on Dockerfile.

A good pratice is do not specify public port, because it limits only one container per host ( a second container will throw a port already in use ).

You can use -p in docker run to control what public port the exposed container ports will be connectable.

Anyway, If you do not use EXPOSE (with -P on docker run) nor -p, no ports will be exposed.

If you always use -p at docker run you do not need EXPOSE but if you use EXPOSE your docker run command may be more simple, EXPOSE can be useful if you don't care what port will be expose on host, or if you are sure of only one container will be loaded.

Disable Enable Trigger SQL server for a table

Below is the Dynamic Script to enable or disable the Triggers.

select 'alter table '+ (select Schema_name(schema_id) from sys.objects o 
where o.object_id = parent_id) + '.'+object_name(parent_id) + ' ENABLE TRIGGER '+
Name as EnableScript,*
from sys.triggers t 
where is_disabled = 1

Wrapping a react-router Link in an html button

Many of the solutions have focused on complicating things.

Using withRouter is a really long solution for something as simple as a button that links to somewhere else in the App.

If you are going for S.P.A. (single page application), the easiest answer I have found is to use with the button's equivalent className.

This ensures you are maintaining shared state / context without reloading your entire app as is done with

import { NavLink } from 'react-router-dom'; // 14.6K (gzipped: 5.2 K)

// Where link.{something} is the imported data
<NavLink className={`bx--btn bx--btn--primary ${link.className}`} to={link.href} activeClassName={'active'}>
    {link.label}
</NavLink>

// Simplified version:
<NavLink className={'bx--btn bx--btn--primary'} to={'/myLocalPath'}>
    Button without using withRouter
</NavLink>

Change fill color on vector asset in Android Studio

Android studio now supports vectors pre-lollipop. No PNG conversion. You can still change your fill color and it will work.

In you ImageView, use

 app:srcCompat="@drawable/ic_more_vert_24dp"

In your gradle file,

 // Gradle Plugin 2.0+  
 android {  
   defaultConfig {  
     vectorDrawables.useSupportLibrary = true  
   }  
 }  

 compile 'com.android.support:design:23.4.0'

How to automatically generate unique id in SQL like UID12345678?

Reference:https://docs.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql?view=sql-server-2017

-- Creating a table using NEWID for uniqueidentifier data type.

CREATE TABLE cust  
(  
 CustomerID uniqueidentifier NOT NULL  
   DEFAULT newid(),  
 Company varchar(30) NOT NULL,  
 ContactName varchar(60) NOT NULL,   
 Address varchar(30) NOT NULL,   
 City varchar(30) NOT NULL,  
 StateProvince varchar(10) NULL,  
 PostalCode varchar(10) NOT NULL,   
 CountryRegion varchar(20) NOT NULL,   
 Telephone varchar(15) NOT NULL,  
 Fax varchar(15) NULL  
);  
GO  
-- Inserting 5 rows into cust table.  
INSERT cust  
(CustomerID, Company, ContactName, Address, City, StateProvince,   
 PostalCode, CountryRegion, Telephone, Fax)  
VALUES  
 (NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,  
 '90110', 'Finland', '981-443655', '981-443655')  
,(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',  
 '08737-363', 'Brasil', '(14) 555-8122', '')  
,(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,   
 '1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')  
,(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,  
 '8010', 'Austria', '7675-3425', '7675-3426')  
,(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,  
 'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');  
GO

Passing parameter to controller action from a Html.ActionLink

You are using the incorrect overload of ActionLink. Try this

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

Best way in asp.net to force https for an entire site?

If you are unable to set this up in IIS for whatever reason, I'd make an HTTP module that does the redirect for you:

using System;
using System.Web;

namespace HttpsOnly
{
    /// <summary>
    /// Redirects the Request to HTTPS if it comes in on an insecure channel.
    /// </summary>
    public class HttpsOnlyModule : IHttpModule
    {
        public void Init(HttpApplication app)
        {
            // Note we cannot trust IsSecureConnection when 
            // in a webfarm, because usually only the load balancer 
            // will come in on a secure port the request will be then 
            // internally redirected to local machine on a specified port.

            // Move this to a config file, if your behind a farm, 
            // set this to the local port used internally.
            int specialPort = 443;

            if (!app.Context.Request.IsSecureConnection 
               || app.Context.Request.Url.Port != specialPort)
            {
               app.Context.Response.Redirect("https://" 
                  + app.Context.Request.ServerVariables["HTTP_HOST"] 
                  + app.Context.Request.RawUrl);    
            }
        }

        public void Dispose()
        {
            // Needed for IHttpModule
        }
    }
}

Then just compile it to a DLL, add it as a reference to your project and place this in web.config:

 <httpModules>
      <add name="HttpsOnlyModule" type="HttpsOnly.HttpsOnlyModule, HttpsOnly" />
 </httpModules>

Python Error: "ValueError: need more than 1 value to unpack"

You have to pass the arguments in the terminal in order to store them in 'argv'. This variable holds the arguments you pass to your Python script when you run it. It later unpacks the arguments and store them in different variables you specify in the program e.g.

script, first, second = argv
print "Your file is:", script
print "Your first entry is:", first
print "Your second entry is:" second

Then in your command line you have to run your code like this,

$python ex14.py Hamburger Pizza

Your output will look like this:

Your file is: ex14.py
Your first entry is: Hamburger
Your second entry is: Pizza

What is the difference between declarations, providers, and import in NgModule?

Angular @NgModule constructs:

  1. import { x } from 'y';: This is standard typescript syntax (ES2015/ES6 module syntax) for importing code from other files. This is not Angular specific. Also this is technically not part of the module, it is just necessary to get the needed code within scope of this file.
  2. imports: [FormsModule]: You import other modules in here. For example we import FormsModule in the example below. Now we can use the functionality which the FormsModule has to offer throughout this module.
  3. declarations: [OnlineHeaderComponent, ReCaptcha2Directive]: You put your components, directives, and pipes here. Once declared here you now can use them throughout the whole module. For example we can now use the OnlineHeaderComponent in the AppComponent view (html file). Angular knows where to find this OnlineHeaderComponent because it is declared in the @NgModule.
  4. providers: [RegisterService]: Here our services of this specific module are defined. You can use the services in your components by injecting with dependency injection.

Example module:

// Angular
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

// Components
import { AppComponent } from './app.component';
import { OfflineHeaderComponent } from './offline/offline-header/offline-header.component';
import { OnlineHeaderComponent } from './online/online-header/online-header.component';

// Services
import { RegisterService } from './services/register.service';

// Directives
import { ReCaptcha2Directive } from './directives/re-captcha2.directive';

@NgModule({
  declarations: [
    OfflineHeaderComponent,,
    OnlineHeaderComponent,
    ReCaptcha2Directive,
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
  ],
  providers: [
    RegisterService,
  ],
  entryComponents: [
    ChangePasswordComponent,
    TestamentComponent,
    FriendsListComponent,
    TravelConfirmComponent
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

How to escape special characters of a string with single backslashes

Simply using re.sub might also work instead of str.maketrans. And this would also work in python 2.x

>>> print(re.sub(r'(\-|\]|\^|\$|\*|\.|\\)',lambda m:{'-':'\-',']':'\]','\\':'\\\\','^':'\^','$':'\$','*':'\*','.':'\.'}[m.group()],"^stack.*/overflo\w$arr=1"))
\^stack\.\*/overflo\\w\$arr=1

How to apply a low-pass or high-pass filter to an array in Matlab?

Look at the filter function.

If you just need a 1-pole low-pass filter, it's

xfilt = filter(a, [1 a-1], x);

where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.

Here's the corresponding high-pass filter:

xfilt = filter([1-a a-1],[1 a-1], x);

If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.

What are Bearer Tokens and token_type in OAuth 2?

From RFC 6750, Section 1.2:

Bearer Token

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer Token or Refresh token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for your a Bearer Token (refresh token) which you can then use to get an access token.

The Bearer Token is normally some kind of cryptic value created by the authentication server, it isn't random it is created based upon the user giving you access and the client your application getting access.

See also: Mozilla MDN Header Information.

matching query does not exist Error in Django

You can use this in your case, it will work fine.

user = UniversityDetails.objects.filter(email=email).first()

How to convert C++ Code to C

While you can do OO in C (e.g. by adding a theType *this first parameter to methods, and manually handling something like vtables for polymorphism) this is never particularly satisfactory as a design, and will look ugly (even with some pre-processor hacks).

I would suggest at least looking at a re-design to compare how this would work out.

Overall a lot depends on the answer to the key question: if you have working C++ code, why do you want C instead?

Can a table row expand and close?

To answer your question, no. That would be possible with div though. THe only question is would cause a hazzle if the functionality were done with div rather than tables.

Laravel: Validation unique on update

This is what I ended up doing. I'm sure there is a more efficient way of doing this but this is what i came up with.

Model/User.php

protected $rules = [
    'email_address' => 'sometimes|required|email|unique:users,email_address, {{$id}}',
];

Model/BaseModel.php

public function validate($data, $id = null) {


      $rules = $this->$rules_string;

     //let's loop through and explode the validation rules
     foreach($rules as $keys => $value) {

        $validations = explode('|', $value);

        foreach($validations as $key=>$value) {

            // Seearch for {{$id}} and replace it with $id
            $validations[$key] = str_replace('{{$id}}', $id, $value);

        }
        //Let's create the pipe seperator 
        $implode = implode("|", $validations);
        $rules[$keys] = $implode;

     }
     ....

  }

I pass the $user_id to the validation in the controller

Controller/UserController.php

public function update($id) { 

   .....

    $user = User::find($user_id);

    if($user->validate($formRequest, $user_id)) {
      //validation succcess 
    } 

    ....


}

Android: TextView: Remove spacing and padding on top and bottom

If you use AppCompatTextView ( or from API 28 onward ) you can use the combination of those 2 attributes to remove the spacing on the first line:

XML

android:firstBaselineToTopHeight="0dp"
android:includeFontPadding="false"

Kotlin

text.firstBaselineToTopHeight = 0
text.includeFontPadding = false

Who is listening on a given TCP port on Mac OS X?

Inspired by user Brent Self:

lsof -i 4 -a | grep LISTEN

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I tried the following:

aws s3 ls s3.console.aws.amazon.com/s3/buckets/{bucket name}

This gave me the error:

An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied

Using this form worked:

aws s3 ls {bucket name}

How to terminate a Python script

from sys import exit
exit()

As a parameter you can pass an exit code, which will be returned to OS. Default is 0.

java: HashMap<String, int> not working

You can use reference type in generic arguments, not primitive type. So here you should use

Map<String, Integer> myMap = new HashMap<String, Integer>();

and store value as

myMap.put("abc", 5);

Python os.path.join on Windows

The reason os.path.join('C:', 'src') is not working as you expect is because of something in the documentation that you linked to:

Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

As ghostdog said, you probably want mypath=os.path.join('c:\\', 'sourcedir')

Specify the date format in XMLGregorianCalendar

you don't need to specify a "SimpleDateFormat", it's simple: You must do specify the constant "DatatypeConstants.FIELD_UNDEFINED" where you don't want to show

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date());
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);

Keyboard shortcut to comment lines in Sublime Text 2

On a Mac with a US keyboard, you want cmd+/.

App installation failed due to application-identifier entitlement

I encountered this issue because I built to the phone with my code signing turned off from another machine, so you need to uninstall the app from the phone before installing/building to the phone with code signing on.

Elegant way to read file into byte[] array in Java

This works for me:

File file = ...;
byte[] data = new byte[(int) file.length()];
try {
    new FileInputStream(file).read(data);
} catch (Exception e) {
    e.printStackTrace();
}

Best way to compare dates in Android

You can directly create a Calendar from a Date:

Calendar validDate = new GregorianCalendar();
validDate.setTime(strDate);
if (Calendar.getInstance().after(validDate)) {
    catalog_outdated = 1;
}

onchange event for html.dropdownlist

You can do this

@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem() 
  { 

       Text = "Newest to Oldest", Value = "0" }, new SelectListItem() { Text = "Oldest to Newest", Value = "1" } , new
       {
           onchange = @"form.submit();"
       }
})

How do I convert a number to a letter in Java?

public static string IntToLetters(int value)
{
string result = string.Empty;
while (--value >= 0)
{
    result = (char)('A' + value % 26 ) + result;
    value /= 26;
}
return result;
}

To meet the requirement of A being 1 instead of 0, I've added -- to the while loop condition, and removed the value-- from the end of the loop, if anyone wants this to be 0 for their own purposes, you can reverse the changes, or simply add value++; at the beginning of the entire method.

Way to ng-repeat defined number of times instead of repeating over array?

A simpler approach would be (for an example of 5 times):

<div ng-repeat="x in [].constructor(5) track by $index">
       ...
</div>

How to change working directory in Jupyter Notebook?

on Jupyter notebook, try this:

pwd                  #this shows the current directory 

if this is not the directory you like and you would like to change, try this:

import os 
os.chdir ('THIS SHOULD BE YOUR DESIRED DIRECTORY')

Then try pwd again to see if the directory is what you want.

It works for me.

How do I 'svn add' all unversioned files to SVN?

What works is this:

c:\work\repo1>svn add . --force

Adds the contents of subdirectories.

Does not add ignored files.

Lists what files were added.

The dot in the command indicates the current directory, this can replaced by a specific directory name or path if you want to add a different directory than the current one.

Complex nesting of partials and templates

You may use ng-include to avoid using nested ng-views.

http://docs.angularjs.org/api/ng/directive/ngInclude
http://plnkr.co/edit/ngdoc:example-example39@snapshot?p=preview

My index page I use ng-view. Then on my sub pages which I need to have nested frames. I use ng-include. The demo shows a dropdown. I replaced mine with a link ng-click. In the function I would put $scope.template = $scope.templates[0]; or $scope.template = $scope.templates[1];

$scope.clickToSomePage= function(){
  $scope.template = $scope.templates[0];
};

Fatal error: Call to undefined function: ldap_connect()

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

    extension=php_ldap.dll

  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin Restart Apache. You can now use functions of the LDAP Module!

Java - How to create a custom dialog box?

Well, you essentially create a JDialog, add your text components and make it visible. It might help if you narrow down which specific bit you're having trouble with.

Options for HTML scraping?

Scrubyt uses Ruby and Hpricot to do nice and easy web scraping. I wrote a scraper for my university's library service using this in about 30 minutes.

How to make input type= file Should accept only pdf and xls

Try this one:-

              <MyTextField
                id="originalFileName"
                type="file"
                inputProps={{ accept: '.xlsx, .xls, .pdf' }}
                required
                label="Document"
                name="originalFileName"
                onChange={e => this.handleFileRead(e)}
                size="small"
                variant="standard"
              />

"std::endl" vs "\n"

There might be performance issues, std::endl forces a flush of the output stream.

HTML Table cell background image alignment

This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:

<table>
    <tr>
        <td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
            Hello World
        </td>
    </tr>
</table>

How to get the index of an element in an IEnumerable?

An alternative to finding the index after the fact is to wrap the Enumerable, somewhat similar to using the Linq GroupBy() method.

public static class IndexedEnumerable
{
    public static IndexedEnumerable<T> ToIndexed<T>(this IEnumerable<T> items)
    {
        return IndexedEnumerable<T>.Create(items);
    }
}

public class IndexedEnumerable<T> : IEnumerable<IndexedEnumerable<T>.IndexedItem>
{
    private readonly IEnumerable<IndexedItem> _items;

    public IndexedEnumerable(IEnumerable<IndexedItem> items)
    {
        _items = items;
    }

    public class IndexedItem
    {
        public IndexedItem(int index, T value)
        {
            Index = index;
            Value = value;
        }

        public T Value { get; private set; }
        public int Index { get; private set; }
    }

    public static IndexedEnumerable<T> Create(IEnumerable<T> items)
    {
        return new IndexedEnumerable<T>(items.Select((item, index) => new IndexedItem(index, item)));
    }

    public IEnumerator<IndexedItem> GetEnumerator()
    {
        return _items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Which gives a use case of:

var items = new[] {1, 2, 3};
var indexedItems = items.ToIndexed();
foreach (var item in indexedItems)
{
    Console.WriteLine("items[{0}] = {1}", item.Index, item.Value);
}

What is the difference between README and README.md in GitHub projects?

.md stands for markdown and is generated at the bottom of your github page as html.

Typical syntax includes:

Will become a heading
==============

Will become a sub heading
--------------

*This will be Italic*

**This will be Bold**

- This will be a list item
- This will be a list item

    Add a indent and this will end up as code

For more details: http://daringfireball.net/projects/markdown/

How can I tell jackson to ignore a property for which I don't have control over the source code?

Mix-in annotations work pretty well here as already mentioned. Another possibility beyond per-property @JsonIgnore is to use @JsonIgnoreType if you have a type that should never be included (i.e. if all instances of GeometryCollection properties should be ignored). You can then either add it directly (if you control the type), or using mix-in, like:

@JsonIgnoreType abstract class MixIn { }
// and then register mix-in, either via SerializationConfig, or by using SimpleModule

This can be more convenient if you have lots of classes that all have a single 'IgnoredType getContext()' accessor or so (which is the case for many frameworks)

How to resize an Image C#

public string CreateThumbnail(int maxWidth, int maxHeight, string path)
{

    var image = System.Drawing.Image.FromFile(path);
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);
    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);
    var newImage = new Bitmap(newWidth, newHeight);
    Graphics thumbGraph = Graphics.FromImage(newImage);

    thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
    thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
    //thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

    thumbGraph.DrawImage(image, 0, 0, newWidth, newHeight);
    image.Dispose();

    string fileRelativePath = "newsizeimages/" + maxWidth + Path.GetFileName(path);
    newImage.Save(Server.MapPath(fileRelativePath), newImage.RawFormat);
    return fileRelativePath;
}

Click here http://bhupendrasinghsaini.blogspot.in/2014/07/resize-image-in-c.html

Elasticsearch: Failed to connect to localhost port 9200 - Connection refused

Edit /etc/elasticsearch/elasticsearch.yml and add the following line:

network.host: 0.0.0.0

This will "unset" this parameter and will allow connections from other IPs.