Programs & Examples On #W3wp.exe

0

Visual Studio breakpoints not being hit

My case is not mentioned here:
I have to run the web project on a fake domain (settup on IIS and /hosts/etc) because of the callbacks from a third party site.

I was seeing two w3wp processes in the process list of VS:
w3wp.exe User Name: IIS APPPOOL\Default app pool
w3wp.exe User Name: IIS APPPOOL.svc

I had to to manually attach to second one to be able to debug.

So I realised the app pool of my Fake domain in iis is not set to "Default app pool"

enter image description here

https://manage.accuwebhosting.com/knowledgebase/2532/How-to-change-application-pool-from-IIS.html

As soon as I changed the domain's app pool to the "Default app pool" visual studio started to debug the web app.

What is w3wp.exe?

An Internet Information Services (IIS) worker process is a windows process (w3wp.exe) which runs Web applications, and is responsible for handling requests sent to a Web Server for a specific application pool.

It is the worker process for IIS. Each application pool creates at least one instance of w3wp.exe and that is what actually processes requests in your application. It is not dangerous to attach to this, that is just a standard windows message.

IIS AppPoolIdentity and file system write access permissions

Each application pool in IIs creates its own secure user folder with FULL read/write permission by default under c:\users. Open up your Users folder and see what application pool folders are there, right click, and check their rights for the application pool virtual account assigned. You should see your application pool account added already with read/write access assigned to its root and subfolders.

So that type of file storage access is automatically done and you should be able to write whatever you like there in the app pools user account folders without changing anything. That's why virtual user accounts for each application pool were created.

Server cannot set status after HTTP headers have been sent IIS7.5

If someone still having this problem.Try to use instead of ovverriding

 public void OnActionExecuting(ActionExecutingContext context)
    {
        try
        {

            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (!HttpContext.Current.Response.IsRequestBeingRedirected)
                {

                    context.Result = new RedirectToRouteResult(
                new RouteValueDictionary {  { "controller", "Login" }, { "action", "Index" } });
                }
            }

        }
        catch (Exception ex)
        {
               new RouteValueDictionary { { "controller", "Login" }, { "action", "Index" } });
        }

    }

W3WP.EXE using 100% CPU - where to start?

This is a guess at best, but perhaps your development team is building and deploying the application in debug mode, in stead of release mode. This will cause the occurrence of .pdb files. The implication of this is that your application will take up additional resources to collect system state and debugging information during the execution of your system, causing more processor utilization.

So, it would be simple enough to ensure that they are building and deploying in release mode.

Add IIS 7 AppPool Identities as SQL Server Logons

If you're going across machines, you either need to be using NETWORK SERVICE, LOCAL SYSTEM, a domain account, or a SQL 2008 R2 (if you have it) Managed Service Account (which is my preference if you had such an infrastructure). You can not use an account which is not visible to the Active Directory domain.

View JSON file in Browser

In Chrome, use JSONView to view formatted JSON.

To view "local" *.json files: - after install You must open the Extensions option from Window menu. - Check box next to "Allow Access to File URLs" - note that save is automatic (i.e. no explicit save necessary)

Re-open the *.json file and it should be formatted.

How to make an HTML back link?

history.go(-1) doesn't work if you click around in the 2nd domain or if the referrer is empty.

So we have to store the historyCount on arriving to this domain and go back the number of navigations in this side minus 1.


// if referrer is different from this site
if (!document.referrer.includes(window.location.host)) {
  // store current history length
  localStorage.setItem('historyLength', `${history.length}`);
}

// Return to stored referrer on logo click
document.querySelector('header .logo').addEventListener('click', 
  () =>
   history.go(Number(localStorage.getItem('historyLength')) - history.length -1)
);

How can I show a hidden div when a select option is selected?

you can use the following common function.

<div>
     <select class="form-control" 
             name="Extension for area validity sought for" 
             onchange="CommonShowHide('txtc1opt2', this, 'States')"
     >
         <option value="All India">All India</option>
         <option value="States">States</option>
     </select>

     <input type="text" 
            id="txtc1opt2" 
            style="display:none;" 
            name="Extension for area validity sought for details" 
            class="form-control" 
            value="" 
            placeholder="">

</div>
<script>
    function CommonShowHide(ElementId, element, value) {
         document
             .getElementById(ElementId)
             .style
             .display = element.value == value ? 'block' : 'none';
    }
</script>

If else in stored procedure sql server

You do not have to have the RETURN stament.

Have anther look at Using a Stored Procedure with Output Parameters

Also have another look at the OUT section in CREATE PROCEDURE

PHP cURL not working - WAMP on Windows 7 64 bit

I have struggled a lot with this myself.. In the end, PHP version 5.3.1 with Apache 2.2.9 worked...

I was getting the consistent error of missing php5.dll. For this, I renamed all the old php.ini files which are not required (outside of the WAMP folder) to old_ohp.ini.

how to view the contents of a .pem certificate

An alternative to using keytool, you can use the command

openssl x509 -in certificate.pem -text

This should work for any x509 .pem file provided you have openssl installed.

Check if current date is between two dates Oracle SQL

You don't need to apply to_date() to sysdate. It is already there:

select 1
from dual 
WHERE sysdate BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND TO_DATE('20/06/2014', 'DD/MM/YYYY');

If you are concerned about the time component on the date, then use trunc():

select 1
from dual 
WHERE trunc(sysdate) BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND
                             TO_DATE('20/06/2014', 'DD/MM/YYYY');

How to export data as CSV format from SQL Server using sqlcmd?

An answer above almost solved it for me but it does not correctly create a parsed CSV.

Here's my version:

sqlcmd -S myurl.com -d MyAzureDB -E -s, -W -i mytsql.sql | findstr /V /C:"-" /B > parsed_correctly.csv

Someone saying that sqlcmd is outdated in favor of some PowerShell alternative is forgetting that sqlcmd isn't just for Windows. I'm on Linux (and when on Windows I avoid PS anyway).

Having said all that, I do find bcp easier.

Is there a way to set background-image as a base64 encoded image?

I think this will help, Base64 is addressed by CSS in a different way, you should set the data type of the image to base64, this will help the CSS to change the base64 to image and display it to the user. and you can use this from javascript by assigning the background image using the jquery script, it will automatically change the base64 to mage and display it

_x000D_
_x000D_
url = "data:image;base64,"+data.replace(/(\r\n|\n|\r)/gm, "");_x000D_
$("body").css("background-image", "url('" + url.replace(/(\r\n|\n|\r)/gm, "") + "')");
_x000D_
_x000D_
_x000D_

Python Timezone conversion

Python 3.9 adds the zoneinfo module so now only the the standard library is needed!

>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime

>>> d = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo('America/Los_Angeles'))
>>> d.astimezone(ZoneInfo('Europe/Berlin'))  # 12:00 in Cali will be 20:00 in Berlin
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))

Wikipedia list of available time zones


Some functions such as now() and utcnow() return timezone-unaware datetimes, meaning they contain no timezone information. I recommend only requesting timezone-aware values from them using the keyword tz=ZoneInfo('localtime').

If astimezone gets a timezone-unaware input, it will assume it is local time, which can lead to errors:

>>> datetime.utcnow()  # UTC -- NOT timezone-aware!!
datetime.datetime(2020, 6, 1, 22, 39, 57, 376479)
>>> datetime.now()     # Local time -- NOT timezone-aware!!
datetime.datetime(2020, 6, 2, 0, 39, 57, 376675)

>>> datetime.now(tz=ZoneInfo('localtime'))  # timezone-aware
datetime.datetime(2020, 6, 2, 0, 39, 57, 376806, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> datetime.now(tz=ZoneInfo('Europe/Berlin'))  # timezone-aware
datetime.datetime(2020, 6, 2, 0, 39, 57, 376937, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))
>>> datetime.utcnow().astimezone(ZoneInfo('Europe/Berlin'))  # WRONG!!
datetime.datetime(2020, 6, 1, 22, 39, 57, 377562, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))

Windows has no system time zone database, so here an extra package is needed:

pip install tzdata  

There is a backport to allow use in Python 3.6 to 3.8:

sudo pip install backports.zoneinfo

Then:

from backports.zoneinfo import ZoneInfo

Function or sub to add new row and data to table

I needed this same solution, but if you use the native ListObject.Add() method then you avoid the risk of clashing with any data immediately below the table. The below routine checks the last row of the table, and adds the data in there if it's blank; otherwise it adds a new row to the end of the table:

Sub AddDataRow(tableName As String, values() As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = ActiveWorkbook.Worksheets("Sheet1")
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        For col = 1 To lastRow.Columns.Count
            If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
                table.ListRows.Add
                Exit For
            End If
        Next col
    Else
        table.ListRows.Add
    End If

    'Iterate through the last row and populate it with the entries from values()
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(values) + 1 Then lastRow.Cells(1, col) = values(col - 1)
    Next col
End Sub

To call the function, pass the name of the table and an array of values, one value per column. You can get / set the name of the table from the Design tab of the ribbon, in Excel 2013 at least: enter image description here

Example code for a table with three columns:

Dim x(2)
x(0) = 1
x(1) = "apple"
x(2) = 2
AddDataRow "Table1", x

C++ initial value of reference to non-const must be an lvalue

When you call test with &nKByte, the address-of operator creates a temporary value, and you can't normally have references to temporary values because they are, well, temporary.

Either do not use a reference for the argument, or better yet don't use a pointer.

Add Auto-Increment ID to existing table?

Proceed like that :

Make a dump of your database first

Remove the primary key like that

ALTER TABLE yourtable DROP PRIMARY KEY

Add the new column like that

ALTER TABLE yourtable add column Id INT NOT NULL AUTO_INCREMENT FIRST, ADD primary KEY Id(Id)

The table will be looked and the AutoInc updated.

How to handle change of checkbox using jQuery?

It seems to me removeProp is not working properly in Chrome : jsfiddle

        $('#badBut1').click(function () {
        checkit('Before');
        if( $('#chk').prop('checked') )
        {
          $('#chk').removeProp('checked');
        }else{
            $('#chk').prop('checked', true);
        }
        checkit('After');
    });
    $('#But1').click(function () {
        checkit('Before');
        if( $('#chk').prop('checked') )
        {
          $('#chk').removeClass('checked').prop('checked',false);
        }else{
            $('#chk').addClass('checked').prop('checked', true);
        }
        checkit('After');
    });

    $('#But2').click(function () {
        var chk1 = $('#chk').is(':checked');
        console.log("Value : " + chk1);
    });

    $('#chk').on( 'change',function () {
        checkit('Result');
    });
    function checkit(moment) {
        var chk1 = $('#chk').is(':checked');
        console.log(moment+", value = " + chk1);
    };

Daemon not running. Starting it now on port 5037

This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.

Take n rows from a spark dataframe and pass to toPandas()

Try it:

def showDf(df, count=None, percent=None, maxColumns=0):
    if (df == None): return
    import pandas
    from IPython.display import display
    pandas.set_option('display.encoding', 'UTF-8')
    # Pandas dataframe
    dfp = None
    # maxColumns param
    if (maxColumns >= 0):
        if (maxColumns == 0): maxColumns = len(df.columns)
        pandas.set_option('display.max_columns', maxColumns)
    # count param
    if (count == None and percent == None): count = 10 # Default count
    if (count != None):
        count = int(count)
        if (count == 0): count = df.count()
        pandas.set_option('display.max_rows', count)
        dfp = pandas.DataFrame(df.head(count), columns=df.columns)
        display(dfp)
    # percent param
    elif (percent != None):
        percent = float(percent)
        if (percent >=0.0 and percent <= 1.0):
            import datetime
            now = datetime.datetime.now()
            seed = long(now.strftime("%H%M%S"))
            dfs = df.sample(False, percent, seed)
            count = df.count()
            pandas.set_option('display.max_rows', count)
            dfp = dfs.toPandas()    
            display(dfp)

Examples of usages are:

# Shows the ten first rows of the Spark dataframe
showDf(df)
showDf(df, 10)
showDf(df, count=10)

# Shows a random sample which represents 15% of the Spark dataframe
showDf(df, percent=0.15) 

How can I get a favicon to show up in my django app?

Came across this while looking for help. I was trying to implement the favicon in my Django project and it was not showing -- wanted to add to the conversation.

While trying to implement the favicon in my Django project I renamed the 'favicon.ico' file to 'my_filename.ico' –– the image would not show. After renaming to 'favicon.ico' resolved the issue and graphic displayed. below is the code that resolved my issue:

<link rel="shortcut icon" type="image/png" href="{% static 'img/favicon.ico' %}" />

2 column div layout: right column with fixed width, left fluid

Simplest and most flexible solution so far it to use table display:

HTML, left div comes first, right div comes second ... we read and write left to right, so it won't make any sense to place the divs right to left

<div class="container">
    <div class="left">
        left content flexible width
    </div>
    <div class="right">
        right content fixed width
    </div>
</div>

CSS:

.container {
  display: table;
  width: 100%;
}

.left {
  display: table-cell;
  width: (whatever you want: 100%, 150px, auto)
}??

.right {
  display: table-cell;
  width: (whatever you want: 100%, 150px, auto)
}

Cases examples:

// One div is 150px fixed width ; the other takes the rest of the width
.left {width: 150px} .right {width: 100%}

// One div is auto to its inner width ; the other takes the rest of the width
.left {width: 100%} .right {width: auto}

How to use 'git pull' from the command line?

Try setting the HOME environment variable in Windows to your home folder (c:\users\username).

( you can confirm that this is the problem by doing echo $HOME in git bash and echo %HOME% in cmd - latter might not be available )

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

It is not an issue it is because of caching...

To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products').

After timestamp it should be axios.get(/api/products?${Date.now()}.

It will resolve your 304 status code.

Download file inside WebView

    mwebView.setDownloadListener(new DownloadListener()
   {

  @Override  


   public void onDownloadStart(String url, String userAgent,
        String contentDisposition, String mimeType,
        long contentLength) {

    DownloadManager.Request request = new DownloadManager.Request(
            Uri.parse(url));


    request.setMimeType(mimeType);


    String cookies = CookieManager.getInstance().getCookie(url);


    request.addRequestHeader("cookie", cookies);


    request.addRequestHeader("User-Agent", userAgent);


    request.setDescription("Downloading file...");


    request.setTitle(URLUtil.guessFileName(url, contentDisposition,
            mimeType));


    request.allowScanningByMediaScanner();


    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalPublicDir(
            Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
                    url, contentDisposition, mimeType));
    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    dm.enqueue(request);
    Toast.makeText(getApplicationContext(), "Downloading File",
            Toast.LENGTH_LONG).show();
}});

How do I associate file types with an iPhone application?

File type handling is new with iPhone OS 3.2, and is different than the already-existing custom URL schemes. You can register your application to handle particular document types, and any application that uses a document controller can hand off processing of these documents to your own application.

For example, my application Molecules (for which the source code is available) handles the .pdb and .pdb.gz file types, if received via email or in another supported application.

To register support, you will need to have something like the following in your Info.plist:

<key>CFBundleDocumentTypes</key>
<array>
    <dict>
        <key>CFBundleTypeIconFiles</key>
        <array>
            <string>Document-molecules-320.png</string>
            <string>Document-molecules-64.png</string>
        </array>
        <key>CFBundleTypeName</key>
        <string>Molecules Structure File</string>
        <key>CFBundleTypeRole</key>
        <string>Viewer</string>
        <key>LSHandlerRank</key>
        <string>Owner</string>
        <key>LSItemContentTypes</key>
        <array>
            <string>com.sunsetlakesoftware.molecules.pdb</string>
            <string>org.gnu.gnu-zip-archive</string>
        </array>
    </dict>
</array>

Two images are provided that will be used as icons for the supported types in Mail and other applications capable of showing documents. The LSItemContentTypes key lets you provide an array of Uniform Type Identifiers (UTIs) that your application can open. For a list of system-defined UTIs, see Apple's Uniform Type Identifiers Reference. Even more detail on UTIs can be found in Apple's Uniform Type Identifiers Overview. Those guides reside in the Mac developer center, because this capability has been ported across from the Mac.

One of the UTIs used in the above example was system-defined, but the other was an application-specific UTI. The application-specific UTI will need to be exported so that other applications on the system can be made aware of it. To do this, you would add a section to your Info.plist like the following:

<key>UTExportedTypeDeclarations</key>
<array>
    <dict>
        <key>UTTypeConformsTo</key>
        <array>
            <string>public.plain-text</string>
            <string>public.text</string>
        </array>
        <key>UTTypeDescription</key>
        <string>Molecules Structure File</string>
        <key>UTTypeIdentifier</key>
        <string>com.sunsetlakesoftware.molecules.pdb</string>
        <key>UTTypeTagSpecification</key>
        <dict>
            <key>public.filename-extension</key>
            <string>pdb</string>
            <key>public.mime-type</key>
            <string>chemical/x-pdb</string>
        </dict>
    </dict>
</array>

This particular example exports the com.sunsetlakesoftware.molecules.pdb UTI with the .pdb file extension, corresponding to the MIME type chemical/x-pdb.

With this in place, your application will be able to handle documents attached to emails or from other applications on the system. In Mail, you can tap-and-hold to bring up a list of applications that can open a particular attachment.

When the attachment is opened, your application will be started and you will need to handle the processing of this file in your -application:didFinishLaunchingWithOptions: application delegate method. It appears that files loaded in this manner from Mail are copied into your application's Documents directory under a subdirectory corresponding to what email box they arrived in. You can get the URL for this file within the application delegate method using code like the following:

NSURL *url = (NSURL *)[launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];

Note that this is the same approach we used for handling custom URL schemes. You can separate the file URLs from others by using code like the following:

if ([url isFileURL])
{
    // Handle file being passed in
}
else
{
    // Handle custom URL scheme
}

How do I delay a function call for 5 seconds?

var rotator = function(){
  widget.Rotator.rotate();
  setTimeout(rotator,5000);
};
rotator();

Or:

setInterval(
  function(){ widget.Rotator.rotate() },
  5000
);

Or:

setInterval(
  widget.Rotator.rotate.bind(widget.Rotator),
  5000
);

Rails: How can I rename a database column in a Ruby on Rails migration?

As an alternative option, if you are not married to the idea of migrations, there is a compelling gem for ActiveRecord which will handle the name changes automatically for you, Datamapper style. All you do is change the column name in your model (and make sure you put Model.auto_upgrade! at the bottom of your model.rb) and viola! Database is updated on the fly.

https://github.com/DAddYE/mini_record

Note: You will need to nuke db/schema.rb to prevent conflicts

Still in beta phases and obviously not for everyone but still a compelling choice (I am currently using it in two non-trivial production apps with no issues)

using sql count in a case statement

Depending on you flavor of SQL, you can also imply the else statement in your aggregate counts.

For example, here's a simple table Grades:

| Letters |
|---------|
| A       |
| A       |
| B       |
| C       |

We can test out each Aggregate counter syntax like this (Interactive Demo in SQL Fiddle):

SELECT
    COUNT(CASE WHEN Letter = 'A' THEN 1 END)           AS [Count - End],
    COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END) AS [Count - Else Null],
    COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END)    AS [Count - Else Zero],
    SUM(CASE WHEN Letter = 'A' THEN 1 END)             AS [Sum - End],
    SUM(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END)   AS [Sum - Else Null],
    SUM(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END)      AS [Sum - Else Zero]
FROM Grades

And here are the results (unpivoted for readability):

|    Description    | Counts |
|-------------------|--------|
| Count - End       |    2   |
| Count - Else Null |    2   |
| Count - Else Zero |    4   | *Note: Will include count of zero values
| Sum - End         |    2   |
| Sum - Else Null   |    2   |
| Sum - Else Zero   |    2   |

Which lines up with the docs for Aggregate Functions in SQL

Docs for COUNT:

COUNT(*) - returns the number of items in a group. This includes NULL values and duplicates.
COUNT(ALL expression) - evaluates expression for each row in a group, and returns the number of nonnull values.
COUNT(DISTINCT expression) - evaluates expression for each row in a group, and returns the number of unique, nonnull values.

Docs for SUM:

ALL - Applies the aggregate function to all values. ALL is the default.
DISTINCT - Specifies that SUM return the sum of unique values.

Joining three tables using MySQL

SELECT *
FROM user u
JOIN user_clockits uc ON u.user_id=uc.user_id
JOIN clockits cl ON cl.clockits_id=uc.clockits_id
WHERE user_id = 158

How to display a loading screen while site content loads

Typically sites that do this by loading content via ajax and listening to the readystatechanged event to update the DOM with a loading GIF or the content.

How are you currently loading your content?

The code would be similar to this:

function load(url) {
    // display loading image here...
    document.getElementById('loadingImg').visible = true;
    // request your data...
    var req = new XMLHttpRequest();
    req.open("POST", url, true);

    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            // content is loaded...hide the gif and display the content...
            if (req.responseText) {
                document.getElementById('content').innerHTML = req.responseText;
                document.getElementById('loadingImg').visible = false;
            }
        }
    };
    request.send(vars);
}

There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.

Where is the documentation for the values() method of Enum?

You can't see this method in javadoc because it's added by the compiler.

Documented in three places :

The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.

  • Enum.valueOf class
    (The special implicit values method is mentioned in description of valueOf method)

All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.

The values function simply list all values of the enumeration.

Change url query string value using jQuery

purls $.params() used without a parameter will give you a key-value object of the parameters.

jQuerys $.param() will build a querystring from the supplied object/array.

var params = parsedUrl.param();
delete params["page"];

var newUrl = "?page=" + $(this).val() + "&" + $.param(params);

Update
I've no idea why I used delete here...

var params = parsedUrl.param();
params["page"] = $(this).val();

var newUrl = "?" + $.param(params);

init-param and context-param

What is the difference between <init-param> and <context-param> !?

Single servlet versus multiple servlets.

Other Answers give details, but here is the summary:

A web app, that is, a “context”, is made up of one or more servlets.

  • <init-param> defines a value available to a single specific servlet within a context.
  • <context-param> defines a value available to all the servlets within a context.

cordova Android requirements failed: "Could not find an installed version of Gradle"

For me the problem was that my android version was still on 6.1.2 which is not compatible with the newest Android Studio 2.3.1.

So what I did was run

cordova platform rm android cordova platform add [email protected]

Test if object implements interface

I used

Assert.IsTrue(myObject is ImyInterface);

for a test in my unit test which tests that myObject is an object which has implemented my interface ImyInterface.

How to use Utilities.sleep() function

Some Google services do not like to be used to much. Quite recently my account was locked because of script, which was sending two e-mails per second to the same user. Google considered it as a spam. So using sleep here is also justified to prevent such situations.

Subtract a value from every number in a list in Python?

This will work:

for i in range(len(a)):
  a[i] -= 13

Best way to combine two or more byte arrays in C#

I took Matt's LINQ example one step further for code cleanliness:

byte[] rv = a1.Concat(a2).Concat(a3).ToArray();

In my case, the arrays are small, so I'm not concerned about performance.

How can I write these variables into one line of code in C#?

 DateTime dateTime = dateTime.Today.ToString("MM.dd.yyyy");

 Console.Write(dateTime);

How to check if type of a variable is string?

I've seen:

hasattr(s, 'endswith') 

Get string between two strings in a string

Something like this perhaps

private static string Between(string text, string from, string to)
{
    return text[(text.IndexOf(from)+from.Length)..text.IndexOf(to, text.IndexOf(from))];
}

Get all messages from Whatsapp

Yes, it must be ways to get msgs from WhatsApp, since there are some tools available on the market help WhatsApp users to backup WhatsApp chat history to their computer, I know this from here. Therefore, you must be able to implement such kind of app. Maybe you can find these tool on the market to see how they work.

How to set up default schema name in JPA configuration?

In order to avoid hardcoding schema in JPA Entity Java Classes we used orm.xml mapping file in Java EE application deployed in OracleApplicationServer10 (OC4J,Orion). It lays in model.jar/META-INF/ as well as persistence.xml. Mapping file orm.xml is referenced from peresistence.xml with tag

...
  <persistence-unit name="MySchemaPU"  transaction-type="JTA">
    <provider>
     <mapping-file>META-INF/orm.xml</mapping-file>
...

File orm.xml content is cited below:

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
                 version="1.0">
 <persistence-unit-metadata>

  <persistence-unit-defaults>
   <schema>myschema</schema>
  </persistence-unit-defaults>
 </persistence-unit-metadata>
</entity-mappings>

Omitting the second expression when using the if-else shorthand

Tiny addition to this very old thread..

If your'e evaluating an expression inside a for/while loop with a ternary operator, and want to continue or break as a result - you're gonna have a problem because both continue&break aren't expressions, they're statements without any value.

This will produce Uncaught SyntaxError: Unexpected token continue

 for (const item of myArray) {
      item.value ? break : continue;
 }

If you really want a one-liner that returns a statement, you can use this instead:

  for (const item of myArray) {
      if (item.value) break; else continue;
  }
  • P.S - This code might raise some eyebrows. Just saying.. :)

Reading value from console, interactively

Here's a example:

const stdin = process.openStdin()

process.stdout.write('Enter name: ')

stdin.addListener('data', text => {
  const name = text.toString().trim()
  console.log('Your name is: ' + name)

  stdin.pause() // stop reading
})

Output:

Enter name: bob
Your name is: bob

How do I output an ISO 8601 formatted string in JavaScript?

Shortest, but not supported by Internet Explorer 8 and earlier:

new Date().toJSON()

Can one class extend two classes?

Familiar with multilevel hierarchy?

You can use subclass as superclass to your another class.

You can try this.

public class PreferenceActivity extends AbstractBillingActivity {}

then

public class Preferences extends PreferenceActivity {}

In this case, Preferences class inherits both PreferencesActivity and AbstractBillingActivity as well.

How to split a data frame?

You could also use

data2 <- data[data$sum_points == 2500, ]

This will make a dataframe with the values where sum_points = 2500

It gives :

airfoils sum_points field_points   init_t contour_t   field_t
...
491        5       2500         5625 0.000086  0.004272  6.321774
498        5       2500         5625 0.000087  0.004507  6.325083
504        5       2500         5625 0.000088  0.004370  6.336034
603        5        250        10000 0.000072  0.000525  1.111278
577        5        250        10000 0.000104  0.000559  1.111431
587        5        250        10000 0.000072  0.000528  1.111524
606        5        250        10000 0.000079  0.000538  1.111685
....
> data2 <- data[data$sum_points == 2500, ]
> data2
airfoils sum_points field_points   init_t contour_t   field_t
108        5       2500          625 0.000082  0.004329  0.733109
106        5       2500          625 0.000102  0.004564  0.733243
117        5       2500          625 0.000087  0.004321  0.733274
112        5       2500          625 0.000081  0.004428  0.733587

C# testing to see if a string is an integer?

It is possible to try this as well:

    var ix=Convert.ToInt32(x);
    if (x==ix) //if this condition is met, then x is integer
    {
        //your code here
    }

How to store Query Result in variable using mysql

Select count(*) from table_name into @var1; 
Select @var1;

Why is $$ returning the same id as the parent process?

You can use one of the following.

  • $! is the PID of the last backgrounded process.
  • kill -0 $PID checks whether it's still running.
  • $$ is the PID of the current shell.

What are the differences between virtual memory and physical memory?

Virtual memory is, among other things, an abstraction to give the programmer the illusion of having infinite memory available on their system.

Virtual memory mappings are made to correspond to actual physical addresses. The operating system creates and deals with these mappings - utilizing the page table, among other data structures to maintain the mappings. Virtual memory mappings are always found in the page table or some similar data structure (in case of other implementations of virtual memory, we maybe shouldn't call it the "page table"). The page table is in physical memory as well - often in kernel-reserved spaces that user programs cannot write over.

Virtual memory is typically larger than physical memory - there wouldn't be much reason for virtual memory mappings if virtual memory and physical memory were the same size.

Only the needed part of a program is resident in memory, typically - this is a topic called "paging". Virtual memory and paging are tightly related, but not the same topic. There are other implementations of virtual memory, such as segmentation.

I could be assuming wrong here, but I'd bet the things you are finding hard to wrap your head around have to do with specific implementations of virtual memory, most likely paging. There is no one way to do paging - there are many implementations and the one your textbook describes is likely not the same as the one that appears in real OSes like Linux/Windows - there are probably subtle differences.

I could blab a thousand paragraphs about paging... but I think that is better left to a different question targeting specifically that topic.

How to mock static methods in c# using MOQ framework?

Another option to transform the static method into a static Func or Action. For instance.

Original code:

    class Math
    {
        public static int Add(int x, int y)
        {
            return x + y;
        }

You want to "mock" the Add method, but you can't. Change the above code to this:

        public static Func<int, int, int> Add = (x, y) =>
        {
            return x + y;
        };

Existing client code doesn't have to change (maybe recompile), but source stays the same.

Now, from the unit-test, to change the behavior of the method, just reassign an in-line function to it:

    [TestMethod]
    public static void MyTest()
    {
        Math.Add = (x, y) =>
        {
            return 11;
        };

Put whatever logic you want in the method, or just return some hard-coded value, depending on what you're trying to do.

This may not necessarily be something you can do each time, but in practice, I found this technique works just fine.

[edit] I suggest that you add the following Cleanup code to your Unit Test class:

    [TestCleanup]
    public void Cleanup()
    {
        typeof(Math).TypeInitializer.Invoke(null, null);
    }

Add a separate line for each static class. What this does is, after the unit test is done running, it resets all the static fields back to their original value. That way other unit tests in the same project will start out with the correct defaults as opposed your mocked version.

Eclipse "Invalid Project Description" when creating new project from existing source

I solved this problem with using the following steps:

  1. File -> Import

  2. Click General then select Existing Projects into Workspace

  3. Click Next

  4. Browse the directory of the project

  5. Click Finish!

It worked for me

Convert Python dict into a dataframe

The error here, is since calling the DataFrame constructor with scalar values (where it expects values to be a list/dict/... i.e. have multiple columns):

pd.DataFrame(d)
ValueError: If using all scalar values, you must must pass an index

You could take the items from the dictionary (i.e. the key-value pairs):

In [11]: pd.DataFrame(d.items())  # or list(d.items()) in python 3
Out[11]:
             0    1
0   2012-07-02  392
1   2012-07-06  392
2   2012-06-29  391
3   2012-06-28  391
...

In [12]: pd.DataFrame(d.items(), columns=['Date', 'DateValue'])
Out[12]:
          Date  DateValue
0   2012-07-02        392
1   2012-07-06        392
2   2012-06-29        391

But I think it makes more sense to pass the Series constructor:

In [21]: s = pd.Series(d, name='DateValue')
Out[21]:
2012-06-08    388
2012-06-09    388
2012-06-10    388

In [22]: s.index.name = 'Date'

In [23]: s.reset_index()
Out[23]:
          Date  DateValue
0   2012-06-08        388
1   2012-06-09        388
2   2012-06-10        388

grep for special characters in Unix

A related note

To grep for carriage return, namely the \r character, or 0x0d, we can do this:

grep -F $'\r' application.log

Alternatively, use printf, or echo, for POSIX compatibility

grep -F "$(printf '\r')" application.log

And we can use hexdump, or less to see the result:

$ printf "a\rb" | grep -F $'\r' | hexdump -c
0000000   a  \r   b  \n

Regarding the use of $'\r' and other supported characters, see Bash Manual > ANSI-C Quoting:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard

Creating a comma separated list from IList<string> or IEnumerable<string>

You could also use something like the following after you have it converted to an array using one of the of methods listed by others:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Configuration;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();
            string[] itemList = { "Test1", "Test2", "Test3" };
            commaStr.AddRange(itemList);
            Console.WriteLine(commaStr.ToString()); //Outputs Test1,Test2,Test3
            Console.ReadLine();
        }
    }
}

Edit: Here is another example

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

In case of Mac OSX,

Go to Targets -> Build Phases click + to Copy new files build phases Select product directory and drop the file there.

Clean and run the project.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

I was running into a similar error in pywikipediabot. The .decode method is a step in the right direction but for me it didn't work without adding 'ignore':

ignore_encoding = lambda s: s.decode('utf8', 'ignore')

Ignoring encoding errors can lead to data loss or produce incorrect output. But if you just want to get it done and the details aren't very important this can be a good way to move faster.

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

You can use the tee command to redirect output:

/usr/bin/mysqldump -u user -pupasswd my-database | \
tee >(gzip -9 -c > /home/user/backup/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz)  | \
gzip> /home/user/backup2/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz 2>&1

see documentation here

Tensorflow image reading & display

First of all scipy.misc.imread and PIL are no longer available. Instead use imageio library but you need to install Pillow for that as a dependancy

pip install Pillow imageio

Then use the following code to load the image and get the details about it.

import imageio
import tensorflow as tf

path = 'your_path_to_image' # '~/Downloads/image.png'

img = imageio.imread(path)
print(img.shape) 

or

img_tf = tf.Variable(img)
print(img_tf.get_shape().as_list()) 

both work fine.

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

Scala has a lot of crazy features (particularly where implicit parameters are concerned) that look very complicated and academic, but are designed to make things easy to use. The most useful ones get syntactic sugar (like [A <% B] which means that an object of type A has an implicit conversion to an object of type B) and a well-documented explanation of what they do. But most of the time, as a client of these libraries you can ignore the implicit parameters and trust them to do the right thing.

In Java, should I escape a single quotation mark (') in String (double quoted)?

You don't need to escape the ' character in a String (wrapped in "), and you don't have to escape a " character in a char (wrapped in ').

Select rows from a data frame based on values in a vector

Similar to above, using filter from dplyr:

filter(df, fct %in% vc)

How to write a multidimensional array to a text file?

There exist special libraries to do just that. (Plus wrappers for python)

hope this helps

Comparing two files in linux terminal

You can also use:

sdiff file1 file2

To display differences side by side within your terminal!

Python print statement “Syntax Error: invalid syntax”

Use print("use this bracket -sample text")

In Python 3 print "Hello world" gives invalid syntax error.

To display string content in Python3 have to use this ("Hello world") brackets.

How to match "any character" in regular expression?

Yes that will work, though note that . will not match newlines unless you pass the DOTALL flag when compiling the expression:

Pattern pattern = Pattern.compile(".*123", Pattern.DOTALL);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();

Failed to execute 'atob' on 'Window'

Here I got the error: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

Because you didn't pass a base64-encoded string. Look at your functions: both download and dataURItoBlob do expect a data URI for some reason; you however are passing a plain html markup string to download in your example.

Not only is HTML invalid as base64, you are calling .split(',')[1] on it which will yield undefined - and "undefined" is not a valid base64-encoded string either.

I don't know, but I read that I need to encode my string to base64

That doesn't make much sense to me. You want to encode it somehow, only to decode it then?

What should I call and how?

Change the interface of your download function back to where it received the filename and text arguments.

Notice that the BlobBuilder does not only support appending whole strings (so you don't need to create those ArrayBuffer things), but also is deprecated in favor of the Blob constructor.

Can I put a name on my saved file?

Yes. Don't use the Blob constructor, but the File constructor.

function download(filename, text) {
    try {
        var file = new File([text], filename, {type:"text/plain"});
    } catch(e) {
        // when File constructor is not supported
        file = new Blob([text], {type:"text/plain"});
    }
    var url  = window.URL.createObjectURL(file);
    …
}

download('test.html', "<html>" + document.documentElement.innerHTML + "</html>");

See JavaScript blob filename without link on what to do with that object url, just setting the current location to it doesn't work.

close fxml window by code, javafx

  1. give your close button an fx:id, if you haven't yet: <Button fx:id="closeButton" onAction="#closeButtonAction">
  2. In your controller class:

    @FXML private javafx.scene.control.Button closeButton;
    
    @FXML
    private void closeButtonAction(){
        // get a handle to the stage
        Stage stage = (Stage) closeButton.getScene().getWindow();
        // do what you have to do
        stage.close();
    }
    

Screenshot sizes for publishing android app on Google Play

You can upload up to 8 screenshots. Those screenshots must be one of the dimensions (sizes) you listed; you can have multiple screenshots of the same dimensions.

Leverage browser caching, how on apache or .htaccess?

This is what I use to control headers/caching, I'm not an Apache pro, so let me know if there is room for improvement, but I know that this has been working well on all of my sites for some time now.

Mod_expires

http://httpd.apache.org/docs/2.2/mod/mod_expires.html

This module controls the setting of the Expires HTTP header and the max-age directive of the Cache-Control HTTP header in server responses. The expiration date can set to be relative to either the time the source file was last modified, or to the time of the client access.

These HTTP headers are an instruction to the client about the document's validity and persistence. If cached, the document may be fetched from the cache rather than from the source until this time has passed. After that, the cache copy is considered "expired" and invalid, and a new copy must be obtained from the source.

# BEGIN Expires
<ifModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 seconds"
ExpiresByType text/html "access plus 1 seconds"
ExpiresByType image/gif "access plus 2592000 seconds"
ExpiresByType image/jpeg "access plus 2592000 seconds"
ExpiresByType image/png "access plus 2592000 seconds"
ExpiresByType text/css "access plus 604800 seconds"
ExpiresByType text/javascript "access plus 216000 seconds"
ExpiresByType application/x-javascript "access plus 216000 seconds"
</ifModule>
# END Expires

Mod_headers

http://httpd.apache.org/docs/2.2/mod/mod_headers.html

This module provides directives to control and modify HTTP request and response headers. Headers can be merged, replaced or removed.

# BEGIN Caching
<ifModule mod_headers.c>
<filesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
<filesMatch "\.(css)$">
Header set Cache-Control "max-age=604800, public"
</filesMatch>
<filesMatch "\.(js)$">
Header set Cache-Control "max-age=216000, private"
</filesMatch>
<filesMatch "\.(xml|txt)$">
Header set Cache-Control "max-age=216000, public, must-revalidate"
</filesMatch>
<filesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=1, private, must-revalidate"
</filesMatch>
</ifModule>
# END Caching

How to use Git?

I think gitready is a great starting point. I'm using git for a project now and that site pretty much got the ball rolling for me.

How to set the From email address for mailx command?

In case you also want to include your real name in the from-field, you can use the following format

mailx -r "[email protected] (My Name)" -s "My Subject" ...

If you happen to have non-ASCII characters in you name, like My AEÆoeøaaå (Æ= C3 86, ø= C3 B8, å= C3 A5), you have to encode them like this:

mailx -r "[email protected] (My =?utf-8?Q?AE=C3=86oe=C3=B8aa=C3=A5?=)" -s "My Subject" ...

Hope this can save someone an hour of hard work/research!

What is the use of join() in Python threading?

There are a few reasons for the main thread (or any other thread) to join other threads

  1. A thread may have created or holding (locking) some resources. The join-calling thread may be able to clear the resources on its behalf

  2. join() is a natural blocking call for the join-calling thread to continue after the called thread has terminated.

If a python program does not join other threads, the python interpreter will still join non-daemon threads on its behalf.

What is the difference between a web API and a web service?

Well, TMK may be right in the Microsoft world, but in world of all software including Java/Python/etc, I believe that there is no difference. They're the same thing.

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

It should work as well

Eval("item") == null?"0": Eval("item");

Git ignore file for Xcode projects

I use the following .gitignore file generated in gitignore.io:

### Xcode ###
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.xcuserstate


### Objective-C ###
# Xcode
#
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate

# CocoaPods
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control
#
Pods/

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

Master:

mysqldump -u root -p --all-databases --master-data | gzip > /tmp/dump.sql.gz  

scp master:/tmp/dump.sql.gz slave:/tmp/ Move dump file to slave server

Slave:

STOP SLAVE;

zcat /tmp/dump.sql.gz | mysql -u root -p

START SLAVE;
SHOW SLAVE STATUS;  

NOTE:
On master you can run SET GLOBAL expire_logs_days = 3 to keep binlogs for 3 days in case of slave issues.

Getters \ setters for dummies

If you're referring to the concept of accessors, then the simple goal is to hide the underlying storage from arbitrary manipulation. The most extreme mechanism for this is

function Foo(someValue) {
    this.getValue = function() { return someValue; }
    return this;
}

var myFoo = new Foo(5);
/* We can read someValue through getValue(), but there is no mechanism
 * to modify it -- hurrah, we have achieved encapsulation!
 */
myFoo.getValue();

If you're referring to the actual JS getter/setter feature, eg. defineGetter/defineSetter, or { get Foo() { /* code */ } }, then it's worth noting that in most modern engines subsequent usage of those properties will be much much slower than it would otherwise be. eg. compare performance of

var a = { getValue: function(){ return 5; }; }
for (var i = 0; i < 100000; i++)
    a.getValue();

vs.

var a = { get value(){ return 5; }; }
for (var i = 0; i < 100000; i++)
    a.value;

Multiprocessing a for loop?

Alternatively

with Pool() as pool: 
    pool.map(fits.open, [name + '.fits' for name in datainput])

twitter bootstrap navbar fixed top overlapping site

Your answer is right in the docs:

Body padding required

The fixed navbar will overlay your other content, unless you add padding to the top of the <body>. Try out your own values or use our snippet below. Tip: By default, the navbar is 50px high.

body { padding-top: 70px; }

Make sure to include this after the core Bootstrap CSS.

and in the Bootstrap 4 docs...

Fixed navbars use position: fixed, meaning they’re pulled from the normal flow of the DOM and may require custom CSS (e.g., padding-top on the ) to prevent overlap with other elements.

Zoom in on a point (using scale and translate)

Here's an alternate way to do it that uses setTransform() instead of scale() and translate(). Everything is stored in the same object. The canvas is assumed to be at 0,0 on the page, otherwise you'll need to subtract its position from the page coords.

this.zoomIn = function (pageX, pageY) {
    var zoomFactor = 1.1;
    this.scale = this.scale * zoomFactor;
    this.lastTranslation = {
        x: pageX - (pageX - this.lastTranslation.x) * zoomFactor,
        y: pageY - (pageY - this.lastTranslation.y) * zoomFactor
    };
    this.canvasContext.setTransform(this.scale, 0, 0, this.scale,
                                    this.lastTranslation.x,
                                    this.lastTranslation.y);
};
this.zoomOut = function (pageX, pageY) {
    var zoomFactor = 1.1;
    this.scale = this.scale / zoomFactor;
    this.lastTranslation = {
        x: pageX - (pageX - this.lastTranslation.x) / zoomFactor,
        y: pageY - (pageY - this.lastTranslation.y) / zoomFactor
    };
    this.canvasContext.setTransform(this.scale, 0, 0, this.scale,
                                    this.lastTranslation.x,
                                    this.lastTranslation.y);
};

Accompanying code to handle panning:

this.startPan = function (pageX, pageY) {
    this.startTranslation = {
        x: pageX - this.lastTranslation.x,
        y: pageY - this.lastTranslation.y
    };
};
this.continuePan = function (pageX, pageY) {
    var newTranslation = {x: pageX - this.startTranslation.x,
                          y: pageY - this.startTranslation.y};
    this.canvasContext.setTransform(this.scale, 0, 0, this.scale,
                                    newTranslation.x, newTranslation.y);
};
this.endPan = function (pageX, pageY) {
    this.lastTranslation = {
        x: pageX - this.startTranslation.x,
        y: pageY - this.startTranslation.y
    };
};

To derive the answer yourself, consider that the same page coordinates need to match the same canvas coordinates before and after the zoom. Then you can do some algebra starting from this equation:

(pageCoords - translation) / scale = canvasCoords

How to enable Logger.debug() in Log4j

This is happening due to the fact that the logging level of your logger is set to 'error' - therefore you will only see error messages or above this level in terms of severity so this is why you also see the 'fatal' message.

If you set the logging level to 'debug' on your logger in your log4j.xml you should see all messages.

Have a look at the log4j introduction for explaination.

How to get a jqGrid cell value when editing

I have a solution: 1. Using this.value to get the current editing value in the editing row. 2. Save the cell value to a hidden field when the cell lost its focus. 3. Read the hidden field when you need.

The code:

 colModel="[
       { name: 'Net', index: 'Net', editable:true, editoptions: { dataEvents: [ { type: 'focusout', fn: function(e) {$('#HiddenNet').val(this.value);} }] }, editrules:{custom:true,}},
       { name: 'Tax', index: 'Tax', editable:true, editoptions: { dataEvents: [ { type: 'focus', fn: function(e) {this.value=$('#HiddenNet').val(); } }] }, editrules:{custom:true}}
    ]" 

Good Luck

Split Div Into 2 Columns Using CSS

Divide a division in two columns is very easy, just specify the width of your column better if you put this (like width:50%) and set the float:left for left column and float:right for right column.

nginx - client_max_body_size has no effect

I had a similar problem recently and found out, that client_max_body_size 0; can solve such an issue. This will set client_max_body_size to no limit. But the best practice is to improve your code, so there is no need to increase this limit.

Appropriate datatype for holding percent values?

I agree with Thomas and I would choose the DECIMAL(5,4) solution at least for WPF applications.

Have a look to the MSDN Numeric Format String to know why : http://msdn.microsoft.com/en-us/library/dwhawy9k#PFormatString

The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a percentage.

Then you would be able to use this in your XAML code:

DataFormatString="{}{0:P}"

Remove legend ggplot 2.2

from r cookbook, where bp is your ggplot:

Remove legend for a particular aesthetic (fill):

bp + guides(fill=FALSE)

It can also be done when specifying the scale:

bp + scale_fill_discrete(guide=FALSE)

This removes all legends:

bp + theme(legend.position="none")

How to set JAVA_HOME in Linux for all users

This is a very simple script to solve the problem

export JAVA_HOME_BIN=`which java`
export JAVA_HOME_DIR=`dirname $JAVA_HOME_BIN`
export JAVA_HOME=`dirname $JAVA_HOME_DIR`

And for testing:

echo $JAVA_HOME

Downgrade npm to an older version

Before doing that Download Node Js 8.11.3 from the URL: download

Open command prompt and run this:

npm install -g [email protected]

use this version this is the stable version which works along with cordova 7.1.0

for installing cordova use : • npm install -g [email protected]

• Run command

• Cordova platform remove android (if you have old android code or code is having some issue)

• Cordova platform add android : for building android app in cordova Running: Corodva run android

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

I had the same problem with a stripes taglib uri showing as not found. I was using Indigo and Maven and when I checked Properties->Java Build Path->Order & Export Tab I found (on a fresh project checkout) that the "Maven Dependencies" checkbox was unchecked for some reason. Simply checking that box and doing a Maven clean install cleared all the errors.

I wonder why Eclipse doesn't assume I want my Maven dependencies in the build path...

Extract month and year from a zoo::yearmon object

The lubridate package is amazing for this kind of thing:

> require(lubridate)
> month(date1)
[1] 3
> year(date1)
[1] 2012

The ResourceConfig instance does not contain any root resource classes

In my case I have added the jars twice in build path after importing from war. It worked fine after removing the extra jars which was showing error deployment descriptor error pages

adding

<init-param>
          <param-name>com.sun.jersey.config.property.packages</param-name>
          <param-value>service.package.name</param-value>
</init-param>

How to stop mongo DB in one command

Building on the answer from stennie:

mongo --eval "db.getSiblingDB('admin').shutdownServer();quit()"

I found that mongo was trying to reconnect to the db after the server shut down, which would cause a delay and error messages. Adding quit() after shutdown speeds it up and reduces the messages, but there is still one.

I also want to add context - I'm starting and stopping mongod as part of test cases for other code, so registering as a service does not fit the use case. I am hoping to end up with something that runs on all platforms (this tested in windows right now). I'm using mongod 3.6.9

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

urlencode vs rawurlencode?

One practical reason to choose one over the other is if you're going to use the result in another environment, for example JavaScript.

In PHP urlencode('test 1') returns 'test+1' while rawurlencode('test 1') returns 'test%201' as result.

But if you need to "decode" this in JavaScript using decodeURI() function then decodeURI("test+1") will give you "test+1" while decodeURI("test%201") will give you "test 1" as result.

In other words the space (" ") encoded by urlencode to plus ("+") in PHP will not be properly decoded by decodeURI in JavaScript.

In such cases the rawurlencode PHP function should be used.

Is SQL syntax case sensitive?

SQL keywords are case insensitive themselves.

Names of tables, columns etc, have a case sensitivity which is database dependent - you should probably assume that they are case sensitive unless you know otherwise (In many databases they aren't though; in MySQL table names are SOMETIMES case sensitive but most other names are not).

Comparing data using =, >, < etc, has a case awareness which is dependent on the collation settings which are in use on the individual database, table or even column in question. It's normal however, to keep collation fairly consistent within a database. We have a few columns which need to store case-sensitive values; they have a collation specifically set.

Generator expressions vs. list comprehensions

The benefit of a generator expression is that it uses less memory since it doesn't build the whole list at once. Generator expressions are best used when the list is an intermediary, such as summing the results, or creating a dict out of the results.

For example:

sum(x*2 for x in xrange(256))

dict( (k, some_func(k)) for k in some_list_of_keys )

The advantage there is that the list isn't completely generated, and thus little memory is used (and should also be faster)

You should, though, use list comprehensions when the desired final product is a list. You are not going to save any memeory using generator expressions, since you want the generated list. You also get the benefit of being able to use any of the list functions like sorted or reversed.

For example:

reversed( [x*2 for x in xrange(256)] )

SQLite string contains other string query

While LIKE is suitable for this case, a more general purpose solution is to use instr, which doesn't require characters in the search string to be escaped. Note: instr is available starting from Sqlite 3.7.15.

SELECT *
  FROM TABLE  
 WHERE instr(column, 'cats') > 0;

Also, keep in mind that LIKE is case-insensitive, whereas instr is case-sensitive.

How to access global js variable in AngularJS directive

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

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

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

Example:

'use strict';

//my data variable that I need access to.
var data = null;

angular.module('sample', [])

Then in your controller:

.controller('SampleApp', function ($scope, $location) {

$scope.availableList = [];

$scope.init = function () {
    $scope.availableList = data;
}

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

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

Finally initialize your controller and init function.

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

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

Replace new lines with a comma delimiter with Notepad++?

This might sound strange but you can remove next line by copying the whole text and pasting it in firefox search bar, and then re-pasting it in notepad++

step 1

step 2

How do I force Robocopy to overwrite files?

From the documentation:

/is Includes the same files. /it Includes "tweaked" files.

"Same files" means files that are identical (name, size, times, attributes). "Tweaked files" means files that have the same name, size, and times, but different attributes.

robocopy src dst sample.txt /is      # copy if attributes are equal
robocopy src dst sample.txt /it      # copy if attributes differ
robocopy src dst sample.txt /is /it  # copy irrespective of attributes

This answer on Super User has a good explanation of what kind of files the selection parameters match.

With that said, I could reproduce the behavior you describe, but from my understanding of the documentation and the output robocopy generated in my tests I would consider this a bug.

PS C:\temp> New-Item src -Type Directory >$null
PS C:\temp> New-Item dst -Type Directory >$null
PS C:\temp> New-Item src\sample.txt -Type File -Value "test001" >$null
PS C:\temp> New-Item dst\sample.txt -Type File -Value "test002" >$null
PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00"
PS C:\temp> Set-ItemProperty dst\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00"
PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir
...
  Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30

------------------------------------------------------------------------------

                           1    C:\temp\src\
            Modified                   7        sample.txt

------------------------------------------------------------------------------

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :         1         0         0         0         0         0
   Files :         1         1         0         0         0         0
   Bytes :         7         7         0         0         0         0
...
PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir
...
  Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30

------------------------------------------------------------------------------

                           1    C:\temp\src\
            Same                       7        sample.txt

------------------------------------------------------------------------------

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :         1         0         0         0         0         0
   Files :         1         1         0         0         0         0
   Bytes :         7         7         0         0         0         0
...
PS C:\temp> Get-Content .\src\sample.txt
test001
PS C:\temp> Get-Content .\dst\sample.txt
test002

The file is listed as copied, and since it becomes a same file after the first robocopy run at least the times are synced. However, even though seven bytes have been copied according to the output no data was actually written to the destination file in both cases despite the data flag being set (via /copyall). The behavior also doesn't change if the data flag is set explicitly (/copy:d).

I had to modify the last write time to get robocopy to actually synchronize the data.

PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value (Get-Date)
PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir
...
  Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30

------------------------------------------------------------------------------

                           1    C:\temp\src\
100%        Newer                      7        sample.txt

------------------------------------------------------------------------------

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :         1         0         0         0         0         0
   Files :         1         1         0         0         0         0
   Bytes :         7         7         0         0         0         0
...
PS C:\temp> Get-Content .\dst\sample.txt
test001

An admittedly ugly workaround would be to change the last write time of same/tweaked files to force robocopy to copy the data:

& robocopy src dst /is /it /l /ndl /njh /njs /ns /nc |
  Where-Object { $_.Trim() } |
  ForEach-Object {
    $f = Get-Item $_
    $f.LastWriteTime = $f.LastWriteTime.AddSeconds(1)
  }
& robocopy src dst /copyall /mir

Switching to xcopy is probably your best option:

& xcopy src dst /k/r/e/i/s/c/h/f/o/x/y

How do you store Java objects in HttpSession?

You are not adding the object to the session, instead you are adding it to the request.
What you need is:

HttpSession session = request.getSession();
session.setAttribute("MySessionVariable", param);

In Servlets you have 4 scopes where you can store data.

  1. Application
  2. Session
  3. Request
  4. Page

Make sure you understand these. For more look here

sql - insert into multiple tables in one query

MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...

INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)

What is the difference between HTTP status code 200 (cache) vs status code 304?

This threw me for a long time too. The first thing I'd verify is that you're not reloading the page by clicking the refresh button, that will always issue a conditional request for resources and will return 304s for many of the page elements. Instead go up to the url bar select the page and hit enter as if you had just typed in the same URL again, that will give you a better indicator of what's being cached properly. This article does a great job explaining the difference between conditional and unconditional requests and how the refresh button affects them: http://blogs.msdn.com/b/ieinternals/archive/2010/07/08/technical-information-about-conditional-http-requests-and-the-refresh-button.aspx

How to get the Android Emulator's IP address?

public String getLocalIpAddress() {

    try {
        for (Enumeration < NetworkInterface > en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration < InetAddress > enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

How to get exit code when using Python subprocess communicate method?

You should first make sure that the process has completed running and the return code has been read out using the .wait method. This will return the code. If you want access to it later, it's stored as .returncode in the Popen object.

jquery json to string?

Most browsers have a native JSON object these days, which includes parse and stringify methods. So just try JSON.stringify({}) and see if you get "{}". You can even pass in parameters to filter out keys or to do pretty-printing, e.g. JSON.stringify({a:1,b:2}, null, 2) puts a newline and 2 spaces in front of each key.

JSON.stringify({a:1,b:2}, null, 2)

gives

"{\n  \"a\": 1,\n  \"b\": 2\n}"

which prints as

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

As for the messing around part of your question, use the second parameter. From http://www.javascriptkit.com/jsref/json.shtml :

The replacer parameter can either be a function or an array of String/Numbers. It steps through each member within the JSON object to let you decide what value each member should be changed to. As a function it can return:

  • A number, string, or Boolean, which replaces the property's original value with the returned one.
  • An object, which is serialized then returned. Object methods or functions are not allowed, and are removed instead.
  • Null, which causes the property to be removed.

As an array, the values defined inside it corresponds to the names of the properties inside the JSON object that should be retained when converted into a JSON object.

How can I check if a var is a string in JavaScript?

Combining the previous answers provides these solutions:

if (typeof str == 'string' || str instanceof String)

or

Object.prototype.toString.call(str) == '[object String]'

Method to find string inside of the text file. Then getting the following lines up to a certain limit

I am doing something similar but in C++. What you need to do is read the lines in one at a time and parse them (go over the words one by one). I have an outter loop that goes over all the lines and inside that is another loop that goes over all the words. Once the word you need is found, just exit the loop and return a counter or whatever you want.

This is my code. It basically parses out all the words and adds them to the "index". The line that word was in is then added to a vector and used to reference the line (contains the name of the file, the entire line and the line number) from the indexed words.

ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
    //Add the path to the list of file paths
    textFilePaths.push_back(path);
    int lineNumber = 1;
    while(!txtFile.eof())
    {
        txtFile.getline(line, 200);
        Line * ln = new Line(line, path, lineNumber);
        lineNumber++;
        myList.push_back(ln);
        vector<string> words = lineParser(ln);
        for(unsigned int i = 0; i < words.size(); i++)
        {
            index->addWord(words[i], ln);
        }
    }
    result = true;
}

How to store a command in a variable in a shell script?

Be Careful registering an order with the: X=$(Command)

This one is still executed Even before being called. To check and confirm this, you cand do:

echo test;
X=$(for ((c=0; c<=5; c++)); do
sleep 2;
done);
echo note the 5 seconds elapsed

Spring Boot Program cannot find main class

I am new in spring boot and using STS with maven build. I did all the things mentioned above but won't work for me. I noticed two problems in problem window of STS. There was a missing jar file on the path (C:\Users\UserName.m2\repository\com\jayway\jsonpath\json-path\2.2.0). I did following, the way is not strongly suggested but worked for me.

1) I deleted .m2 folder from the path location

2) Restarted STS

3) Right Click on project folder -> maven -> update project -> checked "Force update of snapshots/releases" -> Click Ok.

Maven updated its dependencies and the problem is solved.

How to use double or single brackets, parentheses, curly braces

In Bash, test and [ are shell builtins.

The double bracket, which is a shell keyword, enables additional functionality. For example, you can use && and || instead of -a and -o and there's a regular expression matching operator =~.

Also, in a simple test, double square brackets seem to evaluate quite a lot quicker than single ones.

$ time for ((i=0; i<10000000; i++)); do [[ "$i" = 1000 ]]; done

real    0m24.548s
user    0m24.337s
sys 0m0.036s
$ time for ((i=0; i<10000000; i++)); do [ "$i" = 1000 ]; done

real    0m33.478s
user    0m33.478s
sys 0m0.000s

The braces, in addition to delimiting a variable name are used for parameter expansion so you can do things like:

  • Truncate the contents of a variable

    $ var="abcde"; echo ${var%d*}
    abc
    
  • Make substitutions similar to sed

    $ var="abcde"; echo ${var/de/12}
    abc12
    
  • Use a default value

    $ default="hello"; unset var; echo ${var:-$default}
    hello
    
  • and several more

Also, brace expansions create lists of strings which are typically iterated over in loops:

$ echo f{oo,ee,a}d
food feed fad

$ mv error.log{,.OLD}
(error.log is renamed to error.log.OLD because the brace expression
expands to "mv error.log error.log.OLD")

$ for num in {000..2}; do echo "$num"; done
000
001
002

$ echo {00..8..2}
00 02 04 06 08

$ echo {D..T..4}
D H L P T

Note that the leading zero and increment features weren't available before Bash 4.

Thanks to gboffi for reminding me about brace expansions.

Double parentheses are used for arithmetic operations:

((a++))

((meaning = 42))

for ((i=0; i<10; i++))

echo $((a + b + (14 * c)))

and they enable you to omit the dollar signs on integer and array variables and include spaces around operators for readability.

Single brackets are also used for array indices:

array[4]="hello"

element=${array[index]}

Curly brace are required for (most/all?) array references on the right hand side.

ephemient's comment reminded me that parentheses are also used for subshells. And that they are used to create arrays.

array=(1 2 3)
echo ${array[1]}
2

Convert NSDate to String in iOS Swift

you get the detail information from Apple Dateformatter Document.If you want to set the dateformat for your dateString, see this link , the detail dateformat you can get here for e.g , do like

let formatter = DateFormatter()
// initially set the format based on your datepicker date / server String
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

let myString = formatter.string(from: Date()) // string purpose I add here 
// convert your string to date
let yourDate = formatter.date(from: myString)
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
// again convert your date to string
let myStringafd = formatter.string(from: yourDate!)

print(myStringafd)

you get the output as

enter image description here

POSTing JSON to URL via WebClient in C#

You need a json serializer to parse your content, probably you already have it, for your initial question on how to make a request, this might be an idea:

var baseAddress = "http://www.example.com/1.0/service/action";

var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";

string parsedContent = <<PUT HERE YOUR JSON PARSED CONTENT>>;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);

Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();

var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

hope it helps,

How to check if a string contains a specific text

you can use this code

$a = '';

if(!empty($a))
  echo 'text';

For Loop on Lua

By reading online (tables tutorial) it seems tables behave like arrays so you're looking for:

Way1

names = {'John', 'Joe', 'Steve'}
for i = 1,3 do print( names[i] ) end

Way2

names = {'John', 'Joe', 'Steve'}
for k,v in pairs(names) do print(v) end

Way1 uses the table index/key , on your table names each element has a key starting from 1, for example:

names = {'John', 'Joe', 'Steve'}
print( names[1] ) -- prints John

So you just make i go from 1 to 3.

On Way2 instead you specify what table you want to run and assign a variable for its key and value for example:

names = {'John', 'Joe', myKey="myValue" }
for k,v in pairs(names) do print(k,v) end

prints the following:

1   John
2   Joe
myKey   myValue

Git log out user from command line

Remove your SSH keys from ~/.ssh (or where you stored them).

Remove your user settings:

git config --global --unset user.name
git config --global --unset user.email
git config --global --unset credential.helper

Or all your global settings:

git config --global --unset-all

Maybe there's something else related to the credentials store, but I always used git over SSH.

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

1) I am using WAMP.

2) I have installed Open Office (from apache http://www.openoffice.org/download/).

3) $output_dir = "C:/wamp/www/projectfolder/"; this is my project folder where i want to create output file.

4) I have already placed my input file here C:/wamp/www/projectfolder/wordfile.docx";

Then I Run My Code.. (given below)

<?php
    set_time_limit(0);
    function MakePropertyValue($name,$value,$osm){
    $oStruct = $osm->Bridge_GetStruct("com.sun.star.beans.PropertyValue");
    $oStruct->Name = $name;
    $oStruct->Value = $value;
    return $oStruct;
    }
    function word2pdf($doc_url, $output_url){

    //Invoke the OpenOffice.org service manager
    $osm = new COM("com.sun.star.ServiceManager") or die ("Please be sure that OpenOffice.org is installed.\n");
    //Set the application to remain hidden to avoid flashing the document onscreen
    $args = array(MakePropertyValue("Hidden",true,$osm));
    //Launch the desktop
    $oDesktop = $osm->createInstance("com.sun.star.frame.Desktop");
    //Load the .doc file, and pass in the "Hidden" property from above
    $oWriterDoc = $oDesktop->loadComponentFromURL($doc_url,"_blank", 0, $args);
    //Set up the arguments for the PDF output
    $export_args = array(MakePropertyValue("FilterName","writer_pdf_Export",$osm));
    //print_r($export_args);
    //Write out the PDF
    $oWriterDoc->storeToURL($output_url,$export_args);
    $oWriterDoc->close(true);
    }

    $output_dir = "C:/wamp/www/projectfolder/";
    $doc_file = "C:/wamp/www/projectfolder/wordfile.docx";
    $pdf_file = "outputfile_name.pdf";

    $output_file = $output_dir . $pdf_file;
    $doc_file = "file:///" . $doc_file;
    $output_file = "file:///" . $output_file;
    word2pdf($doc_file,$output_file);
    ?>

What is the command for cut copy paste a file from one directory to other directory

mv in unix-ish systems, move in dos/windows.

e.g.

C:\> move c:\users\you\somefile.txt   c:\temp\newlocation.txt

and

$ mv /home/you/somefile.txt /tmp/newlocation.txt

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.

So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

Easiest way is use read only attribute to prevent direct user input:

 <input class="datepicker" type="text" name="date" value="" readonly />

Or you could use HTML5 validation based on pattern attribute. Date input pattern (dd/mm/yyyy or mm/dd/yyyy):

<input type="text" pattern="\d{1,2}/\d{1,2}/\d{4}" class="datepicker" name="date" value="" />

How to disable keypad popup when on edittext?

The best solution lies in the Project Manifest file (AndroidManifest.xml), add the following attribute in the activity construct

android:windowSoftInputMode="stateHidden"


Example:

    <activity android:name=".MainActivity" 
              android:windowSoftInputMode="stateHidden" />

Description:

  • The state of the soft keyboard — whether it is hidden or visible — when the activity becomes the focus of user attention.
  • The adjustment made to the activity's main window — whether it is resized smaller to make room for the soft keyboard or whether its contents pan to make the current focus visible when part of the window is covered by the soft keyboard.

Introduced in:

  • API Level 3.

Link to the Docs

Note: Values set here (other than "stateUnspecified" and "adjustUnspecified") override values set in the theme.

C# '@' before a String

It also means you can use reserved words as variable names

say you want a class named class, since class is a reserved word, you can instead call your class class:

IList<Student> @class = new List<Student>();

How to block calls in android

You can do it by listening to phone call events . You do it by having a BroadcastReceiver to PHONE_STATE and to NEW_OUTGOING_CALL. You find there what is the phone number.

Then when you decide to end the call, this is a bit tricky, because only from Android P it's guaranteed to work. Check here.

How to Generate a random number of fixed length using JavaScript?

I would go with this solution:

Math.floor(Math.random() * 899999 + 100000)

Calculating arithmetic mean (one type of average) in Python

Use statistics.mean:

import statistics
print(statistics.mean([1,2,4])) # 2.3333333333333335

It's available since Python 3.4. For 3.1-3.3 users, an old version of the module is available on PyPI under the name stats. Just change statistics to stats.

Sort array by firstname (alphabetically) in Javascript

Shortest possible code with ES6!

users.sort((a, b) => a.firstname.localeCompare(b.firstname))

String.prototype.localeCompare() basic support is universal!

Could not complete the operation due to error 80020101. IE

Switch off compatibility view if you use IE9.

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use the IP instead:

DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';

For more possibilities, see this link.

To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):

mysqladmin -u root password 'mynewpassword'

Documentation, and Lost root access in MySQL.

Oracle Convert Seconds to Hours:Minutes:Seconds

If you're just looking to convert a given number of seconds into HH:MI:SS format, this should do it

SELECT 
    TO_CHAR(TRUNC(x/3600),'FM9900') || ':' ||
    TO_CHAR(TRUNC(MOD(x,3600)/60),'FM00') || ':' ||
    TO_CHAR(MOD(x,60),'FM00')
FROM DUAL

where x is the number of seconds.

How to completely DISABLE any MOUSE CLICK

The easiest way to freeze the UI would be to make the AJAX call synchronous.

Usually synchronous AJAX calls defeat the purpose of using AJAX because it freezes the UI, but if you want to prevent the user from interacting with the UI, then do it.

How to convert an array to object in PHP?

one liner

$object= json_decode(json_encode($result_array, JSON_FORCE_OBJECT));

Printf long long int in C with GCC?

Try to update your compiler, I'm using GCC 4.7 on Windows 7 Starter x86 with MinGW and it compiles fine with the same options both in C99 and C11.

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

  • It did not work so i switched to oracle sql developer and it worked with no problems (making connection under 1 minute).
  • This link gave me an idea connect to MS Access so i created a user in oracle sql developer and the tried to connect to it in Toad and it worked.

Or second solution

you can try to connect using Direct not TNS by providing host and port in the connect screen of Toad

Passing parameter to controller from route in laravel

This is what you need in 1 line of code.

Route::get('/groups/{groupId}', 'GroupsController@getShow');

Suggestion: Use CamelCase as opposed to underscores, try & follow PSR-* guidelines.

Hope it helps.

The type is defined in an assembly that is not referenced, how to find the cause?

Check target framework in the projects.

In my case "You must add a reference to assembly" actually meant, that caller and reference projects didn't have the same target framework. The caller project had .Net 4.5 , but referenced library had target 4.6.1.

I am sure, that MS compiler can be smarter and log more meaningful error message. I've added a suggestion to https://github.com/dotnet/roslyn/issues/14756

How can I insert vertical blank space into an html document?

write it like this

p {
    padding-bottom: 3cm;
}

or

p {
    margin-bottom: 3cm;
}

How to fix/convert space indentation in Sublime Text?

I wrote a plugin for it. You can find it here or look for "ReIndent" in package control. It mostly does the same thing as Kyle Finley wrote but in a convenient way with shortcuts for converting between 2 and 4 and vice-versa.

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

This error is mainly due to processor architecture incompatibility with Framework installed ei x86 vs x64 The solution: Go to solution explorer>project properties>Compile tab>Advanced Compile Options There you have to change Target CPU from X64 to X86 Save new setting and recompile your solution. I tried it and it worked very fine. Hope this will help you out. Malek

UTF-8 output from PowerShell

Set the [Console]::OuputEncoding as encoding whatever you want, and print out with [Console]::WriteLine.

If powershell ouput method has a problem, then don't use it. It feels bit bad, but works like a charm :)

Create a string with n characters

Considering we have:

String c = "c"; // character to repeat, for empty it would be " ";
int n = 4; // number of times to repeat
String EMPTY_STRING = ""; // empty string (can be put in utility class)

Java 8 (Using Stream)

String resultOne = IntStream.range(0,n)
   .mapToObj(i->c).collect(Collectors.joining(EMPTY_STRING)); // cccc

Java 8 (Using nCopies)

String resultTwo = String.join(EMPTY_STRING, Collections.nCopies(n, c)); //cccc

RabbitMQ / AMQP: single queue, multiple consumers for same message?

There is one interesting option in this scenario I haven`t found in answers here.

You can Nack messages with "requeue" feature in one consumer to process them in another. Generally speaking it is not a right way, but maybe it will be good enough for someone.

https://www.rabbitmq.com/nack.html

And beware of loops (when all concumers nack+requeue message)!

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

Try to set the element's value using the executeScript method of JavascriptExecutor:

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");

How to get Locale from its String representation in Java?

  1. Java provides lot of things with proper implementation lot of complexity can be avoided. This returns ms_MY.

    String key = "ms-MY";
    Locale locale = new Locale.Builder().setLanguageTag(key).build();
    
  2. Apache Commons has LocaleUtils to help parse a string representation. This will return en_US

    String str = "en-US";
    Locale locale =  LocaleUtils.toLocale(str);
    System.out.println(locale.toString());
    
  3. You can also use locale constructors.

    // Construct a locale from a language code.(eg: en)
    new Locale(String language)
    // Construct a locale from language and country.(eg: en and US)
    new Locale(String language, String country)
    // Construct a locale from language, country and variant.
    new Locale(String language, String country, String variant)
    

Please check this LocaleUtils and this Locale to explore more methods.

Focus Next Element In Tab Index

As mentioned in a comment above, I don't think that any browsers expose tab order information. Here a simplified approximation of what the browser does to get the next element in tab order:

var allowedTags = {input: true, textarea: true, button: true};

var walker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW_ELEMENT,
  {
    acceptNode: function(node)
    {
      if (node.localName in allowedTags)
        return NodeFilter.FILTER_ACCEPT;
      else
        NodeFilter.FILTER_SKIP;
    }
  },
  false
);
walker.currentNode = currentElement;
if (!walker.nextNode())
{
  // Restart search from the start of the document
  walker.currentNode = walker.root;
  walker.nextNode();
}
if (walker.currentNode && walker.currentNode != walker.root)
  walker.currentNode.focus();

This only considers some tags and ignores tabindex attribute but might be enough depending on what you are trying to achieve.

How do I simulate a hover with a touch in touch enabled browsers?

Further Improved Solution

First I went with the Rich Bradshaw's approach, but then problems started to appear. By doing the e.preventDefault() on 'touchstart' event, the page no longer scrolls and, neither the long press is able to fire the options menu nor double click zoom is able to finish executing.

A solution could be finding out which event is being called and just e.preventDefault() in the later one, 'touchend'. Since scroll's 'touchmove' comes before 'touchend' it stays as by default, and 'click' is also prevented since it comes afterwords in the event chain applied to mobile, like so:

// Binding to the '.static_parent' ensuring dynamic ajaxified content
$('.static_parent').on('touchstart touchend', '.link', function (e) {

    // If event is 'touchend' then...
    if (e.type == 'touchend') {
        // Ensuring we event prevent default in all major browsers
        e.preventDefault ? e.preventDefault() : e.returnValue = false;
    }

    // Add class responsible for :hover effect
    $(this).toggleClass('hover_effect');
});

But then, when options menu appears, it no longer fires 'touchend' responsible for toggling off the class, and next time the hover behavior will be the other way around, totally mixed up.

A solution then would be, again, conditionally finding out which event we're in, or just doing separate ones, and use addClass() and removeClass() respectively on 'touchstart' and 'touchend', ensuring it always starts and ends by respectively adding and removing instead of conditionally deciding on it. To finish we will also bind the removing callback to the 'focusout' event type, staying responsible for clearing any link's hover class that might stay on and never revisited again, like so:

$('.static_parent').on('touchstart', '.link', function (e) {
    $(this).addClass('hover_effect');
});

$('.static_parent').on('touchend focusout', '.link', function (e) {
    // Think double click zoom still fails here
    e.preventDefault ? e.preventDefault() : e.returnValue = false;
    $(this).removeClass('hover_effect');
});

Atention: Some bugs still occur in the two previous solutions and, also think (not tested), double click zoom still fails too.

Tidy and Hopefully Bug Free (not :)) Javascript Solution

Now, for a second, cleaner, tidier and responsive, approach just using javascript (no mix between .hover class and pseudo :hover) and from where you could call directly your ajax behavior on the universal (mobile and desktop) 'click' event, I've found a pretty well answered question from which I finally understood how I could mix touch and mouse events together without several event callbacks inevitably changing each other's ones up the event chain. Here's how:

$('.static_parent').on('touchstart mouseenter', '.link', function (e) {
    $(this).addClass('hover_effect');
});

$('.static_parent').on('mouseleave touchmove click', '.link', function (e) {
    $(this).removeClass('hover_effect');

    // As it's the chain's last event we only prevent it from making HTTP request
    if (e.type == 'click') {
        e.preventDefault ? e.preventDefault() : e.returnValue = false;

        // Ajax behavior here!
    }
});

Laravel: Using try...catch with DB::transaction()

I've decided to give an answer to this question because I think it can be solved using a simpler syntax than the convoluted try-catch block. The Laravel documentation is pretty brief on this subject.

Instead of using try-catch, you can just use the DB::transaction(){...} wrapper like this:

// MyController.php
public function store(Request $request) {
    return DB::transaction(function() use ($request) {
        $user = User::create([
            'username' => $request->post('username')
        ]);

        // Add some sort of "log" record for the sake of transaction:
        $log = Log::create([
            'message' => 'User Foobar created'
        ]);

        // Lets add some custom validation that will prohibit the transaction:
        if($user->id > 1) {
            throw AnyException('Please rollback this transaction');
        }

        return response()->json(['message' => 'User saved!']);
    });
};

You should then see that the User and the Log record cannot exist without eachother.

Some notes on the implementation above:

  • Make sure to return the transaction, so that you can use the response() you return within its callback.
  • Make sure to throw an exception if you want the transaction to be rollbacked (or have a nested function that throws the exception for you automatically, like an SQL exception from within Eloquent).
  • The id, updated_at, created_at and any other fields are AVAILABLE AFTER CREATION for the $user object (for the duration of this transaction). The transaction will run through any of the creation logic you have. HOWEVER, the whole record is discarded when the AnyException is thrown. This means that for instance an auto-increment column for id does get incremented on failed transactions.

Tested on Laravel 5.8

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

According to this: https://www.simplified.guide/phpmyadmin/enable-login-without-password

This $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; should be added twice in /etc/phpmyadmin/config.inc.php

if (!empty($dbname)) {
    // other configuration options
    $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
    // it should be placed before the following line
    $i++;
}

// other configuration options
$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

How do I zip two arrays in JavaScript?

Zip Arrays of same length:

Using Array.prototype.map()

_x000D_
_x000D_
const zip = (a, b) => a.map((k, i) => [k, b[i]]);

console.log(zip([1,2,3], ["a","b","c"]));
// [[1, "a"], [2, "b"], [3, "c"]]
_x000D_
_x000D_
_x000D_

Zip Arrays of different length:

Using Array.from()

_x000D_
_x000D_
const zip = (a, b) => Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]]);

console.log( zip([1,2,3], ["a","b","c","d"]) );
// [[1, "a"], [2, "b"], [3, "c"], [undefined, "d"]]
_x000D_
_x000D_
_x000D_

Using Array.prototype.fill() and Array.prototype.map()

_x000D_
_x000D_
const zip = (a, b) => Array(Math.max(b.length, a.length)).fill().map((_,i) => [a[i], b[i]]);

console.log(zip([1,2,3], ["a","b","c","d"]));
// [[1, "a"], [2, "b"], [3, "c"], [undefined, 'd']]
_x000D_
_x000D_
_x000D_

connecting MySQL server to NetBeans

Fist of all make sure your SQL server is running. Actually I'm working on windows and I have installed a nice tool which is called MySQL workbench (you can find it here for almost any platform ).

you can see the server is running

Thus I just create a new database to test the connection, let's call it stackoverflow, with one table called user.

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

DROP SCHEMA IF EXISTS `stackoverflow` ;
CREATE SCHEMA IF NOT EXISTS `stackoverflow` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `stackoverflow` ;

-- -----------------------------------------------------
-- Table `stackoverflow`.`user`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `stackoverflow`.`user` ;

CREATE TABLE IF NOT EXISTS `stackoverflow`.`user` (
  `iduser` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(75) NOT NULL,
  `email` VARCHAR(150) NOT NULL,
  PRIMARY KEY (`iduser`),
  UNIQUE INDEX `iduser_UNIQUE` (`iduser` ASC),
  UNIQUE INDEX `email_UNIQUE` (`email` ASC))
ENGINE = InnoDB;


SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

You can reduce important part to

 CREATE SCHEMA IF NOT EXISTS `stackoverflow`

 CREATE TABLE IF NOT EXISTS `stackoverflow`.`user` (
      `iduser` INT NOT NULL AUTO_INCREMENT,
      `name` VARCHAR(75) NOT NULL,
      `email` VARCHAR(150) NOT NULL,
      PRIMARY KEY (`iduser`),
      UNIQUE INDEX `iduser_UNIQUE` (`iduser` ASC),
      UNIQUE INDEX `email_UNIQUE` (`email` ASC))

So now I have my brand new stackoverflow database. Let's connect to it throught Netbeans. Launch netbeans and go to the services panel list of connections available Now right click on databases: new connection.. Choose MySql connector, they already come packed with netbeans. connector Then fill in the gaps the data you need. As shown in the picture add the database name and remove from the connection url the optional parameters as l?zeroDateTimeBehaviour=convertToNull . Use the right user name and password and test the connection. data

As you can see connection is successful.

Click FINISH.

You will have your connection successfully working and available under the services.

finish

Is there a CSS selector for elements containing certain text?

Looks like they were thinking about it for the CSS3 spec but it didn't make the cut.

:contains() CSS3 selector http://www.w3.org/TR/css3-selectors/#content-selectors

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

Based on Kapitán Mlíko's answer with source above, I would change it to use the following:

Marlett Font Example

It's a better practice to use the Marlett font rather than Path Data points for the Minimize, Restore/Maximize and Close buttons.

<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" WindowChrome.IsHitTestVisibleInChrome="True" Grid.Row="0">
<Button Command="{Binding Source={x:Static SystemCommands.MinimizeWindowCommand}}" ToolTip="minimize" Style="{StaticResource WindowButtonStyle}">
    <Button.Content>
        <Grid Width="30" Height="25">
            <TextBlock Text="0" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="3.5,0,0,3" />
        </Grid>
    </Button.Content>
</Button>
<Grid Margin="1,0,1,0">
    <Button x:Name="Restore" Command="{Binding Source={x:Static SystemCommands.RestoreWindowCommand}}" ToolTip="restore" Visibility="Collapsed" Style="{StaticResource WindowButtonStyle}">
        <Button.Content>
            <Grid Width="30" Height="25" UseLayoutRounding="True">
                <TextBlock Text="2" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="2,0,0,1" />
            </Grid>
        </Button.Content>
    </Button>
    <Button x:Name="Maximize" Command="{Binding Source={x:Static SystemCommands.MaximizeWindowCommand}}" ToolTip="maximize" Style="{StaticResource WindowButtonStyle}">
        <Button.Content>
            <Grid Width="31" Height="25">
                <TextBlock Text="1" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="2,0,0,1" />
            </Grid>
        </Button.Content>
    </Button>
</Grid>
<Button Command="{Binding Source={x:Static SystemCommands.CloseWindowCommand}}" ToolTip="close"  Style="{StaticResource WindowButtonStyle}">
    <Button.Content>
        <Grid Width="30" Height="25">
            <TextBlock Text="r" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="0,0,0,1" />
        </Grid>
    </Button.Content>
</Button>

How to make all controls resize accordingly proportionally when window is maximized?

Just thought i'd share this with anyone who needs more clarity on how to achieve this:

myCanvas is a Canvas control and Parent to all other controllers. This code works to neatly resize to any resolution from 1366 x 768 upward. Tested up to 4k resolution 4096 x 2160

Take note of all the MainWindow property settings (WindowStartupLocation, SizeToContent and WindowState) - important for this to work correctly - WindowState for my user case requirement was Maximized

xaml

<Window x:Name="mainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyApp" 
    xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
    x:Class="MyApp.MainWindow" 
     Title="MainWindow"  SizeChanged="MainWindow_SizeChanged"
    Width="1366" Height="768" WindowState="Maximized" WindowStartupLocation="CenterOwner" SizeToContent="WidthAndHeight">
  
    <Canvas x:Name="myCanvas" HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="1356">
        <Image x:Name="maxresdefault_1_1__jpg" Source="maxresdefault-1[1].jpg" Stretch="Fill" Opacity="0.6" Height="767" Canvas.Left="-6" Width="1366"/>

        <Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" Height="0" Canvas.Left="-811" Canvas.Top="148" Width="766"/>
        <Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" HorizontalAlignment="Right" Width="210" Height="0" Canvas.Left="1653" Canvas.Top="102"/>
        <Image x:Name="imgscroll" Source="BcaKKb47i[1].png" Stretch="Fill" RenderTransformOrigin="0.5,0.5" Height="523" Canvas.Left="-3" Canvas.Top="122" Width="580">
            <Image.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="89.093"/>
                    <TranslateTransform/>
                </TransformGroup>
            </Image.RenderTransform>
        </Image>

.cs

 private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        myCanvas.Width = e.NewSize.Width;
        myCanvas.Height = e.NewSize.Height;

        double xChange = 1, yChange = 1;

        if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width / e.PreviousSize.Width);

        if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

        ScaleTransform scale = new ScaleTransform(myCanvas.LayoutTransform.Value.M11 * xChange, myCanvas.LayoutTransform.Value.M22 * yChange);
        myCanvas.LayoutTransform = scale;
        myCanvas.UpdateLayout();
    }

Generate 'n' unique random numbers within a range

You could add to a set until you reach n:

setOfNumbers = set()
while len(setOfNumbers) < n:
    setOfNumbers.add(random.randint(numLow, numHigh))

Be careful of having a smaller range than will fit in n. It will loop forever, unable to find new numbers to insert up to n

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

Select a cell in the cell range in which the data is imported, then Menu > Data > Properties > uncheck save query definition.

Properties will be greyed out unless a cell in the data import range is selected.

You can find out the range in which the data isimported by:

Menu > Data > Connections > (select connection) > Click here to see where the selected connections are used.

How to calculate UILabel width based on text length?

In iOS8 sizeWithFont has been deprecated, please refer to

CGSize yourLabelSize = [yourLabel.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:yourLabel.font size:yourLabel.fontSize]}];

You can add all the attributes you want in sizeWithAttributes. Other attributes you can set:

- NSForegroundColorAttributeName
- NSParagraphStyleAttributeName
- NSBackgroundColorAttributeName
- NSShadowAttributeName

and so on. But probably you won't need the others

Differences between "java -cp" and "java -jar"?

There won't be any difference in terms of performance. Using java - cp we can specify the required classes and jar's in the classpath for running a java class file.

If it is a executable jar file . When java -jar command is used, jvm finds the class that it needs to run from /META-INF/MANIFEST.MF file inside the jar file.

Standard Android menu icons, for example refresh

After seeing this post I found a useful link:

http://developer.android.com/design/downloads/index.html

You can download a lot of sources editable with Fireworks, Illustrator, Photoshop, etc...
And there's also fonts and icon packs.

Here is a stencil example.

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

To further compliment Andrés Torres Marroquín and Leo Dabus, I have a version that preserves fractional seconds. I can't find it documented anywhere, but Apple truncate fractional seconds to the microsecond (3 digits of precision) on both input and output (even though specified using SSSSSSS, contrary to Unicode tr35-31).

I should stress that this is probably not necessary for most use cases. Dates online do not typically need millisecond precision, and when they do, it is often better to use a different data format. But sometimes one must interoperate with a pre-existing system in a particular way.

Xcode 8/9 and Swift 3.0-3.2

extension Date {
    struct Formatter {
        static let iso8601: DateFormatter = {
            let formatter = DateFormatter()
            formatter.calendar = Calendar(identifier: .iso8601)
            formatter.locale = Locale(identifier: "en_US_POSIX")
            formatter.timeZone = TimeZone(identifier: "UTC")
            formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXXXX"
            return formatter
        }()
    }

    var iso8601: String {
        // create base Date format 
         var formatted = DateFormatter.iso8601.string(from: self)

        // Apple returns millisecond precision. find the range of the decimal portion
         if let fractionStart = formatted.range(of: "."),
             let fractionEnd = formatted.index(fractionStart.lowerBound, offsetBy: 7, limitedBy: formatted.endIndex) {
             let fractionRange = fractionStart.lowerBound..<fractionEnd
            // replace the decimal range with our own 6 digit fraction output
             let microseconds = self.timeIntervalSince1970 - floor(self.timeIntervalSince1970)
             var microsecondsStr = String(format: "%.06f", microseconds)
             microsecondsStr.remove(at: microsecondsStr.startIndex)
             formatted.replaceSubrange(fractionRange, with: microsecondsStr)
        }
         return formatted
    }
}

extension String {
    var dateFromISO8601: Date? {
        guard let parsedDate = Date.Formatter.iso8601.date(from: self) else {
            return nil
        }

        var preliminaryDate = Date(timeIntervalSinceReferenceDate: floor(parsedDate.timeIntervalSinceReferenceDate))

        if let fractionStart = self.range(of: "."),
            let fractionEnd = self.index(fractionStart.lowerBound, offsetBy: 7, limitedBy: self.endIndex) {
            let fractionRange = fractionStart.lowerBound..<fractionEnd
            let fractionStr = self.substring(with: fractionRange)

            if var fraction = Double(fractionStr) {
                fraction = Double(floor(1000000*fraction)/1000000)
                preliminaryDate.addTimeInterval(fraction)
            }
        }
        return preliminaryDate
    }
}

How do I compile jrxml to get jasper?

For anyone coming across this question who uses Jaspersoft Studio (which, I think, is replacing iReports; it's quite similar, still freeware, just based on eclipse), look for the "Compile Report" icon on top of the editor area of your .jrxml file. Its icon, first in that line of icons, is a file with binary numbers on it (at least in version 5.6.2):

Jaspersoft Studio - compile report

Clicking this icon will generate the .jasper file in the same directory as the .jrxml file.

Extract a substring using PowerShell

other solution

$template="-----start-------{Value:This is a test 123}------end-------"
$text="-----start-------Hello World------end-------"

$text | ConvertFrom-String -TemplateContent $template

How to clear all input fields in a specific div with jQuery?

$.each($('.fetch_results input'), function(idx, input){
  $(input).val('');
});

Best way to move files between S3 buckets?

To move/copy from one bucket to another or the same bucket I use s3cmd tool and works fine. For instance:

s3cmd cp --recursive s3://bucket1/directory1 s3://bucket2/directory1
s3cmd mv --recursive s3://bucket1/directory1 s3://bucket2/directory1

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

Right-click the project, select Properties then under 'Configuration properties | Linker | Input | Ignore specific Library and write msvcrtd.lib

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

this error basically comes when you use the object before using it.

Only detect click event on pseudo-element

My answer will work for anyone wanting to click a definitive area of the page. This worked for me on my absolutely-positioned :after

Thanks to this article, I realized (with jQuery) I can use e.pageY and e.pageX instead of worrying about e.offsetY/X and e.clientY/X issue between browsers.

Through my trial and error, I started to use the clientX and clientY mouse coordinates in the jQuery event object. These coordinates gave me the X and Y offset of the mouse relative to the top-left corner of the browser's view port. As I was reading the jQuery 1.4 Reference Guide by Karl Swedberg and Jonathan Chaffer, however, I saw that they often referred to the pageX and pageY coordinates. After checking the updated jQuery documentation, I saw that these were the coordinates standardized by jQuery; and, I saw that they gave me the X and Y offset of the mouse relative to the entire document (not just the view port).

I liked this event.pageY idea because it would always be the same, as it was relative to the document. I can compare it to my :after's parent element using offset(), which returns its X and Y also relative to the document.

Therefore, I can come up with a range of "clickable" region on the entire page that never changes.


Here's my demo on codepen.


or if too lazy for codepen, here's the JS:

* I only cared about the Y values for my example.

var box = $('.box');
// clickable range - never changes
var max = box.offset().top + box.outerHeight();
var min = max - 30; // 30 is the height of the :after

var checkRange = function(y) {
  return (y >= min && y <= max);
}

box.click(function(e){
  if ( checkRange(e.pageY) ) {
    // do click action
    box.toggleClass('toggle');
  }
});

How to add parameters to a HTTP GET request in Android?

I use a List of NameValuePair and URLEncodedUtils to create the url string I want.

protected String addLocationToUrl(String url){
    if(!url.endsWith("?"))
        url += "?";

    List<NameValuePair> params = new LinkedList<NameValuePair>();

    if (lat != 0.0 && lon != 0.0){
        params.add(new BasicNameValuePair("lat", String.valueOf(lat)));
        params.add(new BasicNameValuePair("lon", String.valueOf(lon)));
    }

    if (address != null && address.getPostalCode() != null)
        params.add(new BasicNameValuePair("postalCode", address.getPostalCode()));
    if (address != null && address.getCountryCode() != null)
        params.add(new BasicNameValuePair("country",address.getCountryCode()));

    params.add(new BasicNameValuePair("user", agent.uniqueId));

    String paramString = URLEncodedUtils.format(params, "utf-8");

    url += paramString;
    return url;
}

Best practices for API versioning?

There are a few places you can do versioning in a REST API:

  1. As noted, in the URI. This can be tractable and even esthetically pleasing if redirects and the like are used well.

  2. In the Accepts: header, so the version is in the filetype. Like 'mp3' vs 'mp4'. This will also work, though IMO it works a bit less nicely than...

  3. In the resource itself. Many file formats have their version numbers embedded in them, typically in the header; this allows newer software to 'just work' by understanding all existing versions of the filetype while older software can punt if an unsupported (newer) version is specified. In the context of a REST API, it means that your URIs never have to change, just your response to the particular version of data you were handed.

I can see reasons to use all three approaches:

  1. if you like doing 'clean sweep' new APIs, or for major version changes where you want such an approach.
  2. if you want the client to know before it does a PUT/POST whether it's going to work or not.
  3. if it's okay if the client has to do its PUT/POST to find out if it's going to work.

How can I get the current page name in WordPress?

<?php wp_title(''); ?>

This worked for me.

If I understand correctly, you want to get the page name on a page that has post entries.

Cannot redeclare function php

You (or Joomla) is likely including this file multiple times. Enclose your function in a conditional block:

if (!function_exists('parseDate')) {
    // ... proceed to declare your function
}

Are Git forks actually Git clones?

Cloning involves making a copy of the git repository to a local machine, while forking is cloning the repository into another repository. Cloning is for personal use only (although future merges may occur), but with forking you are copying and opening a new possible project path

Mysql - How to quit/exit from stored procedure

I think this solution is handy if you can test the value of the error field later. This is also applicable by creating a temporary table and returning a list of errors.

DROP PROCEDURE IF EXISTS $procName;
DELIMITER //
CREATE PROCEDURE $procName($params)
BEGIN
    DECLARE error INT DEFAULT 0;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET error = 1;
    SELECT
       $fields
    FROM $tables
    WHERE $where
    ORDER BY $sorting LIMIT 1
    INTO $vars;
    IF error = 0 THEN
       SELECT $vars;
    ELSE
       SELECT 1 AS error;
       SET @error = 0;
    END IF;
END//
CALL $procName($effp);

How can I close a login form and show the main form without my application closing?

you should do it the other way round:

Load the mainform first and in its onload event show your loginform with showdialog() which will prevent mainform from showing until you have a result from the loginform

EDIT: As this is a login form and if you do not need any variables from your mainform (which is bad design in practice), you should really implement it in your program.cs as Davide and Cody suggested.

Increasing nesting function calls limit

Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.

I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let you go past the 100 iterations, but you will eventually hit the memory limits.

Creating random numbers with no duplicates

Another approach which allows you to specify how many numbers you want with size and the min and max values of the returned numbers

public static int getRandomInt(int min, int max) {
    Random random = new Random();

    return random.nextInt((max - min) + 1) + min;
}

public static ArrayList<Integer> getRandomNonRepeatingIntegers(int size, int min,
        int max) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();

    while (numbers.size() < size) {
        int random = getRandomInt(min, max);

        if (!numbers.contains(random)) {
            numbers.add(random);
        }
    }

    return numbers;
}

To use it returning 7 numbers between 0 and 25.

    ArrayList<Integer> list = getRandomNonRepeatingIntegers(7, 0, 25);
    for (int i = 0; i < list.size(); i++) {
        System.out.println("" + list.get(i));
    }

How do I filter query objects by date range in Django?

Still relevant today. You can also do:

import dateutil
import pytz

date = dateutil.parser.parse('02/11/2019').replace(tzinfo=pytz.UTC)

Start service in Android

startService(new Intent(this, MyService.class));

Just writing this line was not sufficient for me. Service still did not work. Everything had worked only after registering service at manifest

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >

    ...

    <service
        android:name=".MyService"
        android:label="My Service" >
    </service>
</application>

How to disassemble a memory range with GDB?

Yeah, disassemble is not the best command to use here. The command you want is "x/i" (examine as instructions):

(gdb) x/i 0xdeadbeef

How to get main window handle from process id?

Just to make sure you are not confusing the tid (thread id) and the pid (process id):

DWORD pid;
DWORD tid = GetWindowThreadProcessId( this->m_hWnd, &pid);

Replace HTML Table with Divs

You can create simple float-based forms without having to lose your liquid layout. For example:

<style type="text/css">
    .row { clear: left; padding: 6px; }
    .row label { float: left; width: 10em; }
    .row .field { display: block; margin-left: 10em; }
    .row .field input, .row .field select {
        width: 100%;
        box-sizing: border-box;
        -moz-box-sizing: border-box; -webkit-box-sizing: border-box; -khtml-box-sizing: border-box;
    }
</style>

<div class="row">
    <label for="f-firstname">First name</label>
    <span class="field"><input name="firstname" id="f-firstname" value="Bob" /></span>
</div>
<div class="row">
    <label for="f-state">State</label>
    <span class="field"><select name="state" id="f-state">
        <option value="NY">NY</option>
    </select></span>
</div>

This does tend to break down, though, when you have complex form layouts where there's a grid of multiple fixed and flexible width columns. At that point you have to decide whether to stick with divs and abandon liquid layout in favour of just dropping everything into fixed pixel positions, or let tables do it.

For me personally, liquid layout is a more important usability feature than the exact elements used to lay out the form, so I usually go for tables.

Page vs Window in WPF?

Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer). Pages must be hosted in a NavigationWindow or a Frame

Windows are just normal WPF application Windows, but can host Pages via a Frame container

AWK: Access captured group from line pattern

That was a stroll down memory lane...

I replaced awk by perl a long time ago.

Apparently the AWK regular expression engine does not capture its groups.

you might consider using something like :

perl -n -e'/test(\d+)/ && print $1'

the -n flag causes perl to loop over every line like awk does.

Exclude Blank and NA in R

A good idea is to set all of the "" (blank cells) to NA before any further analysis.

If you are reading your input from a file, it is a good choice to cast all "" to NAs:

foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited

If you have already your table loaded, you can act as follows:

foo[foo==""] <- NA

Then to keep only rows with no NA you may just use na.omit():

foo <- na.omit(foo)

Or to keep columns with no NA:

foo <- foo[, colSums(is.na(foo)) == 0] 

Can I apply multiple background colors with CSS3?

In this LIVE DEMO i've achieved this by using the :before css selector which seems to work quite nicely.

_x000D_
_x000D_
.myDiv  {_x000D_
position: relative; /*Parent MUST be relative*/_x000D_
z-index: 9;_x000D_
background: green;_x000D_
    _x000D_
/*Set width/height of the div in 'parent'*/    _x000D_
width:100px;_x000D_
height:100px;_x000D_
}_x000D_
_x000D_
_x000D_
.myDiv:before {_x000D_
content: "";_x000D_
position: absolute;/*set 'child' to be absolute*/_x000D_
z-index: -1; /*Make this lower so text appears in front*/_x000D_
   _x000D_
    _x000D_
/*You can choose to align it left, right, top or bottom here*/_x000D_
top: 0; _x000D_
right:0;_x000D_
bottom: 60%;_x000D_
left: 0;_x000D_
    _x000D_
    _x000D_
background: red;_x000D_
}
_x000D_
<div class="myDiv">this is my div with multiple colours. It work's with text too!</div>
_x000D_
_x000D_
_x000D_

I thought i would add this as I feel it could work quite well for a percentage bar/visual level of something.

It also means you're not creating multiple divs if you don't have to, and keeps this page up-to-date

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

I've run into that same issue as well. It's because you're closing your connection to the socket, but not the socket itself. The socket can enter a TIME_WAIT state (to ensure all data has been transmitted, TCP guarantees delivery if possible) and take up to 4 minutes to release.

or, for a REALLY detailed/technical explanation, check this link

It's certainly annoying, but it's not a bug. See the comment from @Vereb on this answer below on the use of SO_REUSEADDR.

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

What are App Domains in Facebook Apps?

To add to the answers above, the App Domain is required for security reasons. For example, your app has been sending the browser to "www.example.com/PAGE_NAME_HERE", but suddenly a third party application (or something else) sends the user to "www.supposedlymaliciouswebsite.com/PAGE_HERE", then a 191 error is thrown saying that this wasn't part of the app domains you listed in your Facebook application settings.

Android ListView selected item stay highlighted

From Avinash Kumar Pankaj's example

View v;

then at oncreate method

v = new View(getActivity());

and then onlistitemclick method i wrote

public void onListItemClick(ListView listView, View view, int position,
       long id) {
   v.setBackgroundResource(0);
   view.setBackgroundResource(R.color.green);
   v = view;
}

It worked for me. Thank you.

I replaced

v = new View(getActivity());

to

v = new View(this);

and the code worked well.

It is necessary the xml files 'colors' and 'bg_key' from previous examples too, as well as ListView attribute android:background="@drawable/bg_key"

Mauro

CSS How to set div height 100% minus nPx

I haven't seen anything like this posted yet, but I thought I'd put it out there.

<div class="main">
<header>Header</header>
<div class="content">Content</div>

Then CSS:

body, html {
    height: 100%;
    margin: 0;
    padding: 0;
}

.main {
    height: 100%;
    padding-top: 50px;
    box-sizing: border-box;
}

header {
    height: 50px;
    margin-top: -50px;
    width: 100%;
    background-color: #5078a5;
}

.content {
    height: 100%;
    background-color: #999999;
}

Here is a working jsfiddle

Note: I have no idea what the browser compatability is for this. I was just playing around with alternate solutions and this seemed to work well.

Detect network connection type on Android

@Emil's answer above is brilliant.

Small addition: We should ideally use TelephonyManager to detect network types. So the above should instead read:

/**
 * Check if there is fast connectivity
 * @param context
 * @return
 */
public static boolean isConnectedFast(Context context){
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    return (info != null && info.isConnected() && Connectivity.isConnectionFast(info.getType(), tm.getNetworkType()));
}

Generate insert script for selected records?

If you are using the SQL Management Studio, you can right click your DB name and select Tasks > Import/Export data and follow the wizard.
one of the steps is called "Specify Table Copy or Query" where there is an option to write a query to specify the data to transfer, so you can simply specify the following query:

select * from [Table] where Fk_CompanyId = 1

Is there a download function in jsFiddle?

Still no download functionality supported.. BUT.. you can use the jsfiddle-downloader node script.

Installation:

npm install jsfiddle-downloader -g

To download a single fiddle from its id:

jsfiddle-downloader -i <fiddle-id> [-o <output file>]

To download a single fiddle from its url:

jsfiddle-downloader -l <url> [-o <output file>]
jsfiddle-downloader -l jsfiddle.net/<user>/<fiddle-id>
jsfiddle-downloader -l https://jsfiddle.net/<fiddle-id>
jsfiddle-downloader -l https://jsfiddle.net/<user>/<fiddle-id>/show/ -o myfiddle.html

To download all scripts of a determinated 'user' from jsFiddle.net:

jsfiddle-downloader -u <user> [-o <output file>]

It'll download all backups in the currrent directory, the jsFiddles scripts will be named as:

[<output-folder>/]<id-fiddle>.html

make iframe height dynamic based on content inside- JQUERY/Javascript

This one is useful when you require a solution with no jquery. In that case you should try adding a container and set a padding to it in percentages

HTML example code:

<div class="iframecontainer">
    <iframe scrolling="no" src="..." class="iframeclass"width="999px" height="618px"></iframe>
</div>

CSS example code:

.iframeclass{
    position: absolute;
    top: 0;
    width: 100%;
}

.iframecontainer{
    position: relative;
    width: 100%;
    height: auto;
    padding-top: 61%;
}