Programs & Examples On #Bll

A Business Logic Layer (BLL) is a typical software engineering artifact within a Multitier architecture.

Issue in installing php7.2-mcrypt

I followed below steps to install mcrypt for PHP7.2 using PECL.

  1. Install PECL

apt-get install php-pecl

  1. Before installing MCRYPT you must install libmcrypt

apt-get install libmcrypt-dev libreadline-dev

  1. Install MCRYPT 1.0.1 using PECL

pecl install mcrypt-1.0.1

  1. After the successful installation

You should add "extension=mcrypt.so" to php.ini

Please comment below if you need any assistance. :-)

IMPORTANT !

According to php.net reference many (all) mcrypt functions have been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

Even without looking at assembly, the most obvious reason is that /= 2 is probably optimized as >>=1 and many processors have a very quick shift operation. But even if a processor doesn't have a shift operation, the integer division is faster than floating point division.

Edit: your milage may vary on the "integer division is faster than floating point division" statement above. The comments below reveal that the modern processors have prioritized optimizing fp division over integer division. So if someone were looking for the most likely reason for the speedup which this thread's question asks about, then compiler optimizing /=2 as >>=1 would be the best 1st place to look.


On an unrelated note, if n is odd, the expression n*3+1 will always be even. So there is no need to check. You can change that branch to

{
   n = (n*3+1) >> 1;
   count += 2;
}

So the whole statement would then be

if (n & 1)
{
    n = (n*3 + 1) >> 1;
    count += 2;
}
else
{
    n >>= 1;
    ++count;
}

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

I was getting the same error on a restored database when I tried to insert a new record using the EntityFramework. It turned out that the Indentity/Seed was screwing things up.

Using a reseed command fixed it.

DBCC CHECKIDENT ('[Prices]', RESEED, 4747030);GO

Vagrant error : Failed to mount folders in Linux guest

Fix Step by step:

If you not have vbguest plugin, install it:

$ vagrant plugin install vagrant-vbguest

Run Vagrant

It is show a error.

$ vagrant up

Login on VM

$ vagrant ssh

Fix!

In the guest (VM logged).

$ sudo ln -s /opt/VBoxGuestAdditions-4.3.10/lib/VBoxGuestAdditions /usr/lib/VBoxGuestAdditions

Back on the host, reload Vagrant

$ vagrant reload

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

The problem lays here:

--This result set has 3 columns
select LOC_id,LOC_locatie,LOC_deelVan_LOC_id from tblLocatie t
where t.LOC_id = 1 -- 1 represents an example

union all

--This result set has 1 columns   
select t.LOC_locatie + '>' from tblLocatie t
inner join q parent on parent.LOC_id = t.LOC_deelVan_LOC_id

In order to use union or union all number of columns and their types should be identical cross all result sets.

I guess you should just add the column LOC_deelVan_LOC_id to your second result set

CASE WHEN statement for ORDER BY clause

CASE is an expression - it returns a single scalar value (per row). It can't return a complex part of the parse tree of something else, like an ORDER BY clause of a SELECT statement.

It looks like you just need:

ORDER BY 
CASE WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount END desc,
CASE WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount END desc, 
Case WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount END DESC,
CASE WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount END DESC,
Case WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount END DESC,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC

Or possibly:

ORDER BY 
CASE
   WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
   WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
   WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
   WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
   WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC

It's a little tricky to tell which of the above (or something else) is what you're looking for because you've a) not explained what actual sort order you're trying to achieve, and b) not supplied any sample data and expected results, from which we could attempt to deduce the actual sort order you're trying to achieve.


This may be the answer we're looking for:

ORDER BY 
CASE
   WHEN TblList.PinRequestCount <> 0 THEN 5
   WHEN TblList.HighCallAlertCount <> 0 THEN 4
   WHEN TblList.HighAlertCount <> 0 THEN 3
   WHEN TblList.MediumCallAlertCount <> 0 THEN 2
   WHEN TblList.MediumAlertCount <> 0 THEN 1
END desc,
CASE
   WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
   WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
   WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
   WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
   WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC

How do you uninstall all dependencies listed in package.json (NPM)?

Piggy-backing off of VIKAS KOHLI and jedmao, you can do this

single line version:

npm uninstall `ls -1 node_modules | grep -v ^@ | tr '/\n' ' '` `find node_modules/@* -type d -depth 1 2>/dev/null | cut -d/ -f2-3 | tr '\n' ' '`

multi-lined version:

npm uninstall \
`ls -1 node_modules | grep -v ^@ | tr '/\n' ' '` \
`find node_modules/@* -type d -depth 1 2>/dev/null | cut -d/ -f2-3 | tr '\n' ' '`

Create a temporary table in MySQL with an index from a select

Did find the answer on my own. My problem was, that i use two temporary tables for a join and create the second one out of the first one. But the Index was not copied during creation...

CREATE TEMPORARY TABLE tmpLivecheck (tmpid INTEGER NOT NULL AUTO_INCREMENT, PRIMARY    
KEY(tmpid), INDEX(tmpid))
SELECT * FROM tblLivecheck_copy WHERE tblLivecheck_copy.devId = did;

CREATE TEMPORARY TABLE tmpLiveCheck2 (tmpid INTEGER NOT NULL, PRIMARY KEY(tmpid), 
INDEX(tmpid))  
SELECT * FROM tmpLivecheck;

... solved my problem.

Greetings...

what does this mean ? image/png;base64?

They serve the actual image inside CSS so there will be less HTTP requests per page.

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

My issue was simple: the Master page and Master.Designer.cs class had the correct Namespace, but the Master.cs class had the wrong namespace.

How to change Named Range Scope

Check out these two subs that reverse each other and flip the scope (worksheet to workbook or reverse) of all named ranges that refer to a range on the active sheet.

 Option Explicit
'---------------------------------------------------------------------------------------
' Procedure : RescopeNamedRangesToWorkbook
' Author    : JS20'07'11
' Date      : 11/18/2013
' Purpose   : Rescopes the parent of worksheet scoped named ranges to the active workbook
' for each named range with a scope equal to the active sheet in the active workbook.
'---------------------------------------------------------------------------------------

Public Sub RescopeNamedRangesToWorkbook()
Dim wb As Workbook
Dim ws As Worksheet
Dim objName As Name
Dim sWsName As String
Dim sWbName As String
Dim sRefersTo As String
Dim sObjName As String
Set wb = ActiveWorkbook
Set ws = ActiveSheet
sWsName = ws.Name
sWbName = wb.Name

'Loop through names in worksheet.
For Each objName In ws.Names
'Check name is visble.
    If objName.Visible = True Then
'Check name refers to a range on the active sheet.
        If InStr(1, objName.RefersTo, sWsName, vbTextCompare) Then
            sRefersTo = objName.RefersTo
            sObjName = objName.Name
'Check name is scoped to the worksheet.
            If objName.Parent.Name <> sWbName Then
'Delete the current name scoped to worksheet replacing with workbook scoped name.
                sObjName = Mid(sObjName, InStr(1, sObjName, "!") + 1, Len(sObjName))
                objName.Delete
                wb.Names.Add Name:=sObjName, RefersTo:=sRefersTo
            End If
        End If
    End If
Next objName
End Sub
'---------------------------------------------------------------------------------------
' Procedure : RescopeNamedRangesToWorksheet
' Author    : JS20'07'11
' Date      : 11/18/2013
' Purpose   : Rescopes each workbook scoped named range to the specific worksheet to
' which the range refers for each named range that refers to the active worksheet.
'---------------------------------------------------------------------------------------

Public Sub RescopeNamedRangesToWorksheet()
Dim wb As Workbook
Dim ws As Worksheet
Dim objName As Name
Dim sWsName As String
Dim sWbName As String
Dim sRefersTo As String
Dim sObjName As String
Set wb = ActiveWorkbook
Set ws = ActiveSheet
sWsName = ws.Name
sWbName = wb.Name

'Loop through names in worksheet.
For Each objName In wb.Names
'Check name is visble.
    If objName.Visible = True Then
'Check name refers to a range on the active sheet.
        If InStr(1, objName.RefersTo, sWsName, vbTextCompare) Then
            sRefersTo = objName.RefersTo
            sObjName = objName.Name
'Check name is scoped to the workbook.
            If objName.Parent.Name = sWbName Then
'Delete the current name scoped to workbook replacing with worksheet scoped name.
                objName.Delete
                ws.Names.Add Name:=sObjName, RefersTo:=sRefersTo
            End If
        End If
    End If
Next objName
End Sub

sorting and paging with gridview asp.net

More simple way...:

    Dim dt As DataTable = DirectCast(GridView1.DataSource, DataTable)
    Dim dv As New DataView(dt)

    If GridView1.Attributes("dir") = SortDirection.Ascending Then
        dv.Sort = e.SortExpression & " DESC" 
        GridView1.Attributes("dir") = SortDirection.Descending

    Else
        GridView1.Attributes("dir") = SortDirection.Ascending
        dv.Sort = e.SortExpression & " ASC"

    End If

    GridView1.DataSource = dv
    GridView1.DataBind()

PHP Change Array Keys

Use array array_flip in php

$array = array ( [1] => Sell [2] => Buy [3] => Rent [4] => Jobs )
print_r(array_flip($array));
Array ( [Sell] => 1 [Buy] => 2 [Rent] => 3 [Jobs] => 4 ) 

clearing a char array c

Try the following:

strcpy(my_custom_data,"");

How to send data to COM PORT using JAVA?

The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html

Begin, Rescue and Ensure in Ruby?

Yes, ensure is called in any circumstances. For more information see "Exceptions, Catch, and Throw" of the Programming Ruby book and search for "ensure".

Free FTP Library

After lots of investigation in the same issue I found this one to be extremely convenient: https://github.com/flagbug/FlagFtp

For example (try doing this with the standard .net "library" - it will be a real pain) -> Recursively retreving all files on the FTP server:

  public IEnumerable<FtpFileInfo> GetFiles(string server, string user, string password)
    {
        var credentials = new NetworkCredential(user, password);
        var baseUri = new Uri("ftp://" + server + "/");

        var files = new List<FtpFileInfo>();
        AddFilesFromSubdirectory(files, baseUri, credentials);

        return files;
    }

    private void AddFilesFromSubdirectory(List<FtpFileInfo> files, Uri uri, NetworkCredential credentials)
    {
        var client = new FtpClient(credentials);
        var lookedUpFiles = client.GetFiles(uri);
        files.AddRange(lookedUpFiles);

        foreach (var subDirectory in client.GetDirectories(uri))
        {
            AddFilesFromSubdirectory(files, subDirectory.Uri, credentials);
        }
    }

How to set MimeBodyPart ContentType to "text/html"?

What about using:

mime_body_part.setHeader("Content-Type", "text/html");

In the documentation of getContentType it says that the value returned is found using getHeader(name). So if you set the header using setHeader I guess everything should be fine.

How to figure out the SMTP server host?

To automate the answer of @Jordan S. Jones at WIN/DOS command-line,

Put this in a batch file named: getmns.bat (get mail name server):

@echo off
if @%1==@ goto USAGE
echo set type=MX>mnscmd.txt
echo %1>>mnscmd.txt
echo exit>>mnscmd.txt
nslookup<mnscmd.txt>mnsresult.txt
type mnsresult.txt
del mnsresult.txt
goto END
:USAGE
echo usage:
echo %0 domainname.ext
:END
echo.

For example:

getmns google.com

output:

google.com      MX preference = 20, mail exchanger = alt1.aspmx.l.google.com
google.com      MX preference = 10, mail exchanger = aspmx.l.google.com
google.com      MX preference = 50, mail exchanger = alt4.aspmx.l.google.com
google.com      MX preference = 40, mail exchanger = alt3.aspmx.l.google.com
google.com      MX preference = 30, mail exchanger = alt2.aspmx.l.google.com

alt4.aspmx.l.google.com internet address = 74.125.25.27
alt3.aspmx.l.google.com internet address = 173.194.72.27
aspmx.l.google.com      internet address = 173.194.65.27
alt1.aspmx.l.google.com internet address = 74.125.200.27
alt2.aspmx.l.google.com internet address = 64.233.187.27

For example to pipe the result again into a file do:

getmns google.com > google.mns.txt

:-D

Can I embed a .png image into an html page?

The 64base method works for large images as well, I use that method to embed all the images into my website, and it works every time. I've done with files up to 2Mb size, jpg and png.

How to get the list of all database users

EXEC sp_helpuser

or

SELECT * FROM sysusers

Both of these select all the users of the current database (not the server).

Gmail: 530 5.5.1 Authentication Required. Learn more at

Get to your Gmail account's security settings and set permissions for "Less secure apps" to Enabled. Worked for me.

Maven error: Not authorized, ReasonPhrase:Unauthorized

I have recently encountered this problem. Here are the steps to resolve

  1. Check the servers section in the settings.xml file.Is username and password correct?

_x000D_
_x000D_
<servers>_x000D_
  <server>_x000D_
    <id>serverId</id>_x000D_
    <username>username</username>_x000D_
    <password>password</password>_x000D_
  </server>_x000D_
</servers>
_x000D_
_x000D_
_x000D_

  1. Check the repository section in the pom.xml file.The id of the server tag should be the same as the id of the repository tag.

_x000D_
_x000D_
<repositories>_x000D_
 <repository>_x000D_
   <id>serverId</id>  _x000D_
   <url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
 </repository>_x000D_
</repositories>
_x000D_
_x000D_
_x000D_

  1. If the repository tag is not configured in the pom.xml file, look in the settings.xml file.

_x000D_
_x000D_
<profiles>_x000D_
 <profile>_x000D_
   <repositories>_x000D_
     <repository>_x000D_
      <id>serverId</id>_x000D_
      <name>aliyun</name>_x000D_
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
     </repository>_x000D_
   </repositories>_x000D_
 </profile>_x000D_
</profiles>
_x000D_
_x000D_
_x000D_

Note that you should ensure that the id of the server tag should be the same as the id of the repository tag.

Calling Web API from MVC controller

Controller:

    public JsonResult GetProductsData()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:5136/api/");
            //HTTP GET
            var responseTask = client.GetAsync("product");
            responseTask.Wait();

            var result = responseTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<IList<product>>();
                readTask.Wait();

                var alldata = readTask.Result;

                var rsproduct = from x in alldata
                             select new[]
                             {
                             Convert.ToString(x.pid),
                             Convert.ToString(x.pname),
                             Convert.ToString(x.pprice),
                      };

                return Json(new
                {
                    aaData = rsproduct
                },
    JsonRequestBehavior.AllowGet);


            }
            else //web api sent error response 
            {
                //log response status here..

               var pro = Enumerable.Empty<product>();


                return Json(new
                {
                    aaData = pro
                },
    JsonRequestBehavior.AllowGet);


            }
        }
    }

    public JsonResult InupProduct(string id,string pname, string pprice)
    {
        try
        {

            product obj = new product
            {
                pid = Convert.ToInt32(id),
                pname = pname,
                pprice = Convert.ToDecimal(pprice)
            };



            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:5136/api/product");


                if(id=="0")
                {
                    //insert........
                    //HTTP POST
                    var postTask = client.PostAsJsonAsync<product>("product", obj);
                    postTask.Wait();

                    var result = postTask.Result;

                    if (result.IsSuccessStatusCode)
                    {
                        return Json(1, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        return Json(0, JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    //update........
                    //HTTP POST
                    var postTask = client.PutAsJsonAsync<product>("product", obj);
                    postTask.Wait();
                    var result = postTask.Result;
                    if (result.IsSuccessStatusCode)
                    {
                        return Json(1, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        return Json(0, JsonRequestBehavior.AllowGet);
                    }

                }




            }


            /*context.InUPProduct(Convert.ToInt32(id),pname,Convert.ToDecimal(pprice));

            return Json(1, JsonRequestBehavior.AllowGet);*/
        }
        catch (Exception ex)
        {
            return Json(0, JsonRequestBehavior.AllowGet);
        }

    }

    public JsonResult deleteRecord(int ID)
    {
        try
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:5136/api/product");

                //HTTP DELETE
                var deleteTask = client.DeleteAsync("product/" + ID);
                deleteTask.Wait();

                var result = deleteTask.Result;
                if (result.IsSuccessStatusCode)
                {

                    return Json(1, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(0, JsonRequestBehavior.AllowGet);
                }
            }



           /* var data = context.products.Where(x => x.pid == ID).FirstOrDefault();
            context.products.Remove(data);
            context.SaveChanges();
            return Json(1, JsonRequestBehavior.AllowGet);*/
        }
        catch (Exception ex)
        {
            return Json(0, JsonRequestBehavior.AllowGet);
        }
    }

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

One way for me to understand wildcards is to think that the wildcard isn't specifying the type of the possible objects that given generic reference can "have", but the type of other generic references that it is is compatible with (this may sound confusing...) As such, the first answer is very misleading in it's wording.

In other words, List<? extends Serializable> means you can assign that reference to other Lists where the type is some unknown type which is or a subclass of Serializable. DO NOT think of it in terms of A SINGLE LIST being able to hold subclasses of Serializable (because that is incorrect semantics and leads to a misunderstanding of Generics).

Use string.Contains() with switch()

Faced with this issue when determining an environment, I came up with the following one-liner:

string ActiveEnvironment = localEnv.Contains("LIVE") ? "LIVE" : (localEnv.Contains("TEST") ? "TEST" : (localEnv.Contains("LOCAL") ? "LOCAL" : null));

That way, if it can't find anything in the provided string that matches the "switch" conditions, it gives up and returns null. This could easily be amended to return a different value.

It's not strictly a switch, more a cascading if statement but it's neat and it worked.

How to auto-reload files in Node.js?

You can use nodemon from NPM. And if you are using Express generator then you can using this command inside your project folder:

nodemon npm start

or using Debug mode

DEBUG=yourapp:* nodemon npm start

you can also run directly

nodemon your-app-file.js

Hope this help.

Most popular screen sizes/resolutions on Android phones

Here is a list of almost all resolutions of tablets, with the most common ones in bold :

2560X1600
1366X768

1920X1200
1280X800
1280X768
1024X800
1024X768
1024X600

960X640
960X540
854X480
800X600
800X480
800X400

Happy designing .. ! :)

Pandas get the most frequent values of a column

You could try argmax like this:

dataframe['name'].value_counts().argmax() Out[13]: 'alex'

The value_counts will return a count object of pandas.core.series.Series and argmax could be used to achieve the key of max values.

How to trigger a build only if changes happen on particular set of files

If you are using a declarative syntax of Jenkinsfile to describe your building pipeline, you can use changeset condition to limit stage execution only to the case when specific files are changed. This is now a standard feature of Jenkins and does not require any additional configruation/software.

stages {
    stage('Nginx') {
        when { changeset "nginx/*"}
        steps {
            sh "make build-nginx"
            sh "make start-nginx"
        }
    }
}

You can combine multiple conditions using anyOf or allOf keywords for OR or AND behaviour accordingly:

when {
    anyOf {
        changeset "nginx/**"
        changeset "fluent-bit/**"
    }
}
steps {
    sh "make build-nginx"
    sh "make start-nginx"
}

How to convert string to binary?

We just need to encode it.

'string'.encode('ascii')

Is it a bad practice to use an if-statement without curly braces?

From my experience the only (very) slight advantage of the first form is code readability, the second form adds "noise".

But with modern IDEs and code autogeneration (or autocompletion) I strongly recommend using the second form, you won't spend extra time typing curly braces and you'll avoid some of the most frequent bugs.

There are enough energy consuming bugs, people just shoudn't open doors for big wastes of time.

One of the most important rule to remember when writing code is consistency. Every line of code should be written the same way, no matter who wrote it. Being rigorous prevents bugs from "happening" ;)

This is the same with naming clearly & explicitly your variables, methods, files or with correctly indenting them...

When my students accept this fact, they stop fighting against their own sourcecode and they start to see coding as a really interesting, stimulating and creative activity. They challenge their minds, not their nerves !

How to press back button in android programmatically?

Call onBackPressed after overriding it in your activity.

Should IBOutlets be strong or weak under ARC?

One thing I wish to point out here, and that is, despite what the Apple engineers have stated in their own WWDC 2015 video here:

https://developer.apple.com/videos/play/wwdc2015/407/

Apple keeps changing their mind on the subject, which tells us that there is no single right answer to this question. To show that even Apple engineers are split on this subject, take a look at Apple's most recent sample code, and you'll see some people use weak, and some don't.

This Apple Pay example uses weak: https://developer.apple.com/library/ios/samplecode/Emporium/Listings/Emporium_ProductTableViewController_swift.html#//apple_ref/doc/uid/TP40016175-Emporium_ProductTableViewController_swift-DontLinkElementID_8

As does this picture-in-picture example: https://developer.apple.com/library/ios/samplecode/AVFoundationPiPPlayer/Listings/AVFoundationPiPPlayer_PlayerViewController_swift.html#//apple_ref/doc/uid/TP40016166-AVFoundationPiPPlayer_PlayerViewController_swift-DontLinkElementID_4

As does the Lister example: https://developer.apple.com/library/ios/samplecode/Lister/Listings/Lister_ListCell_swift.html#//apple_ref/doc/uid/TP40014701-Lister_ListCell_swift-DontLinkElementID_57

As does the Core Location example: https://developer.apple.com/library/ios/samplecode/PotLoc/Listings/Potloc_PotlocViewController_swift.html#//apple_ref/doc/uid/TP40016176-Potloc_PotlocViewController_swift-DontLinkElementID_6

As does the view controller previewing example: https://developer.apple.com/library/ios/samplecode/ViewControllerPreviews/Listings/Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift.html#//apple_ref/doc/uid/TP40016546-Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift-DontLinkElementID_5

As does the HomeKit example: https://developer.apple.com/library/ios/samplecode/HomeKitCatalog/Listings/HMCatalog_Homes_Action_Sets_ActionSetViewController_swift.html#//apple_ref/doc/uid/TP40015048-HMCatalog_Homes_Action_Sets_ActionSetViewController_swift-DontLinkElementID_23

All those are fully updated for iOS 9, and all use weak outlets. From this we learn that A. The issue is not as simple as some people make it out to be. B. Apple has changed their mind repeatedly, and C. You can use whatever makes you happy :)

Special thanks to Paul Hudson (author of www.hackingwithsift.com) who gave me the clarification, and references for this answer.

I hope this clarifies the subject a bit better!

Take care.

Configuring diff tool with .gitconfig

Others have done a 99% answer on this, but there is one step left out. (My answer will be coming from OS X so you will have to change file paths accordingly.)

You make these changes to your ~/.gitconfig:

[diff]
    tool = diffmerge
[difftool "diffmerge"]
    cmd = /Applications/Diffmerge.app/Contents/MacOS/diffmerge $LOCAL $REMOTE

This will fix the diff tool. You can also fix this without editing the ~/.gitconfig directly by entering these commands from the terminal:

git config --global diff.tool diffmerge
git config --global difftool.diffmerge.cmd "/Applications/DiffMerge.appContents/MacOS/diffmerge \$LOCAL \$REMOTE"

The 1% that everyone else failed to mention is when using this you can't just run git diff myfile.txt; you need to run git difftool myfile.txt.

iOS8 Beta Ad-Hoc App Download (itms-services)

I was struggling with this, my app was installing but not complete (almost 60% I can say) in iOS8, but in iOS7.1 it was working as expected. The error message popped was:

"Cannot install at this time". 

Finally Zillan's link helped me to get apple documentation. So, check:

  1. make sure the internet reachability in your device as you will be in local network/ intranet.
  2. Also make sure the address ax.init.itunes.apple.com is not getting blocked by your firewall/proxy (Just type this address in safari, a blank page must load).

As soon as I changed the proxy it installed completely. Hope it will help someone.

How can I validate a string to only allow alphanumeric characters in it?

In order to check if the string is both a combination of letters and digits, you can re-write @jgauffin answer as follows using .NET 4.0 and LINQ:

if(!string.IsNullOrWhiteSpace(yourText) && 
yourText.Any(char.IsLetter) && yourText.Any(char.IsDigit))
{
   // do something here
}

PHP "pretty print" json_encode

PHP has JSON_PRETTY_PRINT option since 5.4.0 (release date 01-Mar-2012).

This should do the job:

$json = json_decode($string);
echo json_encode($json, JSON_PRETTY_PRINT);

See http://www.php.net/manual/en/function.json-encode.php

Note: Don't forget to echo "<pre>" before and "</pre>" after, if you're printing it in HTML to preserve formatting ;)

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

setAttribute('display','none') not working

It works for me

setAttribute('style', 'display:none');

How to add constraints programmatically using Swift

Constraints for multiple views in playground.

swift 3+

  var yellowView: UIView!
    var redView: UIView!

    override func loadView() {

        // UI

        let view = UIView()
        view.backgroundColor = .white

        yellowView = UIView()
        yellowView.backgroundColor = .yellow
        view.addSubview(yellowView)

        redView = UIView()
        redView.backgroundColor = .red
        view.addSubview(redView)

        // Layout
        redView.translatesAutoresizingMaskIntoConstraints = false
        yellowView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            yellowView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
            yellowView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            yellowView.widthAnchor.constraint(equalToConstant: 80),
            yellowView.heightAnchor.constraint(equalToConstant: 80),

            redView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
            redView.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant: -20),
            redView.widthAnchor.constraint(equalToConstant: 80),
            redView.heightAnchor.constraint(equalToConstant: 80)
            ])

        self.view = view
    }

In my opinion xcode playground is the best place for learning adding constraints programmatically.

Playground image

Flutter - Wrap text on overflow, like insert ellipsis or fade

One way to fix an overflow of a Text Widget within a row if for example a chat message can be one really long line. You can create a Container and a BoxConstraint with a maxWidth in it.

            Container(
              constraints: BoxConstraints(maxWidth: 200),
                child: Text(
                  (chatName == null) ? " ": chatName,
                  style: TextStyle(
                      fontWeight: FontWeight.w400,
                      color: Colors.black87,
                      fontSize: 17.0),
                )
            ),

Adding a JAR to an Eclipse Java library

In Eclipse Ganymede (3.4.0):

  1. Select the library and click "Edit" (left side of the window)
  2. Click "User Libraries"
  3. Select the library again and click "Add JARs"

How to determine day of week by passing specific date?

LocalDate date=LocalDate.now();

System.out.println(date.getDayOfWeek());//prints THURSDAY
System.out.println(date.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.US) );  //prints Thu   
java.time.DayOfWeek is a enum which returns the singleton instance for the day-of-week of the weekday of the date.

How to delete file from public folder in laravel 5.1

public function destroy($id) {
    $news = News::findOrFail($id);
    $image_path = app_path("images/news/".$news->photo);

    if(file_exists($image_path)){
        //File::delete($image_path);
        File::delete( $image_path);
    }
    $news->delete();
    return redirect('admin/dashboard')->with('message','??? ??????? ???  ??');
}

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

Change from

<security mode="None">

to

<security mode="Transport">

in your web.config file. This change will allow you to use https instead of http

Xcode: failed to get the task for process

I had a the same issue and after reading the above answers all I had to do was go to Build Settings > Code Signing > Provisioning Profile > None and was able to ran the app on my devices again. Hope this helps someone else out

Can I change the scroll speed using css or jQuery?

I just made a pure Javascript function based on that code. Javascript only version demo: http://jsbin.com/copidifiji

That is the independent code from jQuery

if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false); 
window.onmousewheel = document.onmousewheel = wheel;}

function wheel(event) {
    var delta = 0;
    if (event.wheelDelta) delta = (event.wheelDelta)/120 ;
    else if (event.detail) delta = -(event.detail)/3;

    handle(delta);
    if (event.preventDefault) event.preventDefault();
    event.returnValue = false;
}

function handle(sentido) {
    var inicial = document.body.scrollTop;
    var time = 1000;
    var distance = 200;
  animate({
    delay: 0,
    duration: time,
    delta: function(p) {return p;},
    step: function(delta) {
window.scrollTo(0, inicial-distance*delta*sentido);   
    }});}

function animate(opts) {
  var start = new Date();
  var id = setInterval(function() {
    var timePassed = new Date() - start;
    var progress = (timePassed / opts.duration);
    if (progress > 1) {progress = 1;}
    var delta = opts.delta(progress);
    opts.step(delta);
    if (progress == 1) {clearInterval(id);}}, opts.delay || 10);
}

Display a RecyclerView in Fragment

You should retrieve RecyclerView in a Fragment after inflating core View using that View. Perhaps it can't find your recycler because it's not part of Activity

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_artist_tracks, container, false);
    final FragmentActivity c = getActivity();
    final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(c);
    recyclerView.setLayoutManager(layoutManager);

    new Thread(new Runnable() {
        @Override
        public void run() {
            final RecyclerAdapter adapter = new RecyclerAdapter(c);
            c.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    recyclerView.setAdapter(adapter);
                }
            });
        }
    }).start();

    return view;
}

Online Internet Explorer Simulators

I've been using IE Tester (good) but didn't know I could simply switch versions in IE. It's nice to know the browser voted "Most likely to be the bain of your existence" has the tool built in to look at previous versions.

The down side to IE Tester is it does not support javascript well, and also doesn't always do a great job with iframes. (Yes, I still use them.)

I decided that since Google and Facebook no longer support IE7, I won't either. I have a lot less funding than they do.

I know this doesn't fix the need to use VM for MAC users, but there should be ways around that too. With an 8 core processor PC computer, you can VM MAC with 4 cores, same for PC, and run 4 displays, two for each OS. Expensive, but this is our business. In most business models, it is not uncommon to spend tens of thousands of dollars on equipment. We shouldn't think of ourselves any differently. Invest in your success.

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

I used the Visual Studio 2008 Uninstall tool and it worked fine for me.

You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).

Found here, on the MSDN Forum: MSDN forum topic.

I found this answer here

Be sure you run the tool with admin-rights.

Sending message through WhatsApp

get the contact number whom you want to send the message and create uri for whatsapp, here c is a Cursor returning the selected contact.

Uri.parse("content://com.android.contacts/data/" + c.getString(0)));
i.setType("text/plain");
i.setPackage("com.whatsapp");           // so that only Whatsapp reacts and not the chooser
i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
i.putExtra(Intent.EXTRA_TEXT, "I'm the body.");
startActivity(i);

Delete files or folder recursively on Windows CMD

Use the Windows rmdir command

That is, rmdir /S /Q C:\Temp

I'm also using the ones below for some years now, flawlessly.

Check out other options with: forfiles /?

Delete SQM/Telemetry in windows folder recursively

forfiles /p %SYSTEMROOT%\system32\LogFiles /s /m *.* /d -1 /c "cmd /c del @file"

Delete windows TMP files recursively

forfiles /p %SYSTEMROOT%\Temp /s /m *.* /d -1 /c "cmd /c del @file"

Delete user TEMP files and folders recursively

forfiles /p %TMP% /s /m *.* /d -1 /c "cmd /c del @file"

Python's equivalent of && (logical-and) in an if-statement

maybe with & instead % is more fast and mantain readibility

other tests even/odd

x is even ? x % 2 == 0

x is odd ? not x % 2 == 0

maybe is more clear with bitwise and 1

x is odd ? x & 1

x is even ? not x & 1 (not odd)

def front_back(a, b):
    # +++your code here+++
    if not len(a) & 1 and not len(b) & 1:
        return a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):] 
    else:
        #todo! Not yet done. :P
    return

SQL Joins Vs SQL Subqueries (Performance)?

Performance is based on the amount of data you are executing on...

If it is less data around 20k. JOIN works better.

If the data is more like 100k+ then IN works better.

If you do not need the data from the other table, IN is good, But it is alwys better to go for EXISTS.

All these criterias I tested and the tables have proper indexes.

How do search engines deal with AngularJS applications?

Let's get definitive about AngularJS and SEO

Google, Yahoo, Bing, and other search engines crawl the web in traditional ways using traditional crawlers. They run robots that crawl the HTML on web pages, collecting information along the way. They keep interesting words and look for other links to other pages (these links, the amount of them and the number of them come into play with SEO).

So why don't search engines deal with javascript sites?

The answer has to do with the fact that the search engine robots work through headless browsers and they most often do not have a javascript rendering engine to render the javascript of a page. This works for most pages as most static pages don't care about JavaScript rendering their page, as their content is already available.

What can be done about it?

Luckily, crawlers of the larger sites have started to implement a mechanism that allows us to make our JavaScript sites crawlable, but it requires us to implement a change to our site.

If we change our hashPrefix to be #! instead of simply #, then modern search engines will change the request to use _escaped_fragment_ instead of #!. (With HTML5 mode, i.e. where we have links without the hash prefix, we can implement this same feature by looking at the User Agent header in our backend).

That is to say, instead of a request from a normal browser that looks like:

http://www.ng-newsletter.com/#!/signup/page

A search engine will search the page with:

http://www.ng-newsletter.com/?_escaped_fragment_=/signup/page

We can set the hash prefix of our Angular apps using a built-in method from ngRoute:

angular.module('myApp', [])
.config(['$location', function($location) {
  $location.hashPrefix('!');
}]);

And, if we're using html5Mode, we will need to implement this using the meta tag:

<meta name="fragment" content="!">

Reminder, we can set the html5Mode() with the $location service:

angular.module('myApp', [])
.config(['$location', 
function($location) {
  $location.html5Mode(true);
}]);

Handling the search engine

We have a lot of opportunities to determine how we'll deal with actually delivering content to search engines as static HTML. We can host a backend ourselves, we can use a service to host a back-end for us, we can use a proxy to deliver the content, etc. Let's look at a few options:

Self-hosted

We can write a service to handle dealing with crawling our own site using a headless browser, like phantomjs or zombiejs, taking a snapshot of the page with rendered data and storing it as HTML. Whenever we see the query string ?_escaped_fragment_ in a search request, we can deliver the static HTML snapshot we took of the page instead of the pre-rendered page through only JS. This requires us to have a backend that delivers our pages with conditional logic in the middle. We can use something like prerender.io's backend as a starting point to run this ourselves. Of course, we still need to handle the proxying and the snippet handling, but it's a good start.

With a paid service

The easiest and the fastest way to get content into search engine is to use a service Brombone, seo.js, seo4ajax, and prerender.io are good examples of these that will host the above content rendering for you. This is a good option for the times when we don't want to deal with running a server/proxy. Also, it's usually super quick.

For more information about Angular and SEO, we wrote an extensive tutorial on it at http://www.ng-newsletter.com/posts/serious-angular-seo.html and we detailed it even more in our book ng-book: The Complete Book on AngularJS. Check it out at ng-book.com.

How do I load external fonts into an HTML document?

If you want to support more browsers than the CSS3 fancy, you can look at the open source library cufon javascript library

And here is the API, if you want to do more funky stuff.

Major Pro: Allows you to do what you want / need.

Major Con: Disallows text selection in some browsers, so use is appropiate on header texts (but you can use it in all your site if you want)

Check for special characters (/*-+_@&$#%) in a string?

While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:

  1. Add the [https://www.nuget.org/packages/Extensions.cs][1] package to your project.
  2. Add "using Extensions;" to the top of your code.
  3. "smith23@".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
  4. Every other check in the rest of the code is simply MyString.IsAlphaNumeric().

Using cURL with a username and password?

curl -X GET -u username:password  {{ http://www.example.com/filename.txt }} -O

Why am I getting a " Traceback (most recent call last):" error?

At the beginning of your file you set raw_input to 0. Do not do this, at it modifies the built-in raw_input() function. Therefore, whenever you call raw_input(), it is essentially calling 0(), which raises the error. To remove the error, remove the first line of your code:

M = 1.6
# Miles to Kilometers 
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(raw_input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: %f\n" % M_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(raw_input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: %f\n") % F_conv
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(raw_input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: %f\n" % G_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(raw_input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: %f\n" % P_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(raw_input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: %f\n" % inches_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

Disable color change of anchor tag when visited

You can't. You can only style the visited state.

For other people who find this, make sure that you have them in the right order:

a {color:#FF0000;}         /* Unvisited link  */
a:visited {color:#00FF00;} /* Visited link    */
a:hover {color:#FF00FF;}   /* Mouse over link */
a:active {color:#0000FF;}  /* Selected link   */

symbol(s) not found for architecture i386

Came across this issue in Xcode 11, fix was changing the Minimum Deployment Target from 10.0 to 11.0, hope this helps someone :)

Count frequency of words in a list and sort by frequency

Here is code support your question is_char() check for validate string count those strings alone, Hashmap is dictionary in python

def is_word(word):
   cnt =0
   for c in word:

      if 'a' <= c <='z' or 'A' <= c <= 'Z' or '0' <= c <= '9' or c == '$':
          cnt +=1
   if cnt==len(word):
      return True
  return False

def words_freq(s):
  d={}
  for i in s.split():
    if is_word(i):
        if i in d:
            d[i] +=1
        else:
            d[i] = 1
   return d

 print(words_freq('the the sky$ is blue not green'))

What is the fastest way to create a checksum for large files in C#

Don't checksum the entire file, create checksums every 100mb or so, so each file has a collection of checksums.

Then when comparing checksums, you can stop comparing after the first different checksum, getting out early, and saving you from processing the entire file.

It'll still take the full time for identical files.

Where do I find the bashrc file on Mac?

The .bashrc file is in your home directory.

So from command line do:

cd
ls -a

This will show all the hidden files in your home directory. "cd" will get you home and ls -a will "list all".

In general when you see ~/ the tilda slash refers to your home directory. So ~/.bashrc is your home directory with the .bashrc file.

And the standard path to homebrew is in /usr/local/ so if you:

cd /usr/local
ls | grep -i homebrew

you should see the homebrew directory (/usr/local/homebrew). Source

Yes sometimes you may have to create this file and the typical format of a .bashrc file is:

# .bashrc

# User specific aliases and functions
. .alias
alias ducks='du -cks * | sort -rn | head -15'

# Source global definitions
if [ -f /etc/bashrc ]; then
    . /etc/bashrc
fi

PATH=$PATH:/home/username/bin:/usr/local/homebrew
export PATH

If you create your own .bashrc file make sure that the following line is in your ~/.bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

Scanf/Printf double variable C

As far as I read manual pages, scanf says that 'l' length modifier indicates (in case of floating points) that the argument is of type double rather than of type float, so you can have 'lf, le, lg'.

As for printing, officially, the manual says that 'l' applies only to integer types. So it might be not supported on some systems or by some standards. For instance, I get the following error message when compiling with gcc -Wall -Wextra -pedantic

a.c:6:1: warning: ISO C90 does not support the ‘%lf’ gnu_printf format [-Wformat=]

So you may want to doublecheck if your standard supports the syntax.

To conclude, I would say that you read with '%lf' and you print with '%f'.

missing private key in the distribution certificate on keychain

As long as you still have access to the mac which was used to generate the original distribution certificate it's very simple.

Just use that mac's Keychain Access application to export both the certificate and the private key. Select both using shift or command and right click to export to a .p12 file.

Attached a screenshot to make it very clear.

On your mac, import that .p12 file and you are good to go (just make sure you have a valid provisioning profile).

Just choose export

converting a javascript string to a html object

var s = '<div id="myDiv"></div>';
var htmlObject = document.createElement('div');
htmlObject.innerHTML = s;
htmlObject.getElementById("myDiv").style.marginTop = something;

delete_all vs destroy_all?

delete_all is a single SQL DELETE statement and nothing more. destroy_all calls destroy() on all matching results of :conditions (if you have one) which could be at least NUM_OF_RESULTS SQL statements.

If you have to do something drastic such as destroy_all() on large dataset, I would probably not do it from the app and handle it manually with care. If the dataset is small enough, you wouldn't hurt as much.

What is the difference between g++ and gcc?

One notable difference is that if you pass a .c file to gcc it will compile as C.

The default behavior of g++ is to treat .c files as C++ (unless -x c is specified).

linux execute command remotely

If you don't want to deal with security and want to make it as exposed (aka "convenient") as possible for short term, and|or don't have ssh/telnet or key generation on all your hosts, you can can hack a one-liner together with netcat. Write a command to your target computer's port over the network and it will run it. Then you can block access to that port to a few "trusted" users or wrap it in a script that only allows certain commands to run. And use a low privilege user.

on the server

mkfifo /tmp/netfifo; nc -lk 4201 0</tmp/netfifo | bash -e &>/tmp/netfifo

This one liner reads whatever string you send into that port and pipes it into bash to be executed. stderr & stdout are dumped back into netfifo and sent back to the connecting host via nc.

on the client

To run a command remotely: echo "ls" | nc HOST 4201

Change drive in git bash for windows

In order to navigate to a different drive/directory you can do it in convenient way (instead of typing cd /e/Study/Codes), just type in cd[Space], and drag-and-drop your directory Codes with your mouse to git bash, hit [Enter].

What is Teredo Tunneling Pseudo-Interface?

Is to do with IPv6

All the gory details here: http://www.microsoft.com/technet/network/ipv6/teredo.mspx

Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...

Android Completely transparent Status Bar?

This worked for me:

<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:navigationBarColor">@android:color/transparent</item>
<item name="android:windowTranslucentStatus">false</item>
<item name="android:windowTranslucentNavigation">false</item>

Excel CSV - Number cell format

Well, excel never pops up the wizard for CSV files. If you rename it to .txt, you'll see the wizard when you do a File>Open in Excel the next time.

Batch file to copy directories recursively

You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:

@echo off
call :treeProcess
goto :eof

:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
copy *.* C:\dest\dir
for /D %%d in (*) do (
    cd %%d
    call :treeProcess
    cd ..
)
exit /b

Windows Batch File Looping Through Directories to Process Files?

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

Write applications in C or C++ for Android?

Looking at this it seems it is possible:

"the fact is only Java language is supported doesn’t mean that you cannot develop applications in other languages. This have been proved by many developers, hackers and experts in application development for mobile. The guys at Elements Interactive B.V., the company behind Edgelib library, succeeded to run native C++ applications on the Android platform, even that at this time there is still many issues on display and sound … etc. This include the S-Tris2 game and a 3D animation demo of Edgelib."

Passing a variable to a powershell script via command line

Declare the parameter in test.ps1:

 Param(
                [Parameter(Mandatory=$True,Position=1)]
                [string]$input_dir,
                [Parameter(Mandatory=$True)]
                [string]$output_dir,
                [switch]$force = $false
                )

Run the script from Run OR Windows Task Scheduler:

powershell.exe -command "& C:\FTP_DATA\test.ps1 -input_dir C:\FTP_DATA\IN -output_dir C:\FTP_DATA\OUT"

or,

 powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"

Comma separated results in SQL

this works in sql server 2016

USE AdventureWorks
GO
DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' ,'') + Name
FROM Production.Product
SELECT @listStr
GO

What is the difference between SOAP 1.1, SOAP 1.2, HTTP GET & HTTP POST methods for Android?

Differences in SOAP versions

Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.

The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.

The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.

In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.

SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.

There is not difine POST AND GET method for particular android....but all here is differance

GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.

What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.

POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.

Link to original IBM source

Validate fields after user has left a field

By using ng-focus you can achieve your goal. you need to provide ng-focus in your input field. And while writing your ng-show derivatives you have to write a logic not equal too. Like the below code:

<input type="text" class="form-control" name="inputPhone" ng-model="demo.phoneNumber" required ng-focus> <div ng-show="demoForm.inputPhone.$dirty && demoForm.inputPhone.$invalid && !demoForm.inputPhone.$focused"></div>

How to start Fragment from an Activity

You can either add or replace fragment in your activity. Create a FrameLayout in activity layout xml file.

Then do this in your activity to add fragment:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

And to replace fragment do this:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

See Android documentation on adding a fragment to an activity or following related questions on SO:

Difference between add(), replace(), and addToBackStack()

Basic difference between add() and replace() method of Fragment

Difference between add() & replace() with Fragment's lifecycle

How can I display the users profile pic using the facebook graph api?

  //create the url
  $profile_pic =  "http://graph.facebook.com/".$uid."/picture";

 //echo the image out
 echo "<img src=\"" . $profile_pic . "\" />"; 

Works fine for me

Scala list concatenation, ::: vs ++

Legacy. List was originally defined to be functional-languages-looking:

1 :: 2 :: Nil // a list
list1 ::: list2  // concatenation of two lists

list match {
  case head :: tail => "non-empty"
  case Nil          => "empty"
}

Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were redesigned for maximum code reuse and consistent API, so that you can use ++ to concatenate any two collections -- and even iterators. List, however, got to keep its original operators, aside from one or two which got deprecated.

How to change background color in the Notepad++ text editor?

You may need admin access to do it on your system.

  1. Create a folder 'themes' in the Notepad++ installation folder i.e. C:\Program Files (x86)\Notepad++
  2. Search or visit pages like http://timtrott.co.uk/notepad-colour-schemes/ to download the favourite theme. It will be an SML file.
    • Note: I prefer Neon any day.
  3. Download the themes from the site and drag them to the themes folder.
    • Note: I was unable to copy-paste or create new files in 'themes' folder so I used drag and that worked.
  4. Follow the steps provided by @triforceofcourage to select the new theme in Notepad++ preferences.

How to increment variable under DOS?

I've found my own solution.

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

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

Set /P Variable =< Counter.txt

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

if %variable%==250 echo PASS

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

Why am I getting "void value not ignored as it ought to be"?

The original poster is quoting a GCC compiler error message, but even by reading this thread, it's not clear that the error message is properly addressed - except by @pmg's answer. (+1, btw)


error: void value not ignored as it ought to be

This is a GCC error message that means the return-value of a function is 'void', but that you are trying to assign it to a non-void variable.

Example:

void myFunction()
{
   //...stuff...
}

int main()
{
   int myInt = myFunction(); //Compile error!

    return 0;
}

You aren't allowed to assign void to integers, or any other type.

In the OP's situation:

int a = srand(time(NULL));

...is not allowed. srand(), according to the documentation, returns void.

This question is a duplicate of:

I am responding, despite it being duplicates, because this is the top result on Google for this error message. Because this thread is the top result, it's important that this thread gives a succinct, clear, and easily findable result.

Truncate Two decimal places without rounding

If you don't worry too much about performance and your end result can be a string, the following approach will be resilient to floating precision issues:

string Truncate(double value, int precision)
{
    if (precision < 0)
    {
        throw new ArgumentOutOfRangeException("Precision cannot be less than zero");
    }

    string result = value.ToString();

    int dot = result.IndexOf('.');
    if (dot < 0)
    {
        return result;
    }

    int newLength = dot + precision + 1;

    if (newLength == dot + 1)
    {
        newLength--;
    }

    if (newLength > result.Length)
    {
        newLength = result.Length;
    }

    return result.Substring(0, newLength);
}

How to receive serial data using android bluetooth

The issue with the null connection is related to the findBT() function. you must change the device name from "MattsBlueTooth" to your device name as well as confirm the UUID for your service/device. Use something like BLEScanner app to confrim both on Android.

Invariant Violation: _registerComponent(...): Target container is not a DOM element

By the time script is executed, document element is not available yet, because script itself is in the head. While it's a valid solution to keep script in head and render on DOMContentLoaded event, it's even better to put your script at the very bottom of the body and render root component to a div before it like this:

<html>
<head>
</head>
<body>
  <div id="root"></div>
  <script src="/bundle.js"></script>
</body>
</html>

and in the bundle.js, call:

React.render(<App />, document.getElementById('root'));

You should always render to a nested div instead of body. Otherwise, all sorts of third-party code (Google Font Loader, browser plugins, whatever) can modify the body DOM node when React doesn't expect it, and cause weird errors that are very hard to trace and debug. Read more about this issue.

The nice thing about putting script at the bottom is that it won't block rendering until script load in case you add React server rendering to your project.


Update: (October 07, 2015 | v0.14)

React.render is deprecated, use ReactDOM.render instead.

Example:

import ReactDOM from 'react-dom';

ReactDOM.render(<App />, document.getElementById('root'));

Authentication failed because remote party has closed the transport stream

using (var client = new HttpClient(handler))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, apiEndPoint)).ConfigureAwait(false);
                await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            }

This worked for me

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

to resolve this kind of problem you should add two jar in your dependency POM (if use Maven)

<dependency>
    <groupId>asm</groupId>
    <artifactId>asm</artifactId>
    <version>3.3.1</version>
</dependency>

<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.1</version>
</dependency>

Publish to IIS, setting Environment Variable

For those of you looking to this in an azure devops pipeline, this can be achieved by adding the PowerShell on target machines task and running the following script:

$envVariables = (
  @{name='VARIABLE1';value='Value1'},
  @{name='VARIABLE2';value='Value2'}
)

Set-WebConfigurationProperty -PSPath IIS:\ -Location $('mySite') -Filter /system.webServer/aspNetCore/environmentVariables -Name . -Value $envVariables

How to remove "index.php" in codeigniter's path

Have a look in the system\application\config\config.php file, there is a variable named index_page

It should look like this

$config['index_page'] = "index.php";

change it to

$config['index_page'] = "";

Then as mentioned you also need to add a rewrite rule to the .htaccess file

Note: in CodeIgniter v2 this file was moved out of the system folder to application\config\config.php

HTML tag inside JavaScript

<html>
 <body>
  <input type="checkbox" id="number1" onclick="number1();">Number 1</br>
  <p id="h1"></p>
   <script type="text/javascript">
    function number1() {
    if(document.getElementById('number1').checked) {

      document.getElementById("h1").innerHTML = "<h1>Hello member</h1>";
         }
    }
   </script>
 </body>
</html>

Loading PictureBox Image from resource file with path (Part 3)

The path should be something like: "Images\a.bmp". (Note the lack of a leading slash, and the slashes being back slashes.)

And then:

pictureBox1.Image = Image.FromFile(@"Images\a.bmp");

I just tried it to make sure, and it works. This is besides the other answer that you got - to "copy always".

How do I pretty-print existing JSON data with Java?

I think for pretty-printing something, it's very helpful to know its structure.

To get the structure you have to parse it. Because of this, I don't think it gets much easier than first parsing the JSON string you have and then using the pretty-printing method toString mentioned in the comments above.

Of course you can do similar with any JSON library you like.

Correct way to create rounded corners in Twitter Bootstrap

In Bootstrap 4, the correct way to border your elements is to name them as follows in the class list of your elements:

For a slight rounding effect on all corners; class="rounded"
For a slight rounding on the left; class="rounded-left"
For a slight rounding on the top; class="rounded-top"
For a slight rounding on the right; class="rounded-right"
For a slight rounding on the bottom; class="rounded-bottom" 
For a circle rounding, i.e. your element is made circular; class="rounded-circle"
And to remove rounding effects; class="rounded-0"

To use Bootstrap 4 css files, you can simply use the CDN, and use the following link in the of your HTML file:

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

This will provided you with the basics of Bootstrap 4. However if you would like to use the majority of Bootstrap 4 components, including tooltips, popovers, and dropdowns, then you are best to use the following code instead:

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

Alternatively, you can install Bootstrap using NPM, or Bower, and link to the files there.

*Note that the bottom tag of the three is the same as the first tag in the first link path.

A full working example, could be :

<img src="path/to/my/image/image.jpg" width="150" height="150" class="rounded-circle mx-auto">

In the above example, the image is centered by using the Bootstrap auto margin on left and right.

serialize/deserialize java 8 java.time with Jackson JSON mapper

If you are using Jackson Serializer, here is a way to use the date modules:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.apache.kafka.common.serialization.Serializer;

public class JacksonSerializer<T> implements Serializer<T> {

    private final ObjectMapper mapper = new ObjectMapper()
            .registerModule(new ParameterNamesModule())
            .registerModule(new Jdk8Module())
            .registerModule(new JavaTimeModule());

    @Override
    public byte[] serialize(String s, T object) {
        try {
            return mapper.writeValueAsBytes(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Scala vs. Groovy vs. Clojure

I'm reading the Pragmatic Programmers book "Groovy Recipes: Greasing the wheels of Java" by Scott Davis, Copyright 2008 and printed in April of the same year.

It's a bit out of date but the book makes it clear that Groovy is literally an extension of Java. I can write Java code that functions exactly like Java and rename the file *.groovy and it works fine. According to the book, the reverse is true if I include the requisite libraries. So far, experimentation seems to bear this out.

Hide text using css

To hide text from html use text-indent property in css

.classname {
 text-indent: -9999px;
 white-space: nowrap; 
}

/* for dynamic text you need to add white-space, so your applied css will not disturb. nowrap means text will never wrap to the next line, the text continues on the same line until a <br> tag is encountered

Adding default parameter value with type hint in Python

If you're using typing (introduced in Python 3.5) you can use typing.Optional, where Optional[X] is equivalent to Union[X, None]. It is used to signal that the explicit value of None is allowed . From typing.Optional:

def foo(arg: Optional[int] = None) -> None:
    ...

How do I multiply each element in a list by a number?

Since I think you are new with Python, lets do the long way, iterate thru your list using for loop and multiply and append each element to a new list.

using for loop

lst = [5, 20 ,15]
product = []
for i in lst:
    product.append(i*5)
print product

using list comprehension, this is also same as using for-loop but more 'pythonic'

lst = [5, 20 ,15]

prod = [i * 5 for i in lst]
print prod

Get selected value/text from Select on change

Use either JavaScript or jQuery for this.

Using JavaScript

<script>
function val() {
    d = document.getElementById("select_id").value;
    alert(d);
}
</script>

<select onchange="val()" id="select_id">

Using jQuery

$('#select_id').change(function(){
    alert($(this).val());
})

Removing path and extension from filename in PowerShell

Expanding on René Nyffenegger's answer, for those who do not have access to PowerShell version 6.x, we use Split Path, which doesn't test for file existence:

Split-Path "C:\Folder\SubFolder\myfile.txt" -Leaf

This returns "myfile.txt". If we know that the file name doesn't have periods in it, we can split the string and take the first part:

(Split-Path "C:\Folder\SubFolder\myfile.txt" -Leaf).Split('.') | Select -First 1

or

(Split-Path "C:\Folder\SubFolder\myfile.txt" -Leaf).Split('.')[0]

This returns "myfile". If the file name might include periods, to be safe, we could use the following:

$FileName = Split-Path "C:\Folder\SubFolder\myfile.txt.config.txt" -Leaf
$Extension = $FileName.Split('.') | Select -Last 1
$FileNameWoExt = $FileName.Substring(0, $FileName.Length - $Extension.Length - 1)

This returns "myfile.txt.config". Here I prefer to use Substring() instead of Replace() because the extension preceded by a period could also be part of the name, as in my example. By using Substring we return the filename without the extension as requested.

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

As already stated, it's a warning not an error, but (if like me) you want things to run without warnings, you can disable that warning, then re-enable it again when you're done.

SET sql_notes = 0;      -- Temporarily disable the "Table already exists" warning
CREATE TABLE IF NOT EXISTS ...
SET sql_notes = 1;      -- And then re-enable the warning again

E: Unable to locate package npm

I ran into the same issue on Debian 9.2, this is what I did to overcome it.

Installation

sudo apt install curl
curl -sL https://deb.nodesource.com/setup_6.x | sudo bash -
sudo apt-get install -y nodejs
sudo apt-get install -y npm

Check installed versions

node --version
npm --version

Originally sourced from "How to install Node.js LTS on Debian 9 stretch" http://linuxbsdos.com/2017/06/26/how-to-install-node-js-lts-on-debian-9-stretch/

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

I first changed the root password running mysql at a prompt with

mysql -u root -p

Update password:

UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';

Edited line in the file config.inc.php with the new root password:

$cfg['Servers'][$i]['password'] = 'MyNewPass'

Stop and re-start mysql service (in Windows: mysql_stop.bat/mysql_start.bat)

and got phpMyAdmin to work!

EDIT 2017: for MySQL=5.7 use authentication_string in place of Password (see this answer):

UPDATE mysql.user SET authentication_string=PASSWORD('MyNewPass') WHERE User='root';

Angular: Can't find Promise, Map, Set and Iterator

If you came here because you see these errors in Visual Studio 2017 then you have a different problem as above, if you succeed in compiling. This is because the language service doesn't pick your tsconfig.json.

https://developercommunity.visualstudio.com/content/problem/208941/vs-156-ignores-tsconfigjson-and-typescriptcompileb.html

You have to set the Build Action of your tsconfig.json to "Content"(Right click -> Properties), then VS will pick it up.

post checkbox value

You should use

<input type="submit" value="submit" />

inside your form.

and add action into your form tag for example:

<form action="booking.php" method="post">

It's post your form into action which you choose.

From php you can get this value by

$_POST['booking-check'];

How to execute a file within the python interpreter?

Surprised I haven't seen this yet. You can execute a file and then leave the interpreter open after execution terminates using the -i option:

| foo.py |
----------
testvar = 10

def bar(bing):
  return bing*3

--------



$ python -i foo.py
>>> testvar 
10
>>> bar(6)
18

java build path problems

To configure your JRE in eclipse:

  • Window > Preferences > Java > Installed JREs...
  • Click Add
  • Find the directory of your JDK > Click OK

File changed listener in Java

You may also consider the Apache Commons JCI (Java Compiler Interface). Although this API seems to be focused on dynamic compilation of classes, it also includes classes in its API that monitors file changes.

Example: http://commons.apache.org/jci/usage.html

Make ABC Ordered List Items Have Bold Style

You could do something like this also:

ol {
  font-weight: bold;
}

ol > li > * {
  font-weight: normal;
}

So you have no "style" attributes in your HTML

How to rotate portrait/landscape Android emulator?

Yes. Thanks

Ctrl + F11 for Portrait

and

Ctrl + F12 for Landscape

mysql said: Cannot connect: invalid settings. xampp

I also have the problem but now solved

$cfg['Servers'][$i]['user'] = 'admin'; - I change the user name from 'root' to 'admin'

How to use group by with union in t-sql

GROUP BY 1

I've never known GROUP BY to support using ordinals, only ORDER BY. Either way, only MySQL supports GROUP BY's not including all columns without aggregate functions performed on them. Ordinals aren't recommended practice either because if they're based on the order of the SELECT - if that changes, so does your ORDER BY (or GROUP BY if supported).

There's no need to run GROUP BY on the contents when you're using UNION - UNION ensures that duplicates are removed; UNION ALL is faster because it doesn't - and in that case you would need the GROUP BY...

Your query only needs to be:

SELECT a.id,
       a.time
  FROM dbo.TABLE_A a
UNION
SELECT b.id,
       b.time
  FROM dbo.TABLE_B b

How do I get into a non-password protected Java keystore or change the password?

which means that cacerts keystore isn't password protected

That's a false assumption. If you read more carefully, you'll find that the listing was provided without verifying the integrity of the keystore because you didn't provide the password. The listing doesn't require a password, but your keystore definitely has a password, as indicated by:

In order to verify its integrity, you must provide your keystore password.

Java's default cacerts password is "changeit", unless you're on a Mac, where it's "changeme" up to a certain point. Apparently as of Mountain Lion (based on comments and another answer here), the password for Mac is now also "changeit", probably because Oracle is now handling distribution for the Mac JVM as well.

How to ignore a particular directory or file for tslint?

In addition to Michael's answer, consider a second way: adding linterOptions.exclude to tslint.json

For example, you may have tslint.json with following lines:

{
  "linterOptions": {
    "exclude": [
      "someDirectory/*.d.ts"
    ]
  }
}

Currency Formatting in JavaScript

You can use standard JS toFixed method

var num = 5.56789;
var n=num.toFixed(2);

//5.57

In order to add commas (to separate 1000's) you can add regexp as follows (where num is a number):

num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")

//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000

Complete example:

var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

//document.write(num) would write value as follows: $1,250.22

Separation character depends on country and locale. For some countries it may need to be .

How can I pass variable to ansible playbook in the command line?

For some reason none of the above Answers worked for me. As I need to pass several extra vars to my playbook in Ansbile 2.2.0, this is how I got it working (note the -e option before each var):

ansible-playbook site.yaml -i hostinv -e firstvar=false -e second_var=value2

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

Have encountered the same issue in my asp.net project, in the end i found the issue is with the target function not static, the issue fixed after I put the keyword static.

[WebMethod]
public static List<string> getRawData()

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Convert from ASCII string encoded in Hex to plain ASCII?

A slightly simpler solution:

>>> "7061756c".decode("hex")
'paul'

How to handle AccessViolationException

You can try using AppDomain.UnhandledException and see if that lets you catch it.

**EDIT*

Here is some more information that might be useful (it's a long read).

Is there a download function in jsFiddle?

In a recent work I had to download a list of fiddle urls and create separate folder for each fiddles having separate html css js file for each, i have created the following crawler program for this. https://github.com/sguha-work/FiddleCrawler .It will create folder name with counter value and each folder will have a html, a css, a js and a details file. (The details file will holds the links of external resources).

Swing JLabel text change on the running application

Use setText(str) method of JLabel to dynamically change text displayed. In actionPerform of button write this:

jLabel.setText("new Value");

A simple demo code will be:

    JFrame frame = new JFrame("Demo");
    frame.setLayout(new BorderLayout());
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(250,100);

    final JLabel label = new JLabel("flag");
    JButton button = new JButton("Change flag");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            label.setText("new value");
        }
    });

    frame.add(label, BorderLayout.NORTH);
    frame.add(button, BorderLayout.CENTER);
    frame.setVisible(true);

Use CASE statement to check if column exists in table - SQL Server

SELECT *
FROM ...
WHERE EXISTS(SELECT 1 
        FROM sys.columns c
        WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
            AND c.name = 'ModifiedByUser'
    )

How to create an array from a CSV file using PHP and the fgetcsv function

I think the str_getcsv() syntax is much cleaner, it also doesn't require the CSV to be stored in the file system.

$csv = str_getcsv(file_get_contents('myCSVFile.csv'));

echo '<pre>';
print_r($csv);
echo '</pre>';

Or for a line by line solution:

$csv = array();
$lines = file('myCSVFile.csv', FILE_IGNORE_NEW_LINES);

foreach ($lines as $key => $value)
{
    $csv[$key] = str_getcsv($value);
}

echo '<pre>';
print_r($csv);
echo '</pre>';

Or for a line by line solution with no str_getcsv():

$csv = array();
$file = fopen('myCSVFile.csv', 'r');

while (($result = fgetcsv($file)) !== false)
{
    $csv[] = $result;
}

fclose($file);

echo '<pre>';
print_r($csv);
echo '</pre>';

Compilation error: stray ‘\302’ in program etc

It's perhaps because you copied code from net ( from a site which has perhaps not an ASCII encoded page, but UTF-8 encoded page), so you can convert the code to ASCII from this site :

"http://www.percederberg.net/tools/text_converter.html"

There you can either detect errors manually by converting it back to UTF-8, or you can automatically convert it to ASCII and remove all the stray characters.

Return char[]/string from a function

char* charP = createStr();

Would be correct if your function was correct. Unfortunately you are returning a pointer to a local variable in the function which means that it is a pointer to undefined data as soon as the function returns. You need to use heap allocation like malloc for the string in your function in order for the pointer you return to have any meaning. Then you need to remember to free it later.

ASP.NET Identity reset password

In case of password reset, it is recommended to reset it through sending password reset token to registered user email and ask user to provide new password. If have created a easily usable .NET library over Identity framework with default configuration settins. You can find details at blog link and source code at github.

PHP create key => value pairs within a foreach

Create key-value pairs within a foreach like this:

function createOfferUrlArray($Offer) {
    $offerArray = array();

    foreach ($Offer as $key => $value) {
        $offerArray[$key] = $value[4];
    }

    return $offerArray;
}

invalid new-expression of abstract class type

invalid new-expression of abstract class type 'box'

There is nothing unclear about the error message. Your class box has at least one member that is not implemented, which means it is abstract. You cannot instantiate an abstract class.

If this is a bug, fix your box class by implementing the missing member(s).

If it's by design, derive from box, implement the missing member(s) and use the derived class.

Java generics - get class?

You are seeing the result of Type Erasure. From that page...

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

For instance, Box<String> is translated to type Box, which is called the raw type — a raw type is a generic class or interface name without any type arguments. This means that you can't find out what type of Object a generic class is using at runtime.

This also looks like this question which has a pretty good answer as well.

JavaScript query string

Building on the answer by @CMS I have the following (in CoffeeScript which can easily be converted to JavaScript):

String::to_query = ->
  [result, re, d] = [{}, /([^&=]+)=([^&]*)/g, decodeURIComponent]
  while match = re.exec(if @.match /^\?/ then @.substring(1) else @)
    result[d(match[1])] = d match[2] 
  result

You can easily grab what you need with:

location.search.to_query()['my_param']

The win here is an object-oriented interface (instead of functional) and it can be done on any string (not just location.search).

If you are already using a JavaScript library this function make already exist. For example here is Prototype's version

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

I have solved this problem in my pycharm in a bit different way.

Go to settings -> Project Interpreter and then click on the base package there.

You will see a page like this

problemGuide

After that when your package is installed then you should see the package is colored blue rather than white.

And the unresolved reference is also gone too.

Replacing NULL with 0 in a SQL server query

Wrap your column in this code.

 ISNULL(Yourcolumn, 0)

Maybe check why you are getting nulls

Python List vs. Array - when to use?

Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in amortized constant time. If you need to shrink and grow your list time-efficiently and without hassle, they are the way to go. But they use a lot more space than C arrays, in part because each item in the list requires the construction of an individual Python object, even for data that could be represented with simple C types (e.g. float or uint64_t).

The array.array type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data (that is to say, all of the same type) and so it uses only sizeof(one object) * length bytes of memory. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, ioctl or fctnl).

array.array is also a reasonable way to represent a mutable string in Python 2.x (array('B', bytes)). However, Python 2.6+ and 3.x offer a mutable byte string as bytearray.

However, if you want to do math on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays.

To make a long story short: array.array is useful when you need a homogeneous C array of data for reasons other than doing math.

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

You may need to enable 32-bit applications in your AppPool. Go to > 'Application Pool' in IIS => right click your app pool => advance setting => 'enable 32 bit application' to true.

Please don't forget to restart your app pool and your corresponding application pointing to that app pool.

Interfaces vs. abstract classes

Another thing to consider is that, since there is no multiple inheritance, if you want a class to be able to implement/inherit from your interface/abstract class, but inherit from another base class, use an interface.

Deleting queues in RabbitMQ

In RabbitMQ versions > 3.0, you can also utilize the HTTP API if the rabbitmq_management plugin is enabled. Just be sure to set the content-type to 'application/json' and provide the vhost and queue name:

I.E. Using curl with a vhost 'test' and queue name 'testqueue':

$ curl -i -u guest:guest -H "content-type:application/json" -XDELETE http://localhost:15672/api/queues/test/testqueue
HTTP/1.1 204 No Content
Server: MochiWeb/1.1 WebMachine/1.9.0 (someone had painted it blue)
Date: Tue, 16 Apr 2013 10:37:48 GMT
Content-Type: application/json
Content-Length: 0

Why is vertical-align: middle not working on my span or div?

Using CSS3:

<div class="outer">
   <div class="inner"/>
</div>

Css:

.outer {
  display : flex;
  align-items : center;
}

use "justify-content: center;" to align elements horizontally

Note: This might not work in old IE's

Error inflating class android.support.design.widget.NavigationView

I was facing this error in Xamarin. This was due to some files that were present in drawable-v21 folder. So I copied those files (probably icon files) to the drawable folder and the error was gone.

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

Send a ajax request to your server like this in your js and get your result in success function.

jQuery.ajax({
            url: "/rest/abc",
            type: "GET",

            contentType: 'application/json; charset=utf-8',
            success: function(resultData) {
                //here is your json.
                  // process it

            },
            error : function(jqXHR, textStatus, errorThrown) {
            },

            timeout: 120000,
        });

at server side send response as json type.

And you can use jQuery.getJSON for your application.

How to flip background image using CSS?

I found I way to flip only the background not whole element after seeing a clue to flip in Alex's answer. Thanks alex for your answer

HTML

<div class="prev"><a href="">Previous</a></div>
<div class="next"><a href="">Next</a></div>

CSS

.next a, .prev a {
    width:200px;
    background:#fff
}
 .next {
    float:left
}
 .prev {
    float:right
}
 .prev a:before, .next a:before {
    content:"";
    width:16px;
    height:16px;
    margin:0 5px 0 0;
    background:url(http://i.stack.imgur.com/ah0iN.png) no-repeat 0 0;
    display:inline-block 
}
 .next a:before {
    margin:0 0 0 5px;
    transform:scaleX(-1);
}

See example here http://jsfiddle.net/qngrf/807/

Undefined symbols for architecture x86_64 on Xcode 6.1

this setting worked for me:

  • Architectures=$(ARCHS_STANDARD_32_BIT)
  • Build Active Architecture Only:YES
  • Valid Architectures armv6 armv7 armv7s arm64

Oracle: how to set user password unexpire?

While applying the new profile to the user,you should also check for resource limits are "turned on" for the database as a whole i.e.RESOURCE_LIMIT = TRUE

Let check the parameter value.
If in Case it is :

SQL> show parameter resource_limit
NAME                                 TYPE        VALUE
------------------------------------ ----------- ---------
resource_limit                       boolean     FALSE
Its mean resource limit is off,we ist have to enable it. 

Use the ALTER SYSTEM statement to turn on resource limits. 

SQL> ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;
System altered.

How to check if element is visible after scrolling?

Simple modification for scrollable div (container)

var isScrolledIntoView = function(elem, container) {
    var containerHeight = $(container).height();
    var elemTop = $(elem).position().top;
    var elemBottom = elemTop + $(elem).height();
    return (elemBottom > 0 && elemTop < containerHeight);
}

NOTE: this does not work if the element is larger than the scrollable div.

How to read a file line-by-line into a list?

Command line version

#!/bin/python3
import os
import sys
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
filename = dname + sys.argv[1]
arr = open(filename).read().split("\n") 
print(arr)

Run with:

python3 somefile.py input_file_name.txt

How to source virtualenv activate in a Bash script

You can also do this using a subshell to better contain your usage - here's a practical example:

#!/bin/bash

commandA --args

# Run commandB in a subshell and collect its output in $VAR
# NOTE
#  - PATH is only modified as an example
#  - output beyond a single value may not be captured without quoting
#  - it is important to discard (or separate) virtualenv activation stdout
#    if the stdout of commandB is to be captured
#
VAR=$(
    PATH="/opt/bin/foo:$PATH"
    . /path/to/activate > /dev/null  # activate virtualenv
    commandB  # tool from /opt/bin/ which requires virtualenv
)

# Use the output from commandB later
commandC "$VAR"

This style is especially helpful when

  • a different version of commandA or commandC exists under /opt/bin
  • commandB exists in the system PATH or is very common
  • these commands fail under the virtualenv
  • one needs a variety of different virtualenvs

percentage of two int?

One of them has to be a float going in. One possible way of ensuring that is:

float percent = (float) n/v * 100;

Otherwise, you're doing integer division, which truncates the numbers. Also, you should be using double unless there's a good reason for the float.

The next issue you'll run into is that some of your percentages might look like 24.9999999999999% instead of 25%. This is due to precision loss in floating point representation. You'll have to decide how to deal with that, too. Options include a DecimalFormat to "fix" the formatting or BigDecimal to represent exact values.

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

There are two uses for RAISE_APPLICATION_ERROR. The first is to replace generic Oracle exception messages with our own, more meaningful messages. The second is to create exception conditions of our own, when Oracle would not throw them.

The following procedure illustrates both usages. It enforces a business rule that new employees cannot be hired in the future. It also overrides two Oracle exceptions. One is DUP_VAL_ON_INDEX, which is thrown by a unique key on EMP(ENAME). The other is a a user-defined exception thrown when the foreign key between EMP(MGR) and EMP(EMPNO) is violated (because a manager must be an existing employee).

create or replace procedure new_emp
    ( p_name in emp.ename%type
      , p_sal in emp.sal%type
      , p_job in emp.job%type
      , p_dept in emp.deptno%type
      , p_mgr in emp.mgr%type 
      , p_hired in emp.hiredate%type := sysdate )
is
    invalid_manager exception;
    PRAGMA EXCEPTION_INIT(invalid_manager, -2291);
    dummy varchar2(1);
begin
    -- check hiredate is valid
    if trunc(p_hired) > trunc(sysdate) 
    then
        raise_application_error
            (-20000
             , 'NEW_EMP::hiredate cannot be in the future'); 
    end if;

    insert into emp
        ( ename
          , sal
          , job
          , deptno
          , mgr 
          , hiredate )
    values      
        ( p_name
          , p_sal
          , p_job
          , p_dept
          , p_mgr 
          , trunc(p_hired) );
exception
    when dup_val_on_index then
        raise_application_error
            (-20001
             , 'NEW_EMP::employee called '||p_name||' already exists'
             , true); 
    when invalid_manager then
        raise_application_error
            (-20002
             , 'NEW_EMP::'||p_mgr ||' is not a valid manager'); 

end;
/

How it looks:

SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1); END;

*
ERROR at line 1:
ORA-20000: NEW_EMP::hiredate cannot be in the future
ORA-06512: at "APC.NEW_EMP", line 16
ORA-06512: at line 1

SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate); END;

*
ERROR at line 1:
ORA-20002: NEW_EMP::8888 is not a valid manager
ORA-06512: at "APC.NEW_EMP", line 42
ORA-06512: at line 1


SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)

PL/SQL procedure successfully completed.

SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate); END;

*
ERROR at line 1:
ORA-20001: NEW_EMP::employee called DUGGAN already exists
ORA-06512: at "APC.NEW_EMP", line 37
ORA-00001: unique constraint (APC.EMP_UK) violated
ORA-06512: at line 1

Note the different output from the two calls to RAISE_APPLICATION_ERROR in the EXCEPTIONS block. Setting the optional third argument to TRUE means RAISE_APPLICATION_ERROR includes the triggering exception in the stack, which can be useful for diagnosis.

There is more useful information in the PL/SQL User's Guide.

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

Oddly enough, the issue for me was I was trying to open 2012 SQL Server Integration Services on SSMS 2008 R2. When I opened the same in SSMS 2012, it connected right away.

SyntaxError of Non-ASCII character

You should define source code encoding, add this to the top of your script:

# -*- coding: utf-8 -*-

The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:

import sys
print sys.getdefaultencoding()

Also see:

How to return part of string before a certain character?

Another method could be to split the string by ":" and then pop off the end. var newString = string.split(":").pop();

Calculate row means on subset of columns

Starting with your data frame DF, you could use the data.table package:

library(data.table)

## EDIT: As suggested by @MichaelChirico, setDT converts a
## data.frame to a data.table by reference and is preferred
## if you don't mind losing the data.frame
setDT(DF)

# EDIT: To get the column name 'Mean':

DF[, .(Mean = rowMeans(.SD)), by = ID]

#      ID     Mean
# [1,]  A 3.666667
# [2,]  B 4.333333
# [3,]  C 3.333333
# [4,]  D 4.666667
# [5,]  E 4.333333

Sleep/Wait command in Batch

Ok, yup you use the timeout command to sleep. But to do the whole process silently, it's not possible with cmd/batch. One of the ways is to create a VBScript that will run the Batch File without opening/showing any window. And here is the script:

Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "PATH OF BATCH FILE WITH QUOTATION MARKS" & Chr(34), 0
Set WshShell = Nothing

Copy and paste the above code on notepad and save it as Anyname.**vbs ** An example of the *"PATH OF BATCH FILE WITH QUOTATION MARKS" * might be: "C:\ExampleFolder\MyBatchFile.bat"

Get path of executable

This is a Windows specific way, but it is at least half of your answer.

GetThisPath.h

/// dest is expected to be MAX_PATH in length.
/// returns dest
///     TCHAR dest[MAX_PATH];
///     GetThisPath(dest, MAX_PATH);
TCHAR* GetThisPath(TCHAR* dest, size_t destSize);

GetThisPath.cpp

#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib")

TCHAR* GetThisPath(TCHAR* dest, size_t destSize)
{
    if (!dest) return NULL;
    if (MAX_PATH > destSize) return NULL;

    DWORD length = GetModuleFileName( NULL, dest, destSize );
    PathRemoveFileSpec(dest);
    return dest;
}

mainProgram.cpp

TCHAR dest[MAX_PATH];
GetThisPath(dest, MAX_PATH);

I would suggest using platform detection as preprocessor directives to change the implementation of a wrapper function that calls GetThisPath for each platform.

Spring profiles and testing

Can I recommend doing it this way, define your test like this:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
    TestPreperationExecutionListener.class
    })
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {

  @Test
  public void testContext(){

  }

  @Configuration
  @PropertySource("classpath:/myprops.properties")
  @ImportResource({"classpath:context.xml" })
  public static class MyContextConfiguration{

  }
}

with the following content in myprops.properties file:

spring.profiles.active=localtest

With this your second properties file should get resolved:

META-INF/spring/config_${spring.profiles.active}.properties

How to simulate key presses or a click with JavaScript?

Simulating a mouse click

My guess is that the webpage is listening to mousedown rather than click (which is bad for accessibility because when a user uses the keyboard, only focus and click are fired, not mousedown). So you should simulate mousedown, click, and mouseup (which, by the way, is what the iPhone, iPod Touch, and iPad do on tap events).

To simulate the mouse events, you can use this snippet for browsers that support DOM 2 Events. For a more foolproof simulation, fill in the mouse position using initMouseEvent instead.

// DOM 2 Events
var dispatchMouseEvent = function(target, var_args) {
  var e = document.createEvent("MouseEvents");
  // If you need clientX, clientY, etc., you can call
  // initMouseEvent instead of initEvent
  e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};
dispatchMouseEvent(element, 'mouseover', true, true);
dispatchMouseEvent(element, 'mousedown', true, true);
dispatchMouseEvent(element, 'click', true, true);
dispatchMouseEvent(element, 'mouseup', true, true);

When you fire a simulated click event, the browser will actually fire the default action (e.g. navigate to the link's href, or submit a form).

In IE, the equivalent snippet is this (unverified since I don't have IE). I don't think you can give the event handler mouse positions.

// IE 5.5+
element.fireEvent("onmouseover");
element.fireEvent("onmousedown");
element.fireEvent("onclick");  // or element.click()
element.fireEvent("onmouseup");

Simulating keydown and keypress

You can simulate keydown and keypress events, but unfortunately in Chrome they only fire the event handlers and don't perform any of the default actions. I think this is because the DOM 3 Events working draft describes this funky order of key events:

  1. keydown (often has default action such as fire click, submit, or textInput events)
  2. keypress (if the key isn't just a modifier key like Shift or Ctrl)
  3. (keydown, keypress) with repeat=true if the user holds down the button
  4. default actions of keydown!!
  5. keyup

This means that you have to (while combing the HTML5 and DOM 3 Events drafts) simulate a large amount of what the browser would otherwise do. I hate it when I have to do that. For example, this is roughly how to simulate a key press on an input or textarea.

// DOM 3 Events
var dispatchKeyboardEvent = function(target, initKeyboradEvent_args) {
  var e = document.createEvent("KeyboardEvents");
  e.initKeyboardEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};
var dispatchTextEvent = function(target, initTextEvent_args) {
  var e = document.createEvent("TextEvent");
  e.initTextEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};
var dispatchSimpleEvent = function(target, type, canBubble, cancelable) {
  var e = document.createEvent("Event");
  e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};

var canceled = !dispatchKeyboardEvent(element,
    'keydown', true, true,  // type, bubbles, cancelable
    null,  // window
    'h',  // key
    0, // location: 0=standard, 1=left, 2=right, 3=numpad, 4=mobile, 5=joystick
    '');  // space-sparated Shift, Control, Alt, etc.
dispatchKeyboardEvent(
    element, 'keypress', true, true, null, 'h', 0, '');
if (!canceled) {
  if (dispatchTextEvent(element, 'textInput', true, true, null, 'h', 0)) {
    element.value += 'h';
    dispatchSimpleEvent(element, 'input', false, false);
    // not supported in Chrome yet
    // if (element.form) element.form.dispatchFormInput();
    dispatchSimpleEvent(element, 'change', false, false);
    // not supported in Chrome yet
    // if (element.form) element.form.dispatchFormChange();
  }
}
dispatchKeyboardEvent(
    element, 'keyup', true, true, null, 'h', 0, '');

I don't think it is possible to simulate key events in IE.

matplotlib: colorbars and its text labels

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

demo

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

Either their security certificate has expired, or their hosting is broken/down.

Contact CVSDude and ask them whats up.

It could also be a timeout, because for me their site is exhaustively slow..

How to add "Maven Managed Dependencies" library in build path eclipse?

  • Install M2E plugin.
  • Right click your project and select Configure -> Convert to Maven project.

enter image description here

  • Then a pom.xml file will show up in your project. Double click the pom.xml, select Dependency tab to add the jars your project depends on.

UIImageView aspect fit and center

You can achieve this by setting content mode of image view to UIViewContentModeScaleAspectFill.

Then use following method method to get the resized uiimage object.

- (UIImage*)setProfileImage:(UIImage *)imageToResize onImageView:(UIImageView *)imageView
{
    CGFloat width = imageToResize.size.width;
    CGFloat height = imageToResize.size.height;
    float scaleFactor;
    if(width > height)
    {
        scaleFactor = imageView.frame.size.height / height;
    }
    else
    {
        scaleFactor = imageView.frame.size.width / width;
    }

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), NO, 0.0);
    [imageToResize drawInRect:CGRectMake(0, 0, width * scaleFactor, height * scaleFactor)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return resizedImage;
}

Edited Here (Swift Version)

func setProfileImage(imageToResize: UIImage, onImageView: UIImageView) -> UIImage
{
    let width = imageToResize.size.width
    let height = imageToResize.size.height

    var scaleFactor: CGFloat

    if(width > height)
    {
        scaleFactor = onImageView.frame.size.height / height;
    }
    else
    {
        scaleFactor = onImageView.frame.size.width / width;
    }

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), false, 0.0)
    imageToResize.drawInRect(CGRectMake(0, 0, width * scaleFactor, height * scaleFactor))
    let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return resizedImage;
}

PHP 7: Missing VCRUNTIME140.dll

Installing vc_redist.x86.exe works for me even though you have a 64-bit machine.

Apache Proxy: No protocol handler was valid

For my Apache2.4 + php5-fpm installation to start working, I needed to activate the following Apache modules:

sudo a2enmod proxy
sudo a2enmod proxy_fcgi

No need for proxy_http, and this is what sends all .php files straight to php5-fpm:

<FilesMatch \.php$>
    SetHandler "proxy:unix:/var/run/php5-fpm.sock|fcgi://localhost"
</FilesMatch>

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

// The answer that I was looking for when searching
public void Answer()
{
    IEnumerable<YourClass> first = this.GetFirstIEnumerableList();
    // Assign to empty list so we can use later
    IEnumerable<YourClass> second = new List<YourClass>();

    if (IwantToUseSecondList)
    {
        second = this.GetSecondIEnumerableList();  
    }
    IEnumerable<SchemapassgruppData> concatedList = first.Concat(second);
}

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

In SQL Server 2012, 2014:

USE mydb
GO

ALTER ROLE db_datareader ADD MEMBER MYUSER
GO
ALTER ROLE db_datawriter ADD MEMBER MYUSER
GO

In SQL Server 2008:

use mydb
go

exec sp_addrolemember db_datareader, MYUSER 
go
exec sp_addrolemember db_datawriter, MYUSER 
go

To also assign the ability to execute all Stored Procedures for a Database:

GRANT EXECUTE TO MYUSER;

To assign the ability to execute specific stored procedures:

GRANT EXECUTE ON dbo.sp_mystoredprocedure TO MYUSER;

How do I use spaces in the Command Prompt?

It can solve this problem by cd command, this command understand spaces without double quotes and you can call any program this way for example:

C:\Windows\system32>cd c:\Program Files\MongoDB\Server\3.2\bin

c:\Program Files\MongoDB\Server\3.2\bin>mongo now command prompt call mongo.exe

php foreach with multidimensional array

I know this is quite an old answer. Here is a faster solution without using foreach:

Use array_column

print_r(array_column($array, 'firstname')); #returns the value associated with that key 'firstname'

Also you can check before executing the above operation

if(array_key_exists('firstname', $array)){
   print_r(array_column($array, 'firstname'));
}

Java SimpleDateFormat for time zone with a colon separator?

If date string is like 2018-07-20T12:18:29.802Z Use this

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

Grant execute permission for a user on all stored procedures in database?

USE [DATABASE]

DECLARE @USERNAME VARCHAR(500)

DECLARE @STRSQL NVARCHAR(MAX)

SET @USERNAME='[USERNAME] '
SET @STRSQL=''

select @STRSQL+=CHAR(13)+'GRANT EXECUTE ON ['+ s.name+'].['+obj.name+'] TO'+@USERNAME+';'
from
    sys.all_objects as obj
inner join
    sys.schemas s ON obj.schema_id = s.schema_id
where obj.type in ('P','V','FK')
AND s.NAME NOT IN ('SYS','INFORMATION_SCHEMA')


EXEC SP_EXECUTESQL @STRSQL

Get nth character of a string in Swift programming language

Using characters would do the job. You can quickly convert the String to an array of characters that can be manipulated by the CharacterView methods.

Example:

let myString = "Hello World!"
let myChars  = myString.characters

(full CharacterView doc)

(tested in Swift 3)

Storing WPF Image Resources

The following worked and the images to be set is resources in properties:

    var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(MyProject.Properties.Resources.myImage.GetHbitmap(),
                                      IntPtr.Zero,
                                      Int32Rect.Empty,
                                      BitmapSizeOptions.FromEmptyOptions());
    MyButton.Background = new ImageBrush(bitmapSource);
img_username.Source = bitmapSource;

How do you use bcrypt for hashing passwords in PHP?


Edit: 2013.01.15 - If your server will support it, use martinstoeckli's solution instead.


Everyone wants to make this more complicated than it is. The crypt() function does most of the work.

function blowfishCrypt($password,$cost)
{
    $chars='./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $salt=sprintf('$2y$%02d$',$cost);
//For PHP < PHP 5.3.7 use this instead
//    $salt=sprintf('$2a$%02d$',$cost);
    //Create a 22 character salt -edit- 2013.01.15 - replaced rand with mt_rand
    mt_srand();
    for($i=0;$i<22;$i++) $salt.=$chars[mt_rand(0,63)];
    return crypt($password,$salt);
}

Example:

$hash=blowfishCrypt('password',10); //This creates the hash
$hash=blowfishCrypt('password',12); //This creates a more secure hash
if(crypt('password',$hash)==$hash){ /*ok*/ } //This checks a password

I know it should be obvious, but please don't use 'password' as your password.

Git Clone - Repository not found

open Credential Manager -> look for your GIT devops profile -> click on it -> edit -> add user and password generated in DevOps and save.

How can I merge two MySQL tables?

INSERT
INTO    first_table f
SELECT  *
FROM    second_table s
ON DUPLICATE KEY
UPDATE
        s.column1 = DO_WHAT_EVER_MUST_BE_DONE_ON_KEY_CLASH(f.column1)

Verifying that a string contains only letters in C#

Iterate through strings characters and use functions of 'Char' called 'IsLetter' and 'IsDigit'.

If you need something more specific - use Regex class.

What exactly is node.js used for?

Node.js is exactly used for back-end development, but it is popular as a full-stack and front-end solution as well. It is used primarily to build web applications, but it is a very popular choice for building enterprise applications too.

Developers like it because of its versatility, agility and performance. It increases productivity and application performance in a significant way. Since Node.js has a long-term support (LTS) plan that provides security and stability, it's no wonder that huge enterprises constantly add it to their stacks.

It is non-blocking and event-driven. Node.js applications uses “Single Threaded Event Loop Model” architecture to handle multiple concurrent clients. These features are key factors to make real time web applications.

Exit Shell Script Based on Process Exit Code

For Bash:

# This will trap any errors or commands with non-zero exit status
# by calling function catch_errors()
trap catch_errors ERR;

#
# ... the rest of the script goes here
#

function catch_errors() {
   # Do whatever on errors
   #
   #
   echo "script aborted, because of errors";
   exit 0;
}

Resolve conflicts using remote changes when pulling from Git remote

You can either use the answer from the duplicate link pointed by nvm.

Or you can resolve conflicts by using their changes (but some of your changes might be kept if they don't conflict with remote version):

git pull -s recursive -X theirs

How to Increase Import Size Limit in phpMyAdmin

Sharky's answer was spot on. The phpMyAdmin upload file size displayed is NOT managed by the php.ini settings, which you can see when you run a phpinfo.php containing:

<?php
// Show all information, defaults to INFO_ALL
phpinfo();
?>

It is good practice to increase your php.ini settings for:

post_max_size upload_max_filesize max_execution_time max_input_time memory_limit

You may use the settings example that Sujiraj R shared. Once you have made all of the changes to both your php.ini AND in the"Tweak Settings" area of WHM, when you launch phpMyAdmin and go to the import screen, you will see the size you selected for "cPanel PHP max upload size" field.

There were a lot of good answers on this post, but you had to look back and forth to get the right answer. I hope that by encapsulating those previous answers in this post I have helped just a bit. All of the answers I refer to on this post were derived by others that posted here, so please do not credit me with any of the answers posted herein.

List directory in Go

You can try using the ReadDir function in the io/ioutil package. Per the docs:

ReadDir reads the directory named by dirname and returns a list of sorted directory entries.

The resulting slice contains os.FileInfo types, which provide the methods listed here. Here is a basic example that lists the name of everything in the current directory (folders are included but not specially marked - you can check if an item is a folder by using the IsDir() method):

package main

import (
    "fmt"
    "io/ioutil"
     "log"
)

func main() {
    files, err := ioutil.ReadDir("./")
    if err != nil {
        log.Fatal(err)
    }
 
    for _, f := range files {
            fmt.Println(f.Name())
    }
}

What is the reason for having '//' in Python?

To complement Alex's response, I would add that starting from Python 2.2.0a2, from __future__ import division is a convenient alternative to using lots of float(…)/…. All divisions perform float divisions, except those with //. This works with all versions from 2.2.0a2 on.

Howto: Clean a mysql InnoDB storage engine?

Here is a more complete answer with regard to InnoDB. It is a bit of a lengthy process, but can be worth the effort.

Keep in mind that /var/lib/mysql/ibdata1 is the busiest file in the InnoDB infrastructure. It normally houses six types of information:

InnoDB Architecture

InnoDB Architecture

Many people create multiple ibdata files hoping for better disk-space management and performance, however that belief is mistaken.

Can I run OPTIMIZE TABLE ?

Unfortunately, running OPTIMIZE TABLE against an InnoDB table stored in the shared table-space file ibdata1 does two things:

  • Makes the table’s data and indexes contiguous inside ibdata1
  • Makes ibdata1 grow because the contiguous data and index pages are appended to ibdata1

You can however, segregate Table Data and Table Indexes from ibdata1 and manage them independently.

Can I run OPTIMIZE TABLE with innodb_file_per_table ?

Suppose you were to add innodb_file_per_table to /etc/my.cnf (my.ini). Can you then just run OPTIMIZE TABLE on all the InnoDB Tables?

Good News : When you run OPTIMIZE TABLE with innodb_file_per_table enabled, this will produce a .ibd file for that table. For example, if you have table mydb.mytable witha datadir of /var/lib/mysql, it will produce the following:

  • /var/lib/mysql/mydb/mytable.frm
  • /var/lib/mysql/mydb/mytable.ibd

The .ibd will contain the Data Pages and Index Pages for that table. Great.

Bad News : All you have done is extract the Data Pages and Index Pages of mydb.mytable from living in ibdata. The data dictionary entry for every table, including mydb.mytable, still remains in the data dictionary (See the Pictorial Representation of ibdata1). YOU CANNOT JUST SIMPLY DELETE ibdata1 AT THIS POINT !!! Please note that ibdata1 has not shrunk at all.

InnoDB Infrastructure Cleanup

To shrink ibdata1 once and for all you must do the following:

  1. Dump (e.g., with mysqldump) all databases into a .sql text file (SQLData.sql is used below)

  2. Drop all databases (except for mysql and information_schema) CAVEAT : As a precaution, please run this script to make absolutely sure you have all user grants in place:

    mkdir /var/lib/mysql_grants
    cp /var/lib/mysql/mysql/* /var/lib/mysql_grants/.
    chown -R mysql:mysql /var/lib/mysql_grants
    
  3. Login to mysql and run SET GLOBAL innodb_fast_shutdown = 0; (This will completely flush all remaining transactional changes from ib_logfile0 and ib_logfile1)

  4. Shutdown MySQL

  5. Add the following lines to /etc/my.cnf (or my.ini on Windows)

    [mysqld]
    innodb_file_per_table
    innodb_flush_method=O_DIRECT
    innodb_log_file_size=1G
    innodb_buffer_pool_size=4G
    

    (Sidenote: Whatever your set for innodb_buffer_pool_size, make sure innodb_log_file_size is 25% of innodb_buffer_pool_size.

    Also: innodb_flush_method=O_DIRECT is not available on Windows)

  6. Delete ibdata* and ib_logfile*, Optionally, you can remove all folders in /var/lib/mysql, except /var/lib/mysql/mysql.

  7. Start MySQL (This will recreate ibdata1 [10MB by default] and ib_logfile0 and ib_logfile1 at 1G each).

  8. Import SQLData.sql

Now, ibdata1 will still grow but only contain table metadata because each InnoDB table will exist outside of ibdata1. ibdata1 will no longer contain InnoDB data and indexes for other tables.

For example, suppose you have an InnoDB table named mydb.mytable. If you look in /var/lib/mysql/mydb, you will see two files representing the table:

  • mytable.frm (Storage Engine Header)
  • mytable.ibd (Table Data and Indexes)

With the innodb_file_per_table option in /etc/my.cnf, you can run OPTIMIZE TABLE mydb.mytable and the file /var/lib/mysql/mydb/mytable.ibd will actually shrink.

I have done this many times in my career as a MySQL DBA. In fact, the first time I did this, I shrank a 50GB ibdata1 file down to only 500MB!

Give it a try. If you have further questions on this, just ask. Trust me; this will work in the short term as well as over the long haul.

CAVEAT

At Step 6, if mysql cannot restart because of the mysql schema begin dropped, look back at Step 2. You made the physical copy of the mysql schema. You can restore it as follows:

mkdir /var/lib/mysql/mysql
cp /var/lib/mysql_grants/* /var/lib/mysql/mysql
chown -R mysql:mysql /var/lib/mysql/mysql

Go back to Step 6 and continue

UPDATE 2013-06-04 11:13 EDT

With regard to setting innodb_log_file_size to 25% of innodb_buffer_pool_size in Step 5, that's blanket rule is rather old school.

Back on July 03, 2006, Percona had a nice article why to choose a proper innodb_log_file_size. Later, on Nov 21, 2008, Percona followed up with another article on how to calculate the proper size based on peak workload keeping one hour's worth of changes.

I have since written posts in the DBA StackExchange about calculating the log size and where I referenced those two Percona articles.

Personally, I would still go with the 25% rule for an initial setup. Then, as the workload can more accurate be determined over time in production, you could resize the logs during a maintenance cycle in just minutes.

How can I calculate the time between 2 Dates in typescript

This is how it should be done in typescript:

(new Date()).valueOf() - (new Date("2013-02-20T12:01:04.753Z")).valueOf()

Better readability:

      var eventStartTime = new Date(event.startTime);
      var eventEndTime = new Date(event.endTime);
      var duration = eventEndTime.valueOf() - eventStartTime.valueOf();

Using Python's os.path, how do I go up one directory?

For a paranoid like me, I'd prefer this one

TEMPLATE_DIRS = (
    __file__.rsplit('/', 2)[0] + '/templates',
)

Difference between array_push() and $array[] =

I know this is an old answer but it might be helpful for others to know that another difference between the two is that if you have to add more than 2/3 values per loop to an array it's faster to use:

     for($i = 0; $i < 10; $i++){
          array_push($arr, $i, $i*2, $i*3, $i*4, ...)
     }

instead of:

     for($i = 0; $i < 10; $i++){
         $arr[] = $i;
         $arr[] = $i*2;
         $arr[] = $i*3;
         $arr[] = $i*4;
         ...
     }

edit- Forgot to close the bracket for the for conditional

ORDER BY using Criteria API

You can add join type as well:

Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);

How to dynamically create columns in datatable and assign values to it?

If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :

  • Create Data table object.
  • Add columns into that data table object.
  • Add Rows with values into the object.

For eg.

Dim dt As New DataTable

dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))

dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")

jQuery - checkbox enable/disable

Here's another sample using JQuery 1.10.2

$(".chkcc9").on('click', function() {
            $(this)
            .parents('table')
            .find('.group1') 
            .prop('checked', $(this).is(':checked')); 
});

Setting user agent of a java URLConnection

Just for clarification: setRequestProperty("User-Agent", "Mozilla ...") now works just fine and doesn't append java/xx at the end! At least with Java 1.6.30 and newer.

I listened on my machine with netcat(a port listener):

$ nc -l -p 8080

It simply listens on the port, so you see anything which gets requested, like raw http-headers.

And got the following http-headers without setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

And WITH setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

As you can see the user agent was properly set.

Full example:

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;


public class TestUrlOpener {

    public static void main(String[] args) throws IOException {
        URL url = new URL("http://localhost:8080/foobar");
        URLConnection hc = url.openConnection();
        hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

        System.out.println(hc.getContentType());
    }

}

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

Variables can point to anywhere they want.. An error will be thrown if you do the following:

a = "dog"
print a                   #dog
a[1] = "g"                #ERROR!!!!!! STRINGS ARE IMMUTABLE

Using StringWriter for XML Serialization

<TL;DR> The problem is rather simple, actually: you are not matching the declared encoding (in the XML declaration) with the datatype of the input parameter. If you manually added <?xml version="1.0" encoding="utf-8"?><test/> to the string, then declaring the SqlParameter to be of type SqlDbType.Xml or SqlDbType.NVarChar would give you the "unable to switch the encoding" error. Then, when inserting manually via T-SQL, since you switched the declared encoding to be utf-16, you were clearly inserting a VARCHAR string (not prefixed with an upper-case "N", hence an 8-bit encoding, such as UTF-8) and not an NVARCHAR string (prefixed with an upper-case "N", hence the 16-bit UTF-16 LE encoding).

The fix should have been as simple as:

  1. In the first case, when adding the declaration stating encoding="utf-8": simply don't add the XML declaration.
  2. In the second case, when adding the declaration stating encoding="utf-16": either
    1. simply don't add the XML declaration, OR
    2. simply add an "N" to the input parameter type: SqlDbType.NVarChar instead of SqlDbType.VarChar :-) (or possibly even switch to using SqlDbType.Xml)

(Detailed response is below)


All of the answers here are over-complicated and unnecessary (regardless of the 121 and 184 up-votes for Christian's and Jon's answers, respectively). They might provide working code, but none of them actually answer the question. The issue is that nobody truly understood the question, which ultimately is about how the XML datatype in SQL Server works. Nothing against those two clearly intelligent people, but this question has little to nothing to do with serializing to XML. Saving XML data into SQL Server is much easier than what is being implied here.

It doesn't really matter how the XML is produced as long as you follow the rules of how to create XML data in SQL Server. I have a more thorough explanation (including working example code to illustrate the points outlined below) in an answer on this question: How to solve “unable to switch the encoding” error when inserting XML into SQL Server, but the basics are:

  1. The XML declaration is optional
  2. The XML datatype stores strings always as UCS-2 / UTF-16 LE
  3. If your XML is UCS-2 / UTF-16 LE, then you:
    1. pass in the data as either NVARCHAR(MAX) or XML / SqlDbType.NVarChar (maxsize = -1) or SqlDbType.Xml, or if using a string literal then it must be prefixed with an upper-case "N".
    2. if specifying the XML declaration, it must be either "UCS-2" or "UTF-16" (no real difference here)
  4. If your XML is 8-bit encoded (e.g. "UTF-8" / "iso-8859-1" / "Windows-1252"), then you:
    1. need to specify the XML declaration IF the encoding is different than the code page specified by the default Collation of the database
    2. you must pass in the data as VARCHAR(MAX) / SqlDbType.VarChar (maxsize = -1), or if using a string literal then it must not be prefixed with an upper-case "N".
    3. Whatever 8-bit encoding is used, the "encoding" noted in the XML declaration must match the actual encoding of the bytes.
    4. The 8-bit encoding will be converted into UTF-16 LE by the XML datatype

With the points outlined above in mind, and given that strings in .NET are always UTF-16 LE / UCS-2 LE (there is no difference between those in terms of encoding), we can answer your questions:

Is there a reason why I shouldn't use StringWriter to serialize an Object when I need it as a string afterwards?

No, your StringWriter code appears to be just fine (at least I see no issues in my limited testing using the 2nd code block from the question).

Wouldn't setting the encoding to UTF-16 (in the xml tag) work then?

It isn't necessary to provide the XML declaration. When it is missing, the encoding is assumed to be UTF-16 LE if you pass the string into SQL Server as NVARCHAR (i.e. SqlDbType.NVarChar) or XML (i.e. SqlDbType.Xml). The encoding is assumed to be the default 8-bit Code Page if passing in as VARCHAR (i.e. SqlDbType.VarChar). If you have any non-standard-ASCII characters (i.e. values 128 and above) and are passing in as VARCHAR, then you will likely see "?" for BMP characters and "??" for Supplementary Characters as SQL Server will convert the UTF-16 string from .NET into an 8-bit string of the current Database's Code Page before converting it back into UTF-16 / UCS-2. But you shouldn't get any errors.

On the other hand, if you do specify the XML declaration, then you must pass into SQL Server using the matching 8-bit or 16-bit datatype. So if you have a declaration stating that the encoding is either UCS-2 or UTF-16, then you must pass in as SqlDbType.NVarChar or SqlDbType.Xml. Or, if you have a declaration stating that the encoding is one of the 8-bit options (i.e. UTF-8, Windows-1252, iso-8859-1, etc), then you must pass in as SqlDbType.VarChar. Failure to match the declared encoding with the proper 8 or 16 -bit SQL Server datatype will result in the "unable to switch the encoding" error that you were getting.

For example, using your StringWriter-based serialization code, I simply printed the resulting string of the XML and used it in SSMS. As you can see below, the XML declaration is included (because StringWriter does not have an option to OmitXmlDeclaration like XmlWriter does), which poses no problem so long as you pass the string in as the correct SQL Server datatype:

-- Upper-case "N" prefix == NVARCHAR, hence no error:
DECLARE @Xml XML = N'<?xml version="1.0" encoding="utf-16"?>
<string>Test ?</string>';
SELECT @Xml;
-- <string>Test ?</string>

As you can see, it even handles characters beyond standard ASCII, given that ? is BMP Code Point U+1234, and is Supplementary Character Code Point U+1F638. However, the following:

-- No upper-case "N" prefix on the string literal, hence VARCHAR:
DECLARE @Xml XML = '<?xml version="1.0" encoding="utf-16"?>
<string>Test ?</string>';

results in the following error:

Msg 9402, Level 16, State 1, Line XXXXX
XML parsing: line 1, character 39, unable to switch the encoding

Ergo, all of that explanation aside, the full solution to your original question is:

You were clearly passing the string in as SqlDbType.VarChar. Switch to SqlDbType.NVarChar and it will work without needing to go through the extra step of removing the XML declaration. This is preferred over keeping SqlDbType.VarChar and removing the XML declaration because this solution will prevent data loss when the XML includes non-standard-ASCII characters. For example:

-- No upper-case "N" prefix on the string literal == VARCHAR, and no XML declaration:
DECLARE @Xml2 XML = '<string>Test ?</string>';
SELECT @Xml2;
-- <string>Test ???</string>

As you can see, there is no error this time, but now there is data-loss 🙀.

Simple way to compare 2 ArrayLists

If your requirement is to maintain the insertion order plus check the contents of the two arraylist then you should do following:

List<String> listOne = new ArrayList<String>();
List<String> listTwo = new ArrayList<String>();

listOne.add("stack");
listOne.add("overflow");

listTwo.add("stack");
listTwo.add("overflow");

boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray());

This will return true.

However, if you change the ordering for example:

listOne.add("stack");
listOne.add("overflow");

listTwo.add("overflow");
listTwo.add("stack");

boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray());

will return false as ordering is different.

How to store and retrieve a dictionary with redis

One might consider using MessagePack which is endorsed by redis.

import msgpack

data = {
    'one': 'one',
    'two': 2,
    'three': [1, 2, 3]
}

await redis.set('my-key', msgpack.packb(data))
val = await redis.get('my-key')
print(msgpack.unpackb(val))

# {'one': 'one', 'two': 2, 'three': [1, 2, 3]}

Using msgpack-python and aioredis

How to get base64 encoded data from html image

You can try following sample http://jsfiddle.net/xKJB8/3/

<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());

Embed HTML5 YouTube video without iframe?

Use the object tag:

<object data="http://iamawesome.com" type="text/html" width="200" height="200">
  <a href="http://iamawesome.com">access the page directly</a>
</object>

Ref: http://debug.ga/embedding-external-pages-without-iframes/

Could not find module FindOpenCV.cmake ( Error in configuration process)

I had the same error, I use windows. I add "C:\opencv\build" (opencv folder) to path at the control pannel. So, That's Ok!!

Check if table exists in SQL Server

I always check this way.

IF OBJECT_ID('TestXML..tblCustomer') IS NOT NULL  
BEGIN  
    PRINT 'Exist'
END  
ELSE
BEGIN
    PRINT 'Not Exist'
END 

Thanks

Pandas - How to flatten a hierarchical index in columns

Following @jxstanford and @tvt173, I wrote a quick function which should do the trick, regardless of string/int column names:

def flatten_cols(df):
    df.columns = [
        '_'.join(tuple(map(str, t))).rstrip('_') 
        for t in df.columns.values
        ]
    return df

How can I alter a primary key constraint using SQL syntax?

Performance wise there is no point to keep non clustered indexes during this as they will get re-updated on drop and create. If it is a big data set you should consider renaming the table (if possible , any security settings on it?), re-creating an empty table with the correct keys migrate all data there. You have to make sure you have enough space for this.

Youtube autoplay not working on mobile devices with embedded HTML5 player

There is a way to make youtube autoplay, and complete playlists play through. Get Adblock browser for Android, and then go to the youtube website, and and configure it for the desktop version of the page, close Adblock browser out, and then reopen, and you will have the desktop version, where autoplay will work.

Using the desktop version will also mean that AdBlock will work. The mobile version invokes the standalone YouTube player, which is why you want the desktop version of the page, so that autoplay will work, and so ad blocking will work.

How to change UINavigationBar background color from the AppDelegate

Swift syntax:

    UINavigationBar.appearance().barTintColor = UIColor.whiteColor() //changes the Bar Tint Color

I just put that in the AppDelegate didFinishLaunchingWithOptions and it persists throughout the app

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

One of the case

SessionFactory sf=new Configuration().configure().buildSessionFactory();
Session session=sf.openSession();

UserDetails user=new UserDetails();

session.beginTransaction();
user.setUserName("update user agian");
user.setUserId(12);
session.saveOrUpdate(user);
session.getTransaction().commit();
System.out.println("user::"+user.getUserName());

sf.close();