Programs & Examples On #Signtool

The SignTool tool is a command-line tool that digitally signs files, verifies signatures in files, or time stamps files.

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

I got the same problem in my console application development and as a quick workaround,

go to project properties then,

click on signing tab and uncheck "Sign the ClickOnce Manifest".

Image Description:

enter image description here

enter image description here

FYI You can also see this less one minute video solution. The above picture is taken form the video.

How to install SignTool.exe for Windows 10

You should go to Control Panel -> Programs and Features, find Microsoft Visual Studio 2015 and select "Change". Visual Studio 2015 setup will start. Select "Modify".

In Visual Studio components list, open the list of sub-items and select "ClickOnce Publication Tools" and "Windows 10 SDK" too.

Visual Studio SignTool.exe Not Found

No Worries! I have found the solution! I just installed https://msdn.microsoft.com/en-us/windows/desktop/bg162891.aspx and it all worked fine :)

How to Query Database Name in Oracle SQL Developer?

Edit: Whoops, didn't check your question tags before answering.

Check that you can actually connect to DB (have the driver placed? tested the conn when creating it?).

If so, try runnung those queries with F5

Git - remote: Repository not found

You might be logged in with some other GitHub credentials before. Exactly that's why this error is happening.

Usually, mac is storing your GitHub credential to the keychain access tool. Your previous git account details are there. So it is getting mismatched with your current git repo which is in other accounts.

The solution is simple and straight forward,

  1. Go to keychain access in your mac.
  2. On the left side under the category you can find all items. Click that.
  3. Right side top search "git".
  4. You will get some items regarding Github.
  5. Delete all those items.

That's it, here you go.

Try to push again. It will ask you the git username and password. Your new credentials will be stored again in the keychain and your push will be done.

Hurray!

Revert back to me, If you need more help.

Thanks

How to write a caption under an image?

<table>
<tr><td><img ...><td><img ...>
<tr><td>caption1<td>caption2
</table>

Style as desired.

SSRS expression to format two decimal places does not show zeros

Actually, I needed the following...get rid of the decimals without rounding so "12.23" needs to show as "12". In SSRS, do not format the number as a percent. Leave the formatting as default (no formatting applied) then in the expression do the following: =Fix(Fields!PctAmt.Value*100))

Multiply the number by 100 then apply the FIX function in SSRS which returns only the integer portion of a number.

How to submit an HTML form without redirection

Since all current answers use jQuery or tricks with iframe, figured there is no harm to add method with just plain JavaScript:

function formSubmit(event) {
  var url = "/post/url/here";
  var request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.onload = function() { // request successful
  // we can use server response to our request now
    console.log(request.responseText);
  };

  request.onerror = function() {
    // request failed
  };

  request.send(new FormData(event.target)); // create FormData from form that triggered event
  event.preventDefault();
}

// and you can attach form submit event like this for example
function attachFormSubmitEvent(formId){
  document.getElementById(formId).addEventListener("submit", formSubmit);
}

What are the differences between a program and an application?

When I studied IT in college my prof. made it simple for me:

"A computer "program" and an "application" (a.k.a. 'app') are one-in-the-same. The only difference is a technical one. While both are the same, an 'application' is a computer program launched and dependent upon an operating system to execute."

Got it right on the exam.

So when you click on a word processor, for example, it is an application, as is that hidden file that runs the printer spooler launched only by the OS. The two programs depend on the OS, whereby the OS itself or your internal BIOS programming are not 'apps' in the technical sense as they communicate directly with the computer hardware itself.

Unless the definition has changed in the past few years, commercial entities like Microsoft and Apple are not using the terms properly, preferring sexy marketing by making the term 'apps' seem like something popular market and 'new', because a "computer program" sounds too 'nerdy'. :(

JavaScript before leaving the page

This what I did to show the confirmation message just when I have unsaved data

window.onbeforeunload = function () {
            if (isDirty) {
                return "There are unsaved data.";
            }
            return undefined;
        }

returning "undefined" will disable the confirmation

Note: returning "null" will not work with IE

Also you can use "undefined" to disable the confirmation

window.onbeforeunload = undefined;

Excel: Searching for multiple terms in a cell

This will do it for you:

=IF(OR(ISNUMBER(SEARCH("Gingrich",C3)),ISNUMBER(SEARCH("Obama",C3))),"1","")

Given this function in the column to the right of the names (which are in column C), the result is:

Romney  
Gingrich    1
Obama       1

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

Using IntelliJ I just had to install another (higher) JDK Version. After restarting IDE, everything worked and even all dependencies were solved.

Wi-Fi Direct and iOS Support

It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.

Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.

https://developer.apple.com/library/ios/documentation/MultipeerConnectivity/Reference/MultipeerConnectivityFramework/index.html

It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."

Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.

There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.

Python naming conventions for modules

I know my solution is not very popular from the pythonic point of view, but I prefer to use the Java approach of one module->one class, with the module named as the class. I do understand the reason behind the python style, but I am not too fond of having a very large file containing a lot of classes. I find it difficult to browse, despite folding.

Another reason is version control: having a large file means that your commits tend to concentrate on that file. This can potentially lead to a higher quantity of conflicts to be resolved. You also loose the additional log information that your commit modifies specific files (therefore involving specific classes). Instead you see a modification to the module file, with only the commit comment to understand what modification has been done.

Summing up, if you prefer the python philosophy, go for the suggestions of the other posts. If you instead prefer the java-like philosophy, create a Nib.py containing class Nib.

Invoking Java main method with parameters from Eclipse

Another idea:

Place all your parameters in a properties file (one parameter = one property in this file), then in your main method, load this file (using Properties.load(*fileInputStream*)). So if you want to modify one argument, you will just need to edit your args.properties file, and launch your application without more steps to do...

Of course, this is only for development purposes, but can be really helpfull if you have to change your arguments often...

When to use MongoDB or other document oriented database systems?

Who needs distributed, sharded forums? Maybe Facebook, but unless you're creating a Facebook-competitor, just use Mysql, Postgres or whatever you are most comfortable with. If you want to try MongoDB, ok, but don't expect it to do magic for you. It'll have its quirks and general nastiness, just as everything else, as I'm sure you've already discovered if you really have been working on it already.

Sure, MongoDB may be hyped and seem easy on the surface, but you'll run into problems which more mature products have already overcome. Don't be lured so easily, but rather wait until "nosql" matures, or dies.

Personally, I think "nosql" will wither and die from fragmentation, as there are no set standards (almost by definition). So I will not personally bet on it for any long-term projects.

Only thing that can save "nosql" in my book, is if it can integrate into Ruby or similar languages seamlessly, and make the language "persistent", almost without any overhead in coding and design. That may come to pass, but I'll wait until then, not now, AND it needs to be more mature of course.

Btw, why are you creating a forum from scratch? There are tons of open source forums which can be tweaked to fit most requirements, unless you really are creating The Next Generation of Forums (which I doubt).

How do I give PHP write access to a directory?

I'm running Ubuntu, and as said above nobody:nobody does not work on Ubuntu. You get the error:

chown: invalid group: 'nobody:nobody'

Instead you should use the 'nogroup', like:

chown nobody:nogroup <dirname>

What is the correct way to restore a deleted file from SVN?

Use the Tortoise SVN copy functionality to revert commited changes:

  1. Right click the parent folder that contains the deleted files/folder
  2. Select the "show log"
  3. Select and right click on the version before which the changes/deleted was done
  4. Select the "browse repository"
  5. Select the file/folder which needs to be restored and right click
  6. Select "copy to" which will copy the files/folders to the head revision

Hope that helps

How do I find the value of $CATALINA_HOME?

Tomcat can tell you in several ways. Here's the easiest:

 $ /path/to/catalina.sh version
Using CATALINA_BASE:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_HOME:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-7.0.29/temp
Using JRE_HOME:        /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
Using CLASSPATH:       /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.29
Server built:   Jul 3 2012 11:31:52
Server number:  7.0.29.0
OS Name:        Mac OS X
OS Version:     10.7.4
Architecture:   x86_64
JVM Version:    1.6.0_33-b03-424-11M3720
JVM Vendor:     Apple Inc.

If you don't know where catalina.sh is (or it never gets called), you can usually find it via ps:

$ ps aux | grep catalina
chris            930   0.0  3.1  2987336 258328 s000  S    Wed01PM   2:29.43 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -Dnop -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.library.path=/usr/local/apache-tomcat-7.0.29/lib -Djava.endorsed.dirs=/usr/local/apache-tomcat-7.0.29/endorsed -classpath /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar -Dcatalina.base=/Users/chris/blah/blah -Dcatalina.home=/usr/local/apache-tomcat-7.0.29 -Djava.io.tmpdir=/Users/chris/blah/blah/temp org.apache.catalina.startup.Bootstrap start

From the ps output, you can see both catalina.home and catalina.base. catalina.home is where the Tomcat base files are installed, and catalina.base is where the running configuration of Tomcat exists. These are often set to the same value unless you have configured your Tomcat for multiple (configuration) instances to be launched from a single Tomcat base install.

You can also interrogate the JVM directly if you can't find it in a ps listing:

$ jinfo -sysprops 930 | grep catalina
Attaching to process ID 930, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 20.8-b03-424
catalina.base = /Users/chris/blah/blah
[...]
catalina.home = /usr/local/apache-tomcat-7.0.29

If you can't manage that, you can always try to write a JSP that dumps the values of the two system properties catalina.home and catalina.base.

Fastest way to zero out a 2d array in C?

If you initialize the array with malloc, use calloc instead; it will zero your array for free. (Same perf obviously as memset, just less code for you.)

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

How to check if a column is empty or null using SQL query select statement?

An answer above got me 99% of the way there (thanks Denis Ivin!). For my PHP / MySQL implementation, I needed to change the syntax a little:

SELECT *
FROM UserProfile
WHERE PropertydefinitionID in (40, 53)
AND (LENGTH(IFNULL(PropertyValue,'')) = 0)

LEN becomes LENGTH and ISNULL becomes IFNULL.

How to get RegistrationID using GCM in android

In response to your first question: Yes, you have to run a server app to send the messages, as well as a client app to receive them.

In response to your second question: Yes, every application needs its own API key. This key is for your server app, not the client.

How can I read and manipulate CSV file data in C++?

You can try the Boost Tokenizer library, in particular the Escaped List Separator

How do I create an Excel chart that pulls data from multiple sheets?

Here's some code from Excel 2010 that may work. It has a couple specifics (like filtering bad-encode characters from titles) but it was designed to create multiple multi-series graphs from 4-dimensional data having both absolute and percentage-based data. Modify it how you like:

Sub createAllGraphs()

Const chartWidth As Integer = 260
Const chartHeight As Integer = 200




If Sheets.Count = 1 Then
    Sheets.Add , Sheets(1)
    Sheets(2).Name = "AllCharts"
ElseIf Sheets("AllCharts").ChartObjects.Count > 0 Then
    Sheets("AllCharts").ChartObjects.Delete
End If
Dim c As Variant
Dim c2 As Variant
Dim cs As Object
Set cs = Sheets("AllCharts")
Dim s As Object
Set s = Sheets(1)

Dim i As Integer


Dim chartX As Integer
Dim chartY As Integer

Dim r As Integer
r = 2

Dim curA As String
curA = s.Range("A" & r)
Dim curB As String
Dim curC As String
Dim startR As Integer
startR = 2

Dim lastTime As Boolean
lastTime = False

Do While s.Range("A" & r) <> ""

    If curC <> s.Range("C" & r) Then

        If r <> 2 Then
seriesAdd:
            c.SeriesCollection.Add s.Range("D" & startR & ":E" & (r - 1)), , False, True
            c.SeriesCollection(c.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
            c.SeriesCollection(c.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).Values = "='" & s.Name & "'!$E$" & startR & ":$E$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).HasErrorBars = True
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBars.Select
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1), minusvalues:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0

            c2.SeriesCollection.Add s.Range("D" & startR & ":D" & (r - 1) & ",G" & startR & ":G" & (r - 1)), , False, True
            c2.SeriesCollection(c2.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
            c2.SeriesCollection(c2.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).Values = "='" & s.Name & "'!$G$" & startR & ":$G$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).HasErrorBars = True
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBars.Select
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1), minusvalues:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0
            If lastTime = True Then GoTo postLoop
        End If

        If curB <> s.Range("B" & r).Value Then

            If curA <> s.Range("A" & r).Value Then
                chartX = chartX + chartWidth * 2
                chartY = 0
                curA = s.Range("A" & r)
            End If

            Set c = cs.ChartObjects.Add(chartX, chartY, chartWidth, chartHeight)
            Set c = c.Chart
            c.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r), s.Range("D1"), s.Range("E1")

            Set c2 = cs.ChartObjects.Add(chartX + chartWidth, chartY, chartWidth, chartHeight)
            Set c2 = c2.Chart
            c2.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r) & " (%)", s.Range("D1"), s.Range("G1")

            chartY = chartY + chartHeight
            curB = s.Range("B" & r)
            curC = s.Range("C" & r)
        End If

        curC = s.Range("C" & r)
        startR = r
    End If

    If s.Range("A" & r) <> "" Then oneMoreTime = False ' end the loop for real this time
    r = r + 1
Loop

lastTime = True
GoTo seriesAdd
postLoop:
cs.Activate

End Sub

How to create .ipa file using Xcode?

Archive process (using Xcode 8.3.2)

Note : If you are using creating IPA using drag-and-drop process using iTunes Mac app then this is no longer applicable for iTunes 12.7 since there is no built-in App store in iTunes 12.7.

  1. Select ‘Generic iOS Device’ on device list in Xcode

Step 1

  1. Clean the project (cmd + shift + k as shortcut)

Step 2

  1. Go to Product -> Archive your project

Step 3

  1. Once archive is succeeded this will open a window with archived project

  2. You can validate your archive by pressing Validate (optional step but recommended)

  3. Now press on Export button

Step 4 5 6

  1. This will open list of method for export. Select the export method as per your requirement and click on Next button.

Step 7

  1. This will show list of team for provisioning. Select accordingly and press on ‘Choose’ button.

Step 8

  1. Now you’ve to select Device support -> Export one app for all compatible devices (recommended). If you want IPA for specific device then select the device variant from list and press on ‘Next’ button.

Step 9

  1. Now you’ll be able to see the ‘Summary’ and then press on ‘Next’ button

Step 10

  1. Thereafter IPA file generation beings and later you’ll be able to export the IPA as [App Name - Date Time] and then press on ‘Done’.

Step 11

What's the difference between text/xml vs application/xml for webservice response

application/xml is seen by svn as binary type whereas text/xml as text file for which a diff can be displayed.

Simplest way to set image as JPanel background

I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class

yes you will have to extend JPanel and override the paintcomponent(Graphics g) function to do so.

@Override
  protected void paintComponent(Graphics g) {

    super.paintComponent(g);
        g.drawImage(bgImage, 0, 0, null);
}

I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).

You can use other component which allows to add image as icon directly e.g. JLabel if you want.

ImageIcon icon = new ImageIcon(imgURL); 
JLabel thumb = new JLabel();
thumb.setIcon(icon);

But again in the bracket trying to keep things organized and simple !! what makes you to think that just creating a new class will lead you to a messy world ?

Delete all rows in table

Truncate table is faster than delete * from XXX. Delete is slow because it works one row at a time. There are a few situations where truncate doesn't work, which you can read about on MSDN.

Using unset vs. setting a variable to empty

As has been said, using unset is different with arrays as well

$ foo=(4 5 6)

$ foo[2]=

$ echo ${#foo[*]}
3

$ unset foo[2]

$ echo ${#foo[*]}
2

Use HTML5 to resize an image before upload

If some of you, like me, encounter orientation problems I have combined the solutions here with a exif orientation fix

https://gist.github.com/SagiMedina/f00a57de4e211456225d3114fd10b0d0

Filter output in logcat by tagname

Another option is setting the log levels for specific tags:

adb logcat SensorService:S PowerManagerService:S NfcService:S power:I Sensors:E

If you just want to set the log levels for some tags you can do it on a tag by tag basis.

Gitignore not working

In my case whitespaces at the end of the lines of .gitignore was the cause. So watch out for whitespaces in the .gitignore!

Show/hide forms using buttons and JavaScript

There's the global attribute called hidden. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?

_x000D_
_x000D_
var someCondition = true;_x000D_
_x000D_
if (someCondition == true){_x000D_
    document.getElementById('hidden div').hidden = false;_x000D_
}
_x000D_
<div id="hidden div" hidden>_x000D_
    stuff hidden by default_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden

How to tell Maven to disregard SSL errors (and trusting all certs)?

Create a folder ${USER_HOME}/.mvn and put a file called maven.config in it.

The content should be:

-Dmaven.wagon.http.ssl.insecure=true
-Dmaven.wagon.http.ssl.allowall=true
-Dmaven.wagon.http.ssl.ignore.validity.dates=true

Hope this helps.

How to generate random colors in matplotlib?

Here is a more concise version of Ali's answer giving one distinct color per plot :

import matplotlib.pyplot as plt

N = len(data)
cmap = plt.cm.get_cmap("hsv", N+1)
for i in range(N):
    X,Y = data[i]
    plt.scatter(X, Y, c=cmap(i))

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

If you really need to do it in separate transaction you need to use REQUIRES_NEW and live with the performance overhead. Watch out for dead locks.

I'd rather do it the other way:

  • Validate data on Java side.
  • Run everyting in one transaction.
  • If anything goes wrong on DB side -> it's a major error of DB or validation design. Rollback everything and throw critical top level error.
  • Write good unit tests.

Get public/external IP address?

With .Net WebRequest:

  public static string GetPublicIP()
    {
        string url = "http://checkip.dyndns.org";
        System.Net.WebRequest req = System.Net.WebRequest.Create(url);
        System.Net.WebResponse resp = req.GetResponse();
        System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
        string response = sr.ReadToEnd().Trim();
        string[] a = response.Split(':');
        string a2 = a[1].Substring(1);
        string[] a3 = a2.Split('<');
        string a4 = a3[0];
        return a4;
    }

Why does flexbox stretch my image rather than retaining aspect ratio?

It is stretching because align-self default value is stretch. there is two solution for this case : 1. set img align-self : center OR 2. set parent align-items : center

img {

   align-self: center
}

OR

.parent {
  align-items: center
}

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

I had a similar issue when onMouseEnter was called but sometimes the corresponding onMouseLeave event wasn't fired, here is a workaround that works well for me (it partially relies on jQuery):

var Hover = React.createClass({
    getInitialState: function() {
        return {
            hover: false
        };
    },
    onMouseEnterHandler: function(e) {
        this.setState({
            hover: true
        });
        console.log('enter');

        $(e.currentTarget).one("mouseleave", function (e) {
            this.onMouseLeaveHandler();
        }.bind(this));

    },
    onMouseLeaveHandler: function() {
        this.setState({
            hover: false
        });
        console.log('leave');
    },
    render: function() {
        var inner = normal;
        if(this.state.hover) {
            inner = hover;
        }

        return (
            <div style={outer}>
                <div style={inner}
                    onMouseEnter={this.onMouseEnterHandler} >
                    {this.props.children}
                </div>
            </div>
        );
    }
});

See on jsfiddle: http://jsfiddle.net/qtbr5cg6/1/


Why was it happening (in my case): I am running a jQuery scrolling animation (through $('#item').animate({ scrollTop: 0 })) when clicking on the item. So the cursor doesn't leave the item "naturally", but during a the JavaScript-driven animation ... and in this case the onMouseLeave was not fired properly by React (React 15.3.0, Chrome 51, Desktop)

Adding Google Play services version to your app's manifest?

It is probably that your library is not linked to project properly or that you have older google-play-services library version so conflict appears and Eclipse got stupid.. :S

No you don't need to add anything in integers.xml. When you link properly Google-play-services library to your project reference android:value="@integer/google_play_services_version" will be found and you are ready to go. When you add library to your project just do one more clean so funny Eclipse environment sweep-out things properly.

If you hardcode somewhere this number when next play version come you would need to update it. And if you forget that, you will spend time again looking for bug.. :S

Hope it helped. ;)

How do I convert between big-endian and little-endian values in C++?

There is an assembly instruction called BSWAP that will do the swap for you, extremely fast. You can read about it here.

Visual Studio, or more precisely the Visual C++ runtime library, has platform intrinsics for this, called _byteswap_ushort(), _byteswap_ulong(), and _byteswap_int64(). Similar should exist for other platforms, but I'm not aware of what they would be called.

Add resources, config files to your jar using gradle

Be aware that the path under src/main/resources must match the package path of your .class files wishing to access the resource. See my answer here.

How to add google-play-services.jar project dependency so my project will run and present map

The quick start guide that keyboardsurfer references will work if you need to get your project to build properly, but it leaves you with a dummy google-play-services project in your Eclipse workspace, and it doesn't properly link Eclipse to the Google Play Services Javadocs.

Here's what I did instead:

  1. Install the Google Play Services SDK using the instructions in the Android Maps V2 Quick Start referenced above, or the instructions to Setup Google Play Services SDK, but do not follow the instructions to add Google Play Services into your project.

  2. Right click on the project in the Package Explorer, select Properties to open the properties for your project.

  3. (Only if you already followed the instructions in the quick start guide!) Remove the dependency on the google-play-services project:

    • Click on the Android category and remove the reference to the google-play-services project.

    • Click on the Java Build Path category, then the Projects tab and remove the reference to the google-play-services project.

  4. Click on the Java Build Path category, then the Libraries tab.

  5. Click Add External JARs... and select the google-play-services.jar file. This should be in [Your ADT directory]\sdk\extras\google\google_play_services\libproject\google-play-services_lib\libs.

  6. Click on the arrow next to the new google-play-services.jar entry, and select the Javadoc Location item.

  7. Click Edit... and select the folder containing the Google Play Services Javadocs. This should be in [Your ADT directory]\sdk\extras\google\google_play_services\docs\reference.

  8. Still in the Java Build Path category, click on the Order and Export tab. Check the box next to the google-play-services.jar entry.

  9. Click OK to save your project properties.

Your project should now have access to the Google Play Services library, and the Javadocs should display properly in Eclipse.

Perfect 100% width of parent container for a Bootstrap input?

For anyone Googling this, one suggestion is to remove all the input-group class instances. Worked for me in a similar situation. Original code:

_x000D_
_x000D_
<form>_x000D_
  <div class="bs-callout">_x000D_
    <div class="row">_x000D_
      <div class="col-md-4">_x000D_
        <div class="form-group">_x000D_
          <div class="input-group">_x000D_
            <input type="text" class="form-control" name="time" placeholder="Time">_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="col-md-8">_x000D_
        <div class="form-group">_x000D_
          <div class="input-group">_x000D_
            <select name="dtarea" class="form-control">_x000D_
              <option value="1">Option value 1</option>_x000D_
            </select>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="row">_x000D_
      <div class="input-group">_x000D_
        <input type="text" name="reason" class="form-control" placeholder="Reason">_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_ With input-group

New code:

_x000D_
_x000D_
<form>_x000D_
  <div class="bs-callout">_x000D_
    <div class="row">_x000D_
      <div class="col-md-4">_x000D_
        <div class="form-group">_x000D_
          <input type="text" class="form-control" name="time" placeholder="Time">_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="col-md-8">_x000D_
        <div class="form-group">_x000D_
          <select name="dtarea" class="form-control">_x000D_
            <option value="1">Option value 1</option>_x000D_
          </select>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="row">_x000D_
      <input type="text" name="reason" class="form-control" placeholder="Reason">_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_ Without input-group

open resource with relative path in Java

Supply the path relative to the classloader, not the class you're getting the loader from. For instance:

resourcesloader.class.getClassLoader().getResource("package1/resources/repository/SSL-Key/cert.jks").toString();

How to install a specific version of Node on Ubuntu?

Chris Lea has 0.8.23 in his ppa repo.

This package let you add a repository to apt-get: (You can also do this manually)

sudo apt-get install software-properties-common

Add Chris Lea's repository:

sudo apt-add-repository ppa:chris-lea/node.js-legacy

Update apt-get:

sudo apt-get update

Install Node.js:

sudo apt-get install nodejs=0.8.23-1chl1~precise1

I think (feel free to edit) the version number is optional if you only add node.js-legacy. If you add both legacy and ppa/chris-lea/node.js you most likely need to add the version.

HTML page disable copy/paste

You can use jquery for this:

$('body').bind('copy paste',function(e) {
    e.preventDefault(); return false; 
});

Using jQuery bind() and specififying your desired eventTypes .

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

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.querySelector('attributeValue').value='new value'");

How do you use colspan and rowspan in HTML tables?

<body>
<table>
<tr><td colspan="2" rowspan="2">1</td><td colspan="4">2</td></tr>
<tr><td>3</td><td>3</td><td>3</td><td>3</td></tr>
<tr><td colspan="2">1</td><td>3</td><td>3</td><td>3</td><td>3</td></tr>
</table>
</body>

Convert String to Date in MS Access Query

Use the DateValue() function to convert a string to date data type. That's the easiest way of doing this.

DateValue(String Date) 

How to convert a Drawable to a Bitmap?

Here is better resolution

public static Bitmap drawableToBitmap (Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable)drawable).getBitmap();
    }

    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

public static InputStream bitmapToInputStream(Bitmap bitmap) {
    int size = bitmap.getHeight() * bitmap.getRowBytes();
    ByteBuffer buffer = ByteBuffer.allocate(size);
    bitmap.copyPixelsToBuffer(buffer);
    return new ByteArrayInputStream(buffer.array());
}

Code from How to read drawable bits as InputStream

Change One Cell's Data in mysql

UPDATE TABLE <tablename> SET <COLUMN=VALUE> WHERE <CONDITION>

Example:

UPDATE TABLE teacher SET teacher_name='NSP' WHERE teacher_id='1'

How to shift a block of code left/right by one space in VSCode?

Have a look at File > Preferences > Keyboard Shortcuts (or Ctrl+K Ctrl+S)

Search for cursorColumnSelectDown or cursorColumnSelectUp which will give you the relevent keyboard shortcut. For me it is Shift+Alt+Down/Up Arrow

HTML5 - mp4 video does not play in IE9

for IE9 I found that a meta tag was required to set the mode

<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>

<video width="400" height="300" preload controls>
<source src="movie.mp4" type="video/mp4" />
Your browser does not support the video tag
</video>

Limiting floats to two decimal points

The Python tutorial has an appendix called Floating Point Arithmetic: Issues and Limitations. Read it. It explains what is happening and why Python is doing its best. It has even an example that matches yours. Let me quote a bit:

>>> 0.1
0.10000000000000001

you may be tempted to use the round() function to chop it back to the single digit you expect. But that makes no difference:

>>> round(0.1, 1)
0.10000000000000001

The problem is that the binary floating-point value stored for “0.1” was already the best possible binary approximation to 1/10, so trying to round it again can’t make it better: it was already as good as it gets.

Another consequence is that since 0.1 is not exactly 1/10, summing ten values of 0.1 may not yield exactly 1.0, either:

>>> sum = 0.0
>>> for i in range(10):
...     sum += 0.1
...
>>> sum
0.99999999999999989

One alternative and solution to your problems would be using the decimal module.

How can I read inputs as numbers?

input() (Python 3) and raw_input() (Python 2) always return strings. Convert the result to integer explicitly with int().

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

How to gzip all files in all sub-directories into one compressed file in bash

tar -zcvf compressFileName.tar.gz folderToCompress

everything in folderToCompress will go to compressFileName

Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName

Eslint: How to disable "unexpected console statement" in Node.js?

If you're still having trouble even after configuring your package.json according to the documentation (if you've opted to use package.json to track rather than separate config files):

"rules": {
      "no-console": "off"
    },

And it still isn't working for you, don't forget you need to go back to the command line and do npm install again. :)

Switching to landscape mode in Android Emulator

following for different plateform

WINDOWS: Ctrl + F12

LINUX: Ctrl + F12

MAC OS X: control + F12 (or fn + control + F12, depending on your keyboard configuration)

How to resolve git stash conflict without commit?

Its not the best way to do it but it works:

$ git stash apply
$ >> resolve your conflict <<
$ >> do what you want to do with your code <<
$ git checkout HEAD -- file/path/to/your/file

Uninstall all installed gems, in OSX?

A slighest different version, skipping the cut step, taking advantage of the '--no-version' option:

gem list --no-version |xargs gem uninstall -ax

Since you are removing everything, I don't see the need for the 'I' option. Whenever the gem is removed, it's fine.

TypeError: a bytes-like object is required, not 'str'

This code is probably good for Python 2. But in Python 3, this will cause an issue, something related to bit encoding. I was trying to make a simple TCP server and encountered the same problem. Encoding worked for me. Try this with sendto command.

clientSocket.sendto(message.encode(),(serverName, serverPort))

Similarly you would use .decode() to receive the data on the UDP server side, if you want to print it exactly as it was sent.

How to find a Java Memory Leak

You can find out by measuring memory usage size after calling garbage collector multiple times:

Runtime runtime = Runtime.getRuntime();

while(true) {
    ...
    if(System.currentTimeMillis() % 4000 == 0){
        System.gc();
        float usage = (float) (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024;
        System.out.println("Used memory: " + usage + "Mb");
    }

}

If the output numbers were equal, there is no memory leak in your application, but if you saw difference between the numbers of memory usage (increasing numbers), there is memory leak in your project. For example:

Used memory: 14.603279Mb
Used memory: 14.737213Mb
Used memory: 14.772224Mb
Used memory: 14.802681Mb
Used memory: 14.840599Mb
Used memory: 14.900841Mb
Used memory: 14.942261Mb
Used memory: 14.976143Mb

Note that sometimes it takes some time to release memory by some actions like streams and sockets. You should not judge by first outputs, You should test it in a specific amount of time.

How to insert a row between two rows in an existing excel with HSSF (Apache POI)

I came across the same issue recently. I had to insert new rows in a document with hidden rows and faced the same issues with you. After some search and some emails in apache poi list, it seems like a bug in shiftrows() when a document has hidden rows.

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

INSERT INTO ... ON DUPLICATE KEY UPDATE will only work for MYSQL, not for SQL Server.

for SQL server, the way to work around this is to first declare a temp table, insert value to that temp table, and then use MERGE

Like this:

declare @Source table
(
name varchar(30),
age decimal(23,0)
)

insert into @Source VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29);


MERGE beautiful  AS Tg
using  @source as Sc
on tg.namet=sc.name 

when matched then update 
set tg.age=sc.age

when not matched then 
insert (name, age) VALUES
(SC.name, sc.age);

javascript remove "disabled" attribute from html input

To set the disabled to false using the name property of the input:

document.myForm.myInputName.disabled = false;

How can I get table names from an MS Access Database?

Schema information which is designed to be very close to that of the SQL-92 INFORMATION_SCHEMA may be obtained for the Jet/ACE engine (which is what I assume you mean by 'access') via the OLE DB providers.

See:

OpenSchema Method (ADO)

Supported Schema Rowsets

CR LF notepad++ removal

Goto View -> Show Symbol -> Show All Characters. Uncheck it. There you go.!!

enter image description here

How can I parse a local JSON file from assets folder into a ListView?

As Faizan describes in their answer here:

First of all read the Json File from your assests file using below code.

and then you can simply read this string return by this function as

public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open("yourfilename.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

and use this method like that

    try {
        JSONObject obj = new JSONObject(loadJSONFromAsset());
        JSONArray m_jArry = obj.getJSONArray("formules");
        ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> m_li;

        for (int i = 0; i < m_jArry.length(); i++) {
            JSONObject jo_inside = m_jArry.getJSONObject(i);
            Log.d("Details-->", jo_inside.getString("formule"));
            String formula_value = jo_inside.getString("formule");
            String url_value = jo_inside.getString("url");

            //Add your values in your `ArrayList` as below:
            m_li = new HashMap<String, String>();
            m_li.put("formule", formula_value);
            m_li.put("url", url_value);

            formList.add(m_li);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

For further details regarding JSON Read HERE

How do I get a human-readable file size in bytes abbreviation using .NET?

string[] suffixes = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
int s = 0;
long size = fileInfo.Length;

while (size >= 1024)
{
    s++;
    size /= 1024;
}

string humanReadable = String.Format("{0} {1}", size, suffixes[s]);

height: 100% for <div> inside <div> with display: table-cell

This is exactly what you want:

HTML

<div class="table">

    <div class="cell">
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
    </div>
    <div class="cell">
        <div class="container">Text</div>
    </div>
</div>

CSS

.table {
    display: table;
    height:auto;
}

.cell {
    border: 2px solid black; 
    display:table-cell;
    vertical-align:top;
}

.container {
    height: 100%;
    overflow:auto;
    border: 2px solid green;
    -moz-box-sizing: border-box;
}

Attempt to set a non-property-list object as an NSUserDefaults

Swift 5: The Codable protocol can be used instead of NSKeyedArchiever.

struct User: Codable {
    let id: String
    let mail: String
    let fullName: String
}

The Pref struct is custom wrapper around the UserDefaults standard object.

struct Pref {
    static let keyUser = "Pref.User"
    static var user: User? {
        get {
            if let data = UserDefaults.standard.object(forKey: keyUser) as? Data {
                do {
                    return try JSONDecoder().decode(User.self, from: data)
                } catch {
                    print("Error while decoding user data")
                }
            }
            return nil
        }
        set {
            if let newValue = newValue {
                do {
                    let data = try JSONEncoder().encode(newValue)
                    UserDefaults.standard.set(data, forKey: keyUser)
                } catch {
                    print("Error while encoding user data")
                }
            } else {
                UserDefaults.standard.removeObject(forKey: keyUser)
            }
        }
    }
}

So you can use it this way:

Pref.user?.name = "John"

if let user = Pref.user {...

Python:Efficient way to check if dictionary is empty or not

any(d)

This will return true if the dict. d contains at least one truelike key, false otherwise.

Example:

any({0:'test'}) == False

another (more general) way is to check the number of items:

len(d)

iPhone UILabel text soft shadow

Subclass UILabel, and override -drawInRect:

Check if event exists on element

I ended up doing this

typeof ($('#mySelector').data('events').click) == "object"

Automatic HTTPS connection/redirect with node.js/express

Thanks to this guy: https://www.tonyerwin.com/2014/09/redirecting-http-to-https-with-nodejs.html

app.use (function (req, res, next) {
        if (req.secure) {
                // request was via https, so do no special handling
                next();
        } else {
                // request was via http, so redirect to https
                res.redirect('https://' + req.headers.host + req.url);
        }
});

Android - default value in editText

You can use EditText.setText(...) to set the current text of an EditText field.

Example:

yourEditText.setText(currentUserName);

How Do I Convert an Integer to a String in Excel VBA?

In my case, the function CString was not found. But adding an empty string to the value works, too.

Dim Test As Integer, Test2 As Variant
Test = 10
Test2 = Test & ""
//Test2 is now "10" not 10

Json.net serialize/deserialize derived types?

If you are storing the type in your text (as you should be in this scenario), you can use the JsonSerializerSettings.

See: how to deserialize JSON into IEnumerable<BaseType> with Newtonsoft JSON.NET

Be careful, though. Using anything other than TypeNameHandling = TypeNameHandling.None could open yourself up to a security vulnerability.

How do you post data with a link

I assume that each house is stored in its own table and has an 'id' field, e.g house id. So when you loop through the houses and display them, you could do something like this:

<a href="house.php?id=<?php echo $house_id;?>">
  <?php echo $house_name;?>
</a>

Then in house.php, you would get the house id using $_GET['id'], validate it using is_numeric() and then display its info.

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

Parsing jQuery AJAX response

Imagine that this is your Json response

{"Visit":{"VisitId":8,"Description":"visit8"}}

This is how you parse the response and access the values

    Ext.Ajax.request({
    headers: {
        'Content-Type': 'application/json'
    },
    url: 'api/fullvisit/getfullvisit/' + visitId,
    method: 'GET',
    dataType: 'json',
    success: function (response, request) {
        obj = JSON.parse(response.responseText);
        alert(obj.Visit.VisitId);
    }
});

This will alert the VisitId field

How can I uninstall npm modules in Node.js?

I found this out the hard way, even if it is seemingly obvious.

I initially tried to loop through the node_modules directory running npm uninstall module-name with a simple for loop in a script. I found out it will not work if you call the full path, e.g.,

npm uninstall module-name

was working, but

npm uninstall /full/path/to/node_modules/module-name 

was not working.

Dynamic WHERE clause in LINQ

I came up with a solution that even I can understand... by using the 'Contains' method you can chain as many WHERE's as you like. If the WHERE is an empty string, it's ignored (or evaluated as a select all). Here is my example of joining 2 tables in LINQ, applying multiple where clauses and populating a model class to be returned to the view. (this is a select all).

public ActionResult Index()
    {
        string AssetGroupCode = "";
        string StatusCode = "";
        string SearchString = "";

        var mdl = from a in _db.Assets
                  join t in _db.Tags on a.ASSETID equals t.ASSETID
                  where a.ASSETGROUPCODE.Contains(AssetGroupCode)
                  && a.STATUSCODE.Contains(StatusCode)
                  && (
                  a.PO.Contains(SearchString)
                  || a.MODEL.Contains(SearchString)
                  || a.USERNAME.Contains(SearchString)
                  || a.LOCATION.Contains(SearchString)
                  || t.TAGNUMBER.Contains(SearchString)
                  || t.SERIALNUMBER.Contains(SearchString)
                  )
                  select new AssetListView
                  {
                      AssetId = a.ASSETID,
                      TagId = t.TAGID,
                      PO = a.PO,
                      Model = a.MODEL,
                      UserName = a.USERNAME,
                      Location = a.LOCATION,
                      Tag = t.TAGNUMBER,
                      SerialNum = t.SERIALNUMBER
                  };


        return View(mdl);
    }

How to deploy ASP.NET webservice to IIS 7?

  1. rebuild project in VS
  2. copy project folder to iis folder, probably C:\inetpub\wwwroot\
  3. in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
  4. add web service to created website, almost the same as 3.
  5. INSTALL ASP for windows 7 and .net 4.0: c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
  6. check access to web service on your browser

python inserting variable string as file name

Even better are f-strings in python 3!

f = open(f'{name}.csv', 'wb')

How do I right align div elements?

I know this is an old post but couldn't you just use <div id=xyz align="right"> for right.

You can just replace right with left, center and justify.

Worked on my site:)

Removing a model in rails (reverse of "rails g model Title...")

For future questioners: If you can't drop the tables from the console, try to create a migration that drops the tables for you. You should create a migration and then in the file note tables you want dropped like this:

class DropTables < ActiveRecord::Migration
  def up
    drop_table :table_you_dont_want
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

The question, essentially, is "how to concatenate arrays in Ruby". Naturally the answer is to use concat or + as mentioned in nearly every answer.

A natural extension to the question would be "how to perform row-wise concatenation of 2D arrays in Ruby". When I googled "ruby concatenate matrices", this SO question was the top result so I thought I would leave my answer to that (unasked but related) question here for posterity.


In some applications you might want to "concatenate" two 2D arrays row-wise. Something like,

[[a, b], | [[x],    [[a, b, x],
 [c, d]] |  [y]] =>  [c, d, y]]

This is something like "augmenting" a matrix. For example, I used this technique to create a single adjacency matrix to represent a graph out of a bunch of smaller matrices. Without this technique I would have had to iterate over the components in a way that could have been error prone or frustrating to think about. I might have had to do an each_with_index, for example. Instead I combined zip and flatten as follows,

# given two multi-dimensional arrays that you want to concatenate row-wise
m1 = [[:a, :b], [:c, :d]]
m2 = [[:x], [:y]]

m1m2 = m1.zip(m2).map(&:flatten)
# => [[:a, :b, :x], [:c, :d, :y]]

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

My general pattern is that if it fits on one line, I'll do:

if(true) do_something();

If there's an else clause, or if the code I want to execute on true is of significant length, braces all the way:

if(true) {
    do_something_and_pass_arguments_to_it(argument1, argument2, argument3);
}

if(false) {
    do_something();
} else {
    do_something_else();
}

Ultimately, it comes down to a subjective issue of style and readability. The general programming world, however, pretty much splits into two parties (for languages that use braces): either use them all the time without exception, or use them all the time with exception. I'm part of the latter group.

How to show SVG file on React Native?

I posted another solution here Which is the best approach to insert an vector (svg) graph into a react native application, This approach use a vector font(from svg) instead a svg file. PS: Its works great in ios and android, and you also can change the color and size of your vector icon.

If you want to insert a svg directly into your app, you can try a 3rd party library : react-native-svg. With more than 3k stars in github it's one of the best approach.

  • install:
    • npm i react-native-svg
    • npm i react-native-svg-uri
  • link the to native:
    • react-native link react-native-svg

And here's a sample:

import * as React from 'react';
import SvgUri from 'react-native-svg-uri';
import testSvg from './test.svg';
export default () => (
  <SvgUri
    width="200"
    height="200"
    svgXmlData={testSvg}
  />
);

How do I create my own URL protocol? (e.g. so://...)

You don't really have to do any registering as such. I've seen many programs, like emule, create their own protocol specificier (that's what I think it's called). After that, you basically just have to set some values in the registry as to what program handles that protocol. I'm not sure if there's any official registry of protocol specifiers. There isn't really much to stop you from creating your own protocol specifier for your own application if you want people to open your app from their browser.

Correct way to try/except using Python requests module?

Exception object also contains original response e.response, that could be useful if need to see error body in response from the server. For example:

try:
    r = requests.post('somerestapi.com/post-here', data={'birthday': '9/9/3999'})
    r.raise_for_status()
except requests.exceptions.HTTPError as e:
    print (e.response.text)

Convert json to a C# array?

using Newtonsoft.Json;

Install this class in package console This class works fine in all .NET Versions, for example in my project: I have DNX 4.5.1 and DNX CORE 5.0 and everything works.

Firstly before JSON deserialization, you need to declare a class to read normally and store some data somewhere This is my class:

public class ToDoItem
{
    public string text { get; set; }
    public string complete { get; set; }
    public string delete { get; set; }
    public string username { get; set; }
    public string user_password { get; set; }
    public string eventID { get; set; }
}

In HttpContent section where you requesting data by GET request for example:

HttpContent content = response.Content;
string mycontent = await content.ReadAsStringAsync();
//deserialization in items
ToDoItem[] items = JsonConvert.DeserializeObject<ToDoItem[]>(mycontent);

How to implement private method in ES6 class with Traceur

Although currently there is no way to declare a method or property as private, ES6 modules are not in the global namespace. Therefore, anything that you declare in your module and do not export will not be available to any other part of your program, but will still be available to your module during run time. Thus, you have private properties and methods :)

Here is an example (in test.js file)

function tryMe1(a) {
  console.log(a + 2);
}

var tryMe2 = 1234;

class myModule {
  tryMe3(a) {
    console.log(a + 100);
  }

  getTryMe1(a) {
    tryMe1(a);
  }

  getTryMe2() {
    return tryMe2;
  }
}

// Exports just myModule class. Not anything outside of it.
export default myModule; 

In another file

import MyModule from './test';

let bar = new MyModule();

tryMe1(1); // ReferenceError: tryMe1 is not defined
tryMe2; // ReferenceError: tryMe2 is not defined
bar.tryMe1(1); // TypeError: bar.tryMe1 is not a function
bar.tryMe2; // undefined

bar.tryMe3(1); // 101
bar.getTryMe1(1); // 3
bar.getTryMe2(); // 1234

log4j logging hierarchy order

Use the force, read the source (excerpt from the Priority and Level class compiled, TRACE level was introduced in version 1.2.12):

public final static int OFF_INT = Integer.MAX_VALUE;
public final static int FATAL_INT = 50000;
public final static int ERROR_INT = 40000;
public final static int WARN_INT  = 30000;
public final static int INFO_INT  = 20000;
public final static int DEBUG_INT = 10000;
public static final int TRACE_INT = 5000; 
public final static int ALL_INT = Integer.MIN_VALUE; 

or the log4j API for the Level class, which makes it quite clear.

When the library decides whether to print a certain statement or not, it computes the effective level of the responsible Logger object (based on configuration) and compares it with the LogEvent's level (depends on which method was used in the code – trace/debug/.../fatal). If LogEvent's level is greater or equal to the Logger's level, the LogEvent is sent to appender(s) – "printed". At the core, it all boils down to an integer comparison and this is where these constants come to action.

Remove .php extension with .htaccess

After changing the parameter AllowOverride from None to All in /etc/apache2/apache2.conf (Debian 8), following this, the .htaccess file just must contain:

Options +MultiViews
AddHandler php5-script php
AddType text/html php

And it was enough to hide .php extension from files

How to set delay in vbscript

Here is an update to the solution provided by @user235218 that allows you to specify number of milliseconds you require.

Note: The -n option is the number of retries and the -w is the timeout in milliseconds for ping. I chose the 127.255.255.254 address because it is in the loopback range and ms windows doesn’t respond to it.

I also doubt this will provide millisecond accuracy but on another note i tried it in an application using the ms script control and whilst the built in sleep function locked up the interface this method didn't.

If somebody can provide an explanation for why this method didn't lock up the interface we could make this answer more complete. Both sleep functions where run in the user thread.

Const WshHide = 0
Const WAIT_ON_RETURN = True

Sub Sleep(ByVal ms)

   Dim shell 'As WScript.Shell

   If Not IsNumeric(ms) Then _
       Exit Sub

   Set shell = CreateObject("WScript.Shell")

   Call shell.Run("%COMSPEC% /c ping -n 1 -w " & ms & " 127.255.255.254 > nul", WshHide, WAIT_ON_RETURN)

End Sub

How to use adb command to push a file on device without sd card

Certain versions of android do not fire proper tasks for updating the state of file system. You could trigger an explicit intent for updating the status of the file system. (I just tested after being in the same OP's situation)

adb shell am broadcast -a android.intent.action.MEDIA_MOUNTED -d file:///

(You could pass a specific filepath instead of file:/// like file:///sdcard )

Check if a JavaScript string is a URL

If you can change the input type, I think this solution would be much easier:

You can simple use type="url" in your input and the check it with checkValidity() in js

E.g:

your.html

<input id="foo" type="url">

your.js

// The selector is JQuery, but the function is plain JS
$("#foo").on("keyup", function() {
    if (this.checkValidity()) {
        // The url is valid
    } else {
        // The url is invalid
    }
});

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

Calling performSelector with an NSNumber or other NSValue will not work. Instead of using the value of the NSValue/NSNumber, it will effectively cast the pointer to an int, float, or whatever and use that.

But the solution is simple and obvious. Create the NSInvocation and call

[invocation performSelector:@selector(invoke) withObject:nil afterDelay:delay]

Unzipping files

If anyone's reading images or other binary files from a zip file hosted at a remote server, you can use following snippet to download and create zip object using the jszip library.

// this function just get the public url of zip file.
let url = await getStorageUrl(path) 
console.log('public url is', url)
//get the zip file to client
axios.get(url, { responseType: 'arraybuffer' }).then((res) => {
  console.log('zip download status ', res.status)
//load contents into jszip and create an object
  jszip.loadAsync(new Blob([res.data], { type: 'application/zip' })).then((zip) => {
    const zipObj = zip
    $.each(zip.files, function (index, zipEntry) {
    console.log('filename', zipEntry.name)
    })
  })

Now using the zipObj you can access the files and create a src url for it.

var fname = 'myImage.jpg'
zipObj.file(fname).async('blob').then((blob) => {
var blobUrl = URL.createObjectURL(blob)

Angular 5 Reactive Forms - Radio Button Group

IF you want to derive usg Boolean true False need to add "[]" around value

<form [formGroup]="form">
  <input type="radio" [value]=true formControlName="gender" >Male
  <input type="radio" [value]=false formControlName="gender">Female
</form>

A table name as a variable

For static queries, like the one in your question, table names and column names need to be static.

For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.

Here is an example of a script used to compare data between the same tables of different databases:

Static query:

SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]

Since I want to easily change the name of table and schema, I have created this dynamic query:

declare @schema varchar(50)
declare @table varchar(50)
declare @query nvarchar(500)

set @schema = 'dbo'
set @table = 'ACTY'

set @query = 'SELECT * FROM [DB_ONE].[' + @schema + '].[' + @table + '] EXCEPT SELECT * FROM [DB_TWO].[' + @schema + '].[' + @table + ']'

EXEC sp_executesql @query

Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL

How do I compile a Visual Studio project from the command-line?

To be honest I have to add my 2 cents.

You can do it with msbuild.exe. There are many version of the msbuild.exe.

C:\Windows\Microsoft.NET\Framework64\v2.0.50727\msbuild.exe C:\Windows\Microsoft.NET\Framework64\v3.5\msbuild.exe C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe
C:\Windows\Microsoft.NET\Framework\v2.0.50727\msbuild.exe C:\Windows\Microsoft.NET\Framework\v3.5\msbuild.exe C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe

Use version you need. Basically you have to use the last one.

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe

So how to do it.

  1. Run the COMMAND window

  2. Input the path to msbuild.exe

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe

  1. Input the path to the project solution like

"C:\Users\Clark.Kent\Documents\visual studio 2012\Projects\WpfApplication1\WpfApplication1.sln"

  1. Add any flags you need after the solution path.

  2. Press ENTER

Note you can get help about all possible flags like

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe /help

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

An other way of CASE:

SELECT *  
FROM MyTable
WHERE 1 = CASE WHEN @myParm = value1 AND MyColumn IS NULL     THEN 1 
               WHEN @myParm = value2 AND MyColumn IS NOT NULL THEN 1 
               WHEN @myParm = value3                          THEN 1 
          END

How to resolve Unneccessary Stubbing exception

For me neither the @Rule nor the @RunWith(MockitoJUnitRunner.Silent.class) suggestions worked. It was a legacy project where we upgraded to mockito-core 2.23.0.

We could get rid of the UnnecessaryStubbingException by using:

Mockito.lenient().when(mockedService.getUserById(any())).thenReturn(new User());

instead of:

when(mockedService.getUserById(any())).thenReturn(new User());

Needless to say that you should rather look at the test code, but we needed to get the stuff compiled and the tests running first of all ;)

In a bootstrap responsive page how to center a div

You don't need to change anything in CSS you can directly write this in class and you will get the result.

<div class="col-lg-4 col-md-4 col-sm-4 container justify-content-center">
  <div class="col" style="background:red">
    TEXT
  </div>
</div>

enter image description here

What is the difference between SQL, PL-SQL and T-SQL?

SQL is a standard and there are many database vendors like Microsoft,Oracle who implements this standard using their own proprietary language.

Microsoft uses T-SQL to implement SQL standard to interact with data whereas oracle uses PL/SQL.

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

Change hash without reload in jQuery

You could try catching the onload event. And stopping the propagation dependent on some flag.

var changeHash = false;

$('ul.questions li a').click(function(event) {
    var $this = $(this)
    $('.tab').hide();  //you can improve the speed of this selector.
    $($this.attr('href')).fadeIn('slow');
    StopEvent(event);  //notice I've changed this
    changeHash = true;
    window.location.hash = $this.attr('href');
});

$(window).onload(function(event){
    if (changeHash){
        changeHash = false;
        StopEvent(event);
    }
}

function StopEvent(event){
    event.preventDefault();
    event.stopPropagation();
    if ($.browser.msie) {
        event.originalEvent.keyCode = 0;
        event.originalEvent.cancelBubble = true;
        event.originalEvent.returnValue = false;
    }
}

Not tested, so can't say if it would work

Sort array by firstname (alphabetically) in Javascript

Pushed the top answers into a prototype to sort by key.

Array.prototype.alphaSortByKey= function (key) {
    this.sort(function (a, b) {
        if (a[key] < b[key])
            return -1;
        if (a[key] > b[key])
            return 1;
        return 0;
    });
    return this;
};

How display only years in input Bootstrap Datepicker?

For bootstrap 3 datepicker. (Note the capital letters)

$("#datetimepicker").datetimepicker( {
  format: "YYYY",
  viewMode: "years"
});

Why my $.ajax showing "preflight is invalid redirect error"?

I received the same error when I tried to call https web service as http webservice.

e.g when I call url 'http://api.example.com/users/get'
which should be 'https://api.example.com/users/get'

This error is produced because of redirection status 302 when you try to call http instead of https.

Regular Expression: Any character that is NOT a letter or number

This regular expression matches anything that isn't a letter, digit, or an underscore (_) character.

\W

For example in JavaScript:

"(,,@,£,() asdf 345345".replace(/\W/g, ' '); // Output: "          asdf 345345"

Using margin:auto to vertically-align a div

I think you can fix that with Flexbox

_x000D_
_x000D_
.black {
  height : 200px;
  width : 200px;
  background-color : teal;
  border: 5px solid rgb(0, 53, 53);
  /* This is the important part */
  display : flex;
  justify-content: center;
  align-items: center;
}

.message {
  background-color :  rgb(119, 128, 0);
  border: 5px solid rgb(0, 53, 53);
  height : 50%;
  width : 50%;
  padding : 5px;
}
_x000D_
<div class="black">
    <div class="message">
        This is a popup message.
    </div>
</div>
_x000D_
_x000D_
_x000D_

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

Personally I use small subset of Bootstrap functionality and don't need to attach Tether.

This should help:

window.Tether = function () {
  throw new Error('Your Bootstrap may actually need Tether.');
};

Why isn't .ico file defined when setting window's icon?

I recently ran into this problem and didn't find any of the answers very relevant so I decided to make a SO account for this.

Solution 1: Convert your .ico File online there are a lot of site out there

Solution 2: Convert .ico File in photoshop

If you or your Editor just renamed your image file to *.ico then it is not going to work.
If you see the image icon from your Windows/OS folder then it is working

What does 'git remote add upstream' help achieve?

Let's take an example: You want to contribute to django, so you fork its repository. In the while you work on your feature, there is much work done on the original repo by other people. So the code you forked is not the most up to date. setting a remote upstream and fetching it time to time makes sure your forked repo is in sync with the original repo.

How can I list all cookies for the current page with Javascript?

For just quickly viewing the cookies on any particular page, I keep a favorites-bar "Cookies" shortcut with the URL set to:

javascript:window.alert(document.cookie.split(';').join(';\r\n'));

In Javascript, how to conditionally add a member to an object?

Using spread syntax with boolean (as suggested here) is not valid syntax. Spread can only be use with iterables.

I suggest the following:

const a = {
   ...(someCondition? {b: 5}: {} )
}

Getting current directory in VBScript

Your line

Directory = CurrentDirectory\attribute.exe

does not match any feature I have encountered in a vbscript instruction manual. The following works for me, tho not sure what/where you expect "attribute.exe" to reside.

dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run curDir & "\testme.bat", 1
set WinScriptHost = nothing

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

I just fix this problem in my project-

CSS code

.scroll-menu{
   min-width: 220px;
   max-height: 90vh;
   overflow: auto;
 }

HTML code

<ul class="dropdown-menu scroll-menu" role="menu">
   <li><a href="#">Action</a></li>
   <li><a href="#">Another action</a></li>
   <li><a href="#">Something else here</a></li>
   <li><a href="#">Action</a></li>
   ..
   <li><a href="#">Action</a></li>
   <li><a href="#">Another action</a></li>
</ul>

Remove blank lines with grep

Here is another way of removing the white lines and lines starting with the # sign. I think this is quite useful to read configuration files.

[root@localhost ~]# cat /etc/sudoers | egrep -v '^(#|$)'
Defaults    requiretty
Defaults   !visiblepw
Defaults    always_set_home
Defaults    env_reset
Defaults    env_keep =  "COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR
LS_COLORS"
root    ALL=(ALL)       ALL
%wheel  ALL=(ALL)       ALL
stack ALL=(ALL) NOPASSWD: ALL

How to recursively list all the files in a directory in C#?

Short and simple solution

string dir = @"D:\PATH";

DateTime from_date = DateTime.Now.Date;
DateTime to_date = DateTime.Now.Date.AddHours(23);
var files = Directory.EnumerateFiles(dir, "*.*",SearchOption.AllDirectories).Select(i=>new FileInfo(i))
.Where(file=>file.LastWriteTime >= from_date && file.LastWriteTime <= to_date);
foreach(var fl in files)
    Console.WriteLine(fl.FullName);

How to fix Git error: object file is empty?

Actually I had the same problem. Have a copy of your code before trying this.

I just did git reset HEAD~

my last commit was undone then I commited it again, problem solved!

Image resizing client-side with JavaScript before upload to the server

Here's a gist which does this: https://gist.github.com/dcollien/312bce1270a5f511bf4a

(an es6 version, and a .js version which can be included in a script tag)

You can use it as follows:

<input type="file" id="select">
<img id="preview">
<script>
document.getElementById('select').onchange = function(evt) {
    ImageTools.resize(this.files[0], {
        width: 320, // maximum width
        height: 240 // maximum height
    }, function(blob, didItResize) {
        // didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
        document.getElementById('preview').src = window.URL.createObjectURL(blob);
        // you can also now upload this blob using an XHR.
    });
};
</script>

It includes a bunch of support detection and polyfills to make sure it works on as many browsers as I could manage.

(it also ignores gif images - in case they're animated)

Difference between subprocess.Popen and os.system

When running python (cpython) on windows the <built-in function system> os.system will execute under the curtains _wsystem while if you're using a non-windows os, it'll use system.

On contrary, Popen should use CreateProcess on windows and _posixsubprocess.fork_exec in posix-based operating-systems.

That said, an important piece of advice comes from os.system docs, which says:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

how to create a logfile in php?

Use below function

// Enable error reporting
ini_set('display_errors', 1);
//Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//error_reporting(E_ALL & ~E_NOTICE);
// Tell php where your custom php error log is
ini_set('error_log', 'php_error.log');

$dateTime=date("Y-m-d H:i:s");
$ip= $_SERVER['REMOTE_ADDR'];
$errorString="Error occured on time $dateTime by ip $ip";
$php_error_msg.=$errorString;
// Append the error message to the php-error log
//error_log($php_error_msg);
error_log("A custom error has been triggered",1,"email_address","From: email_address");

Above function will create a log in file php_error with proper description and email will be sent.

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

Restart intelliJ and import project as maven if it is a maven project

Spring - @Transactional - What happens in background?

All existing answers are correct, but I feel cannot give just this complex topic.

For a comprehensive, practical explanation you might want to have a look at this Spring @Transactional In-Depth guide, which tries its best to cover transaction management in ~4000 simple words, with a lot of code examples.

How to scroll to bottom in react?

Working Example:

You can use the DOM scrollIntoView method to make a component visible in the view.

For this, while rendering the component just give a reference ID for the DOM element using ref attribute. Then use the method scrollIntoView on componentDidMount life cycle. I am just putting a working sample code for this solution. The following is a component rendering each time a message received. You should write code/methods for rendering this component.

class ChatMessage extends Component {
    scrollToBottom = (ref) => {
        this.refs[ref].scrollIntoView({ behavior: "smooth" });
    }

    componentDidMount() {
        this.scrollToBottom(this.props.message.MessageId);
    }

    render() {
        return(
            <div ref={this.props.message.MessageId}>
                <div>Message content here...</div>
            </div>
        );
    }
}

Here this.props.message.MessageId is the unique ID of the particular chat message passed as props

Is there a way to use max-width and height for a background image?

As thirtydot said, you can use the CSS3 background-size syntax:

For example:

-o-background-size:35% auto;
-webkit-background-size:35% auto;
-moz-background-size:35% auto;
background-size:35% auto;

However, as also stated by thirtydot, this does not work in IE6, 7 and 8.

See the following links for more information about background-size: http://www.w3.org/TR/css3-background/#the-background-size

jQuery Ajax requests are getting cancelled without being sent

If anyone else runs into this, the issue we had was that we were making the ajax request from a link, and not preventing the link from being followed. So if you are doing this in an onclick attribute, make sure to return false; as well.

How to get a specific output iterating a hash in Ruby?

hash.each do |key, array|
  puts "#{key}-----"
  puts array
end

Regarding order I should add, that in 1.8 the items will be iterated in random order (well, actually in an order defined by Fixnum's hashing function), while in 1.9 it will be iterated in the order of the literal.

How to programmatically set style attribute in a view

For anyone looking for a Material answer see this SO post: Coloring Buttons in Android with Material Design and AppCompat

I used a combination of this answer to set the default text color of the button to white for my button: https://stackoverflow.com/a/32238489/3075340

Then this answer https://stackoverflow.com/a/34355919/3075340 to programmatically set the background color. The code for that is:

ViewCompat.setBackgroundTintList(your_colored_button,
 ContextCompat.getColorStateList(getContext(),R.color.your_custom_color));

your_colored_button can be just a regular Button or a AppCompat button if you wish - I tested the above code with both types of buttons and it works.

EDIT: I found that pre-lollipop devices do not work with the above code. See this post on how to add support for pre-lollipop devices: https://stackoverflow.com/a/30277424/3075340

Basically do this:

Button b = (Button) findViewById(R.id.button);
ColorStateList c = ContextCompat.getColorStateList(mContext, R.color.your_custom_color;
Drawable d = b.getBackground();
if (b instanceof AppCompatButton) {
    // appcompat button replaces tint of its drawable background
    ((AppCompatButton)b).setSupportBackgroundTintList(c);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    // Lollipop button replaces tint of its drawable background
    // however it is not equal to d.setTintList(c)
    b.setBackgroundTintList(c);
} else {
    // this should only happen if 
    // * manually creating a Button instead of AppCompatButton
    // * LayoutInflater did not translate a Button to AppCompatButton
    d = DrawableCompat.wrap(d);
    DrawableCompat.setTintList(d, c);
    b.setBackgroundDrawable(d);
}

SQL Server command line backup statement

Here's an example you can run as a batch script (copy-paste into a .bat file), using the SQLCMD utility in Sql Server client tools:

BACKUP:

echo off
cls
echo -- BACKUP DATABASE --
set /p DATABASENAME=Enter database name:

:: filename format Name-Date (eg MyDatabase-2009.5.19.bak)
set DATESTAMP=%DATE:~-4%.%DATE:~7,2%.%DATE:~4,2%
set BACKUPFILENAME=%CD%\%DATABASENAME%-%DATESTAMP%.bak
set SERVERNAME=your server name here
echo.

sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
pause

RESTORE:

echo off
cls
echo -- RESTORE DATABASE --
set /p BACKUPFILENAME=Enter backup file name:%CD%\
set /p DATABASENAME=Enter database name:
set SERVERNAME=your server name here
sqlcmd -E -S %SERVERNAME% -d master -Q "ALTER DATABASE [%DATABASENAME%] SET SINGLE_USER WITH ROLLBACK IMMEDIATE"

:: WARNING - delete the database, suits me
:: sqlcmd -E -S %SERVERNAME% -d master -Q "IF EXISTS (SELECT * FROM sysdatabases WHERE name=N'%DATABASENAME%' ) DROP DATABASE [%DATABASENAME%]"
:: sqlcmd -E -S %SERVERNAME% -d master -Q "CREATE DATABASE [%DATABASENAME%]"

:: restore
sqlcmd -E -S %SERVERNAME% -d master -Q "RESTORE DATABASE [%DATABASENAME%] FROM DISK = N'%CD%\%BACKUPFILENAME%' WITH REPLACE"

:: remap user/login (http://msdn.microsoft.com/en-us/library/ms174378.aspx)
sqlcmd -E -S %SERVERNAME% -d %DATABASENAME% -Q "sp_change_users_login 'Update_One', 'login-name', 'user-name'"
sqlcmd -E -S %SERVERNAME% -d master -Q "ALTER DATABASE [%DATABASENAME%] SET MULTI_USER"
echo.
pause

Multiple distinct pages in one HTML file

have all the pages in distinct div areas

<div style="" id="page1">
First Page Contents
</div>

<div style="display:none" id="page2">
Second Page Contents
</div>

then use a js script to workout what you are viewing (like within an hashtag style) to navigate. Either that, or ajax to get the response from a specific file (like /pages/page1.html)

var $prehashval = "";
function loop()
{
    if (location.hash.slice(1)!=$prehashval)
        hashChanged();

    $prehashval = location.hash.slice(1);
    setTimeout("loop()", 100);
}
function hashChanged()
{
    var $output;
    switch (location.hash.slice(1))
    {
        case "page1":
            document.getElementById('page1').style.display = "";
            document.getElementById('page2').style.display = "none";
            break;
        case "page2":
            document.getElementById('page1').style.display = "none";
            document.getElementById('page2').style.display = "";
            break;
        default:
            $output = location.hash.slice(1);
    }
}
loop();

LINQ to SQL - Left Outer Join with multiple join conditions

Can be written using composite join key. Also if there is need to select properties from both left and right sides the LINQ can be written as

var result = context.Periods
    .Where(p => p.companyid == 100)
    .GroupJoin(
        context.Facts,
        p => new {p.id, otherid = 17},
        f => new {id = f.periodid, f.otherid},
        (p, f) => new {p, f})
    .SelectMany(
        pf => pf.f.DefaultIfEmpty(),
        (pf, f) => new MyJoinEntity
        {
            Id = pf.p.id,
            Value = f.value,
            // and so on...
        });

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

(9.61 + "").replace('.',':')

Or if your 9.61 is already a string:

"9.61".replace('.',':')

Python: Checking if a 'Dictionary' is empty doesn't seem to work

use 'any'

dict = {}

if any(dict) :

     # true
     # dictionary is not empty 

else :

     # false 
     # dictionary is empty

Why are unnamed namespaces used and what are their benefits?

The example shows that the people in the project you joined don't understand anonymous namespaces :)

namespace {
    const int SIZE_OF_ARRAY_X;
    const int SIZE_OF_ARRAY_Y;

These don't need to be in an anonymous namespace, since const object already have static linkage and therefore can't possibly conflict with identifiers of the same name in another translation unit.

    bool getState(userType*,otherUserType*);
}

And this is actually a pessimisation: getState() has external linkage. It is usually better to prefer static linkage, as that doesn't pollute the symbol table. It is better to write

static bool getState(/*...*/);

here. I fell into the same trap (there's wording in the standard that suggest that file-statics are somehow deprecated in favour of anonymous namespaces), but working in a large C++ project like KDE, you get lots of people that turn your head the right way around again :)

Split string, convert ToList<int>() in one line

Joze's way also need LINQ, ToList() is in System.Linq namespace.

You can convert Array to List without Linq by passing the array to List constructor:

List<int> numbers = new List<int>( Array.ConvertAll(sNumbers.Split(','), int.Parse) );

Catching multiple exception types in one catch block

In PHP >= 7.1 this is possible. See this answer.


If you can modify the exceptions, use this answer.

If you can't, you could try catching all with Exception and then check which exception was thrown with instanceof.

try
{
    /* something */
}
catch( Exception $e )
{
    if ($e instanceof AError OR $e instanceof BError) {
       // It's either an A or B exception.
    } else {
        // Keep throwing it.
        throw $e;
    }
}

But it would probably be better to use multiple catch blocks as described in aforementioned answer.

try
{
    /* something */
}
catch( AError $e )
{
   handler1( $e );
}
catch ( BError $b )
{
   handler2( $e );
}

Force “landscape” orientation mode

It is now possible with the HTML5 webapp manifest. See below.


Original answer:

You can't lock a website or a web application in a specific orientation. It goes against the natural behaviour of the device.

You can detect the device orientation with CSS3 media queries like this:

@media screen and (orientation:portrait) {
    // CSS applied when the device is in portrait mode
}

@media screen and (orientation:landscape) {
    // CSS applied when the device is in landscape mode
}

Or by binding a JavaScript orientation change event like this:

document.addEventListener("orientationchange", function(event){
    switch(window.orientation) 
    {  
        case -90: case 90:
            /* Device is in landscape mode */
            break; 
        default:
            /* Device is in portrait mode */
    }
});

Update on November 12, 2014: It is now possible with the HTML5 webapp manifest.

As explained on html5rocks.com, you can now force the orientation mode using a manifest.json file.

You need to include those line into the json file:

{
    "display":      "standalone", /* Could be "fullscreen", "standalone", "minimal-ui", or "browser" */
    "orientation":  "landscape", /* Could be "landscape" or "portrait" */
    ...
}

And you need to include the manifest into your html file like this:

<link rel="manifest" href="manifest.json">

Not exactly sure what the support is on the webapp manifest for locking orientation mode, but Chrome is definitely there. Will update when I have the info.

Include another JSP file

For a reason I don't yet understand, after I used <%@include file="includes/footer.jsp" %> in my index.jsp then in the other jsp files like register.jsp I had to use <%@ include file="footer.jsp"%>. As you see there was no more need to use full path, STS had store my initial path.

Pytorch reshape tensor dimension

There are multiple ways of reshaping a PyTorch tensor. You can apply these methods on a tensor of any dimensionality.

Let's start with a 2-dimensional 2 x 3 tensor:

x = torch.Tensor(2, 3)
print(x.shape)
# torch.Size([2, 3])

To add some robustness to this problem, let's reshape the 2 x 3 tensor by adding a new dimension at the front and another dimension in the middle, producing a 1 x 2 x 1 x 3 tensor.

Approach 1: add dimension with None

Use NumPy-style insertion of None (aka np.newaxis) to add dimensions anywhere you want. See here.

print(x.shape)
# torch.Size([2, 3])

y = x[None, :, None, :] # Add new dimensions at positions 0 and 2.
print(y.shape)
# torch.Size([1, 2, 1, 3])

Approach 2: unsqueeze

Use torch.Tensor.unsqueeze(i) (a.k.a. torch.unsqueeze(tensor, i) or the in-place version unsqueeze_()) to add a new dimension at the i'th dimension. The returned tensor shares the same data as the original tensor. In this example, we can use unqueeze() twice to add the two new dimensions.

print(x.shape)
# torch.Size([2, 3])

# Use unsqueeze twice.
y = x.unsqueeze(0) # Add new dimension at position 0
print(y.shape)
# torch.Size([1, 2, 3])

y = y.unsqueeze(2) # Add new dimension at position 2
print(y.shape)
# torch.Size([1, 2, 1, 3])

In practice with PyTorch, adding an extra dimension for the batch may be important, so you may often see unsqueeze(0).

Approach 3: view

Use torch.Tensor.view(*shape) to specify all the dimensions. The returned tensor shares the same data as the original tensor.

print(x.shape)
# torch.Size([2, 3])

y = x.view(1, 2, 1, 3)
print(y.shape)
# torch.Size([1, 2, 1, 3])

Approach 4: reshape

Use torch.Tensor.reshape(*shape) (aka torch.reshape(tensor, shapetuple)) to specify all the dimensions. If the original data is contiguous and has the same stride, the returned tensor will be a view of input (sharing the same data), otherwise it will be a copy. This function is similar to the NumPy reshape() function in that it lets you define all the dimensions and can return either a view or a copy.

print(x.shape)
# torch.Size([2, 3])

y = x.reshape(1, 2, 1, 3)
print(y.shape)
# torch.Size([1, 2, 1, 3])

Furthermore, from the O'Reilly 2019 book Programming PyTorch for Deep Learning, the author writes:

Now you might wonder what the difference is between view() and reshape(). The answer is that view() operates as a view on the original tensor, so if the underlying data is changed, the view will change too (and vice versa). However, view() can throw errors if the required view is not contiguous; that is, it doesn’t share the same block of memory it would occupy if a new tensor of the required shape was created from scratch. If this happens, you have to call tensor.contiguous() before you can use view(). However, reshape() does all that behind the scenes, so in general, I recommend using reshape() rather than view().

Approach 5: resize_

Use the in-place function torch.Tensor.resize_(*sizes) to modify the original tensor. The documentation states:

WARNING. This is a low-level method. The storage is reinterpreted as C-contiguous, ignoring the current strides (unless the target size equals the current size, in which case the tensor is left unchanged). For most purposes, you will instead want to use view(), which checks for contiguity, or reshape(), which copies data if needed. To change the size in-place with custom strides, see set_().

print(x.shape)
# torch.Size([2, 3])

x.resize_(1, 2, 1, 3)
print(x.shape)
# torch.Size([1, 2, 1, 3])

My observations

If you want to add just one dimension (e.g. to add a 0th dimension for the batch), then use unsqueeze(0). If you want to totally change the dimensionality, use reshape().

See also:

What's the difference between reshape and view in pytorch?

What is the difference between view() and unsqueeze()?

In PyTorch 0.4, is it recommended to use reshape than view when it is possible?

Read a file line by line assigning the value to a variable

Using the following Bash template should allow you to read one value at a time from a file and process it.

while read name; do
    # Do what you want to $name
done < filename

Align nav-items to right side in bootstrap-4

Here and easy Example.

<!-- Navigation bar-->

<nav class="navbar navbar-toggleable-md bg-info navbar-inverse">
    <div class="container">
        <button class="navbar-toggler" data-toggle="collapse" data-target="#mainMenu">
            <span class="navbar-toggler-icon"></span>
            </button>
        <div class="collapse navbar-collapse" id="mainMenu">
            <div class="navbar-nav ml-auto " style="width:100%">
                <a class="nav-item nav-link active" href="#">Home</a>
                <a class="nav-item nav-link" href="#">About</a>
                <a class="nav-item nav-link" href="#">Training</a>
                <a class="nav-item nav-link" href="#">Contact</a>
            </div>
        </div>
    </div>
</nav>

How to install PyQt4 on Windows using pip?

Earlier PyQt .exe installers were available directly from the website download page. Now with the release of PyQt4.12 , installers have been deprecated. You can make the libraries work somehow by compiling them but that would mean going to great lengths of trouble.

Otherwise you can use the previous distributions to solve your purpose. The .exe windows installers can be downloaded from :

https://sourceforge.net/projects/pyqt/files/PyQt4/PyQt-4.11.4/

fatal error: iostream.h no such file or directory

Using standard C++ calling (note that you should use namespace std for cout or add using namespace std;)

#include <iostream>

int main()
{
    std::cout<<"Hello World!\n";
    return 0;
}

Add views in UIStackView programmatically

UIStackView uses constraints internally to position its arranged subviews. Exactly what constraints are created depends on how the stack view itself is configured. By default, a stack view will create constraints that lay out its arranged subviews in a horizontal line, pinning the leading and trailing views to its own leading and trailing edges. So your code would produce a layout that looks like this:

|[view1][view2]|

The space that is allocated to each subview is determined by a number of factors including the subview's intrinsic content size and it's compression resistance and content hugging priorities. By default, UIView instances don't define an intrinsic content size. This is something that is generally provided by a subclass, such as UILabel or UIButton.

Since the content compression resistance and content hugging priorities of two new UIView instances will be the same, and neither view provides an intrinsic content size, the layout engine must make its best guess as to what size should be allocated to each view. In your case, it is assigning the first view 100% of the available space, and nothing to the second view.

If you modify your code to use UILabel instances instead, you will get better results:

UILabel *label1 = [UILabel new];
label1.text = @"Label 1";
label1.backgroundColor = [UIColor blueColor];

UILabel *label2 = [UILabel new];
label2.text = @"Label 2";
label2.backgroundColor = [UIColor greenColor];

[self.stack1 addArrangedSubview:label1];
[self.stack1 addArrangedSubview:label2];

Note that it is not necessary to explictly create any constraints yourself. This is the main benefit of using UIStackView - it hides the (often ugly) details of constraint management from the developer.

Verify ImageMagick installation

Try this:

<?php
//This function prints a text array as an html list.
function alist ($array) {  
  $alist = "<ul>";
  for ($i = 0; $i < sizeof($array); $i++) {
    $alist .= "<li>$array[$i]";
  }
  $alist .= "</ul>";
  return $alist;
}
//Try to get ImageMagick "convert" program version number.
exec("convert -version", $out, $rcode);
//Print the return code: 0 if OK, nonzero if error. 
echo "Version return code is $rcode <br>"; 
//Print the output of "convert -version"    
echo alist($out); 
?>

Cannot find name 'require' after upgrading to Angular4

As for me, using VSCode and Angular 5, only had to add "node" to types in tsconfig.app.json. Save, and restart the server.

_x000D_
_x000D_
{_x000D_
    "compilerOptions": {_x000D_
    .._x000D_
    "types": [_x000D_
      "node"_x000D_
    ]_x000D_
  }_x000D_
  .._x000D_
}
_x000D_
_x000D_
_x000D_

One curious thing, is that this problem "cannot find require (", does not happen when excuting with ts-node

List all virtualenv

If you came here from Google, trying to find where your previously created virtualenv installation ended up, and why there is no command to find it, here's the low-down.

The design of virtualenv has a fundamental flaw of not being able to keep track of it's own created environments. Someone was not quite in their right mind when they created virtualenv without having a rudimentary way to keep track of already created environments, and certainly not fit for a time and age when most pip requirements require multi-giga-byte installations, which should certainly not go into some obscure .virtualenvs sub-directory of your ~/home.

IMO, the created virtualenv directory should be created in $CWD and a file called ~/.virtualenv (in home) should keep track of the name and path of that creation. Which is a darn good reason to use Conda/Miniconda3 instead, which does seem to keep good track of this.

As answered here, the only way to keep track of this, is to install yet another package called virtualenvwrapper. If you don't do that, you will have to search for the created directory by yourself. Clearly, if you don't remember the name or the location it was created with/at, you will most likely never find your virtual environment again...

One try to remedy the situation in windows, is by putting the following functions into your powershell profile:

# wrap virtualenv.exe and write last argument (presumably 
# your virtualenv name) to the file: $HOME/.virtualenv.
function ven { if( $args.count -eq 0) {Get-Content ~/.virtualenv } else {virtualenv.exe "$args"; Write-Output ("{0} `t{1}" -f $args[-1],$PWD) | Out-File -Append $HOME/.virtualenv }}

# List what's in the file or the directories under ~/.virtualenvs
function lsven { try {Get-Content ~/.virtualenv } catch {Get-ChildItem ~\.virtualenvs -Directory | Select-Object -Property Name } }

WARNING: This will write to ~\.virtualenv...

Magento - How to add/remove links on my account navigation?

You can also disable the menu items through the backend, without having to touch any code. Go into:

System > Configuration > Advanced

You'll be presented with a long list of options. Here are some of the key modules to set to 'Disabled' :

Mage_Downloadable -> My Downloadable Products
Mage_Newsletter -> My Newsletter
Mage_Review -> My Reviews
Mage_Tag -> My Tags
Mage_Wishlist -> My Wishlist

I also disabled Mage_Poll, as it has a tendency to show up in other page templates and can be annoying if you're not using it.

How do I escape spaces in path for scp copy in Linux?

I had huge difficulty getting this to work for a shell variable containing a filename with whitespace. For some reason using:

file="foo bar/baz"
scp [email protected]:"'$file'"

as in @Adrian's answer seems to fail.

Turns out that what works best is using a parameter expansion to prepend backslashes to the whitespace as follows:

file="foo bar/baz"
file=${file// /\\ }
scp [email protected]:"$file"

HTML Button Close Window

Closing a window that was opened by the user through JavaScript is considered to be a security risk, thus not all browsers will allow this (which is why all solutions are hacks/workarounds). Browsers that are steadily maintained remove these types of hacks, and solutions that work one day may be broken the next.

This was addressed here by rvighne in a similar question on the subject.

What size should TabBar images be?

According to the Apple Human Interface Guidelines:

@1x : about 25 x 25 (max: 48 x 32)

@2x : about 50 x 50 (max: 96 x 64)

@3x : about 75 x 75 (max: 144 x 96)

Determine if Python is running inside virtualenv

Easiest way is to just run: which python, if you are in a virtualenv it will point to its python instead of the global one

php static function

After trying examples (PHP 5.3.5), I found that in both cases of defining functions you can't use $this operator to work on class functions. So I couldn't find a difference in them yet. :(

Which are more performant, CTE or temporary tables?

This is a really open ended question, and it all depends on how its being used and the type of temp table (Table variable or traditional table).

A traditional temp table stores the data in the temp DB, which does slow down the temp tables; however table variables do not.

HTML: Select multiple as dropdown

Here is the documentation of <select>. You are using 2 attributes:

multiple
This Boolean attribute indicates that multiple options can be selected in the list. If it is not specified, then only one option can be selected at a time. When multiple is specified, most browsers will show a scrolling list box instead of a single line dropdown.

size
If the control is presented as a scrolling list box (e.g. when multiple is specified), this attribute represents the number of rows in the list that should be visible at one time. Browsers are not required to present a select element as a scrolled list box. The default value is 0.

As described in the docs. <select size="1" multiple> will render a List box only 1 line visible and a scrollbar. So you are loosing the dropdown/arrow with the multiple attribute.

How to set default values for Angular 2 component properties?

That is interesting subject. You can play around with two lifecycle hooks to figure out how it works: ngOnChanges and ngOnInit.

Basically when you set default value to Input that's mean it will be used only in case there will be no value coming on that component. And the interesting part it will be changed before component will be initialized.

Let's say we have such components with two lifecycle hooks and one property coming from input.

@Component({
  selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
  @Input() property: string = 'default';

  ngOnChanges(changes) {
    console.log('Changed', changes.property.currentValue, changes.property.previousValue);
  }

  ngOnInit() {
    console.log('Init', this.property);
  }

}

Situation 1

Component included in html without defined property value

As result we will see in console: Init default

That's mean onChange was not triggered. Init was triggered and property value is default as expected.

Situation 2

Component included in html with setted property <cmp [property]="'new value'"></cmp>

As result we will see in console:

Changed new value Object {}

Init new value

And this one is interesting. Firstly was triggered onChange hook, which setted property to new value, and previous value was empty object! And only after that onInit hook was triggered with new value of property.

Plotting using a CSV file

You can also plot to a png file using gnuplot (which is free):

terminal commands

gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'

note: you always need to give the right extension (.png here) at set output

Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:

plot '<Fromfile.csv>' with line lt -1 lw 2

More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html

  • gnuplot is available in most linux distros via the package manager (e.g. on an apt based distro, run apt-get install gnuplot)
  • gnuplot is available in windows via Cygwin
  • gnuplot is available on macOS via homebrew (run brew install gnuplot)

Split string with JavaScript

var wrapper = $(document.body);

strings = [
    "19 51 2.108997",
    "20 47 2.1089"
];

$.each(strings, function(key, value) {
    var tmp = value.split(" ");
    $.each([
        tmp[0] + " " + tmp[1],
        tmp[2]
    ], function(key, value) {
        $("<span>" + value + "</span>").appendTo(wrapper);
    }); 
});

Is it possible to have placeholders in strings.xml for runtime values?

in res/values/string.xml

<resources>
    <string name="app_name">Hello World</string>
    <string name="my_application">Application name: %s, package name: %s</string>
</resources>

in java code

String[] args = new String[2];
args[0] = context.getString(R.string.app_name);
args[1] = context.getPackageName();
String textMessage = context.getString(R.string.my_application,(Object[]) args);

Accessing post variables using Java Servlets

Here's a simple example. I didn't get fancy with the html or the servlet, but you should get the idea.

I hope this helps you out.

<html>
<body>
<form method="post" action="/myServlet">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
</form>
</body>
</html>

Now for the Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {
  public void doPost(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {

    String userName = request.getParameter("username");
    String password = request.getParameter("password");
    ....
    ....
  }
}

Converting a double to an int in C#

ToInt32 rounds. Casting to int just throws away the non-integer component.

phpMyAdmin - Error > Incorrect format parameter?

If you use docker-compose just set UPLOAD_LIMIT

phpmyadmin:
    image: phpmyadmin/phpmyadmin
    environment:
        UPLOAD_LIMIT: 1G

Calculating number of full months between two dates in SQL

select CAST(DATEDIFF(MONTH, StartDate, EndDate) AS float) -
  (DATEPART(dd,StartDate) - 1.0) / DATEDIFF(DAY, StartDate, DATEADD(MONTH, 1, StartDate)) +
  (DATEPART(dd,EndDate)*1.0 ) / DATEDIFF(DAY, EndDate, DATEADD(MONTH, 1, EndDate))

error: member access into incomplete type : forward declaration of

You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

class B;

class A
{
    B* b;

    void doSomething();
};

class B
{
    A* a;

    void add() {}
};

void A::doSomething()
{
    b->add();
}

What does value & 0xff do in Java?

In 32 bit format system the hexadecimal value 0xff represents 00000000000000000000000011111111 that is 255(15*16^1+15*16^0) in decimal. and the bitwise & operator masks the same 8 right most bits as in first operand.

Has anyone gotten HTML emails working with Twitter Bootstrap?

The best approach I've come up with is to use Sass imports on a selected basis to pull in your bootstrap (or any other) styles into emails as might be needed.

First, create a new scss parent file something like email.scss for your email style. This could look like this:

    // Core variables and mixins
    @import "css/main/ezdia-variables";

    @import "css/bootstrap/mixins";
    @import "css/main/ezdia-mixins";

    // Import base classes
    @import "css/bootstrap/scaffolding";
    @import "css/bootstrap/type";
    @import "css/bootstrap/buttons";
    @import "css/bootstrap/alerts";

    // nest conflicting bootstrap styles
    .bootstrap-style {
        //use single quotes for nested imports
        @import 'css/bootstrap/normalize';
        @import 'css/bootstrap/tables';
    }

    @import "css/main/main";

    // Main email classes
    @import "css/email/zurb";
    @import "css/email/main";

Then in your email templates, only reference your compiled email.css file, which only contains the selected bootstrap styles referenced and nested properly in your email.scss.

For example, certain bootstrap styles will conflict with Zurb's responsive table style. To fix that, you can nest bootstrap's styles within a parent class or other selector in order to call bootstrap's table styles only when needed.

This way, you have the flexibility to pull in classes only when needed. You'll see that I use http://zurb.com/ which is a great responsive email library to use. See also http://zurb.com/ink/

Lastly, use a premailer like https://github.com/fphilipe/premailer-rails3 mentioned above to process the style into inline css, compiling inline styles to only what is used in that particular email template. For instance, for premailer, your ruby file could look something like this to compile an email into inline style.

    require 'rubygems' # optional for Ruby 1.9 or above.
    require 'premailer'

    premailer = Premailer.new('http://www.yourdomain.com/TestSnap/view/emailTemplates/DeliveryReport.jsp', :warn_level => Premailer::Warnings::SAFE)

    # Write the HTML output
    File.open("delivery_report.html", "w") do |fout|
      fout.puts premailer.to_inline_css
    end

    # Write the plain-text output
    File.open("output.txt", "w") do |fout|
      fout.puts premailer.to_plain_text
    end

    # Output any CSS warnings
    premailer.warnings.each do |w|
      puts "#{w[:message]} (#{w[:level]}) may not render properly in #{w[:clients]}"
    end

Hope this helps! Been struggling to find a flexible email templating framework across Pardot, Salesforce, and our product's built-in auto-response and daily emails.

What is @RenderSection in asp.net MVC

If

(1) you have a _Layout.cshtml view like this

<html>
    <body>
        @RenderBody()

    </body>
    <script type="text/javascript" src="~/lib/layout.js"></script>
    @RenderSection("scripts", required: false)
</html>

(2) you have Contacts.cshtml

@section Scripts{
    <script type="text/javascript" src="~/lib/contacts.js"></script>

}
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>    Contacts</h2>
    </div>
</div>

(3) you have About.cshtml

<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>    Contacts</h2>
    </div>
</div>

On you layout page, if required is set to false "@RenderSection("scripts", required: false)", When page renders and user is on about page, the contacts.js doesn't render.

    <html>
        <body><div>About<div>             
        </body>
        <script type="text/javascript" src="~/lib/layout.js"></script>
    </html>

if required is set to true "@RenderSection("scripts", required: true)", When page renders and user is on ABOUT page, the contacts.js STILL gets rendered.

<html>
    <body><div>About<div>             
    </body>
    <script type="text/javascript" src="~/lib/layout.js"></script>
    <script type="text/javascript" src="~/lib/contacts.js"></script>
</html>

IN SHORT, when set to true, whether you need it or not on other pages, it will get rendered anyhow. If set to false, it will render only when the child page is rendered.

The developers of this app have not set up this app properly for Facebook Login?

This is because you didn't make your Facebook app live. For this go to:

Facebook developer page->Select your app->you will see top of the right your live option is disable and click to enable it->It will refer to you in "basic setting section"->You have to add "privacy policy url" and "Terms and services url" also you may select app category->then save the setting.

Note: You can use any blogspot or website to make your privacy policy also terms and condition page.Both I gave same url which worked.

Toggle button for Facebook app live

How do you clear a slice in Go?

Setting the slice to nil is the best way to clear a slice. nil slices in go are perfectly well behaved and setting the slice to nil will release the underlying memory to the garbage collector.

See playground

package main

import (
    "fmt"
)

func dump(letters []string) {
    fmt.Println("letters = ", letters)
    fmt.Println(cap(letters))
    fmt.Println(len(letters))
    for i := range letters {
        fmt.Println(i, letters[i])
    }
}

func main() {
    letters := []string{"a", "b", "c", "d"}
    dump(letters)
    // clear the slice
    letters = nil
    dump(letters)
    // add stuff back to it
    letters = append(letters, "e")
    dump(letters)
}

Prints

letters =  [a b c d]
4
4
0 a
1 b
2 c
3 d
letters =  []
0
0
letters =  [e]
1
1
0 e

Note that slices can easily be aliased so that two slices point to the same underlying memory. The setting to nil will remove that aliasing.

This method changes the capacity to zero though.

Combining "LIKE" and "IN" for SQL Server

I know this is old but I got a kind of working solution

SELECT Tbla.* FROM Tbla
INNER JOIN Tblb ON
Tblb.col1 Like '%'+Tbla.Col2+'%'

You can expand it further with your where clause etc. I only answered this because this is what I was looking for and I had to figure out a way of doing it.

How to detect a loop in a linked list?

public boolean isCircular() {

    if (head == null)
        return false;

    Node temp1 = head;
    Node temp2 = head;

    try {
        while (temp2.next != null) {

            temp2 = temp2.next.next.next;
            temp1 = temp1.next;

            if (temp1 == temp2 || temp1 == temp2.next) 
                return true;    

        }
    } catch (NullPointerException ex) {
        return false;

    }

    return false;

}

document.getelementbyId will return null if element is not defined?

Yes it will return null if it's not present you can try this below in the demo. Both will return true. The first elements exists the second doesn't.

Demo

Html

<div id="xx"></div>

Javascript:

   if (document.getElementById('xx') !=null) 
     console.log('it exists!');

   if (document.getElementById('xxThisisNotAnElementOnThePage') ==null) 
     console.log('does not exist!');

Changing CSS Values with Javascript

I don't know why the other solutions go through the whole list of stylesheets for the document. Doing so creates a new entry in each stylesheet, which is inefficient. Instead, we can simply append a new stylesheet and simply add our desired CSS rules there.

style=document.createElement('style');
document.head.appendChild(style);
stylesheet=style.sheet;
function css(selector,property,value)
{
    try{ stylesheet.insertRule(selector+' {'+property+':'+value+'}',stylesheet.cssRules.length); }
    catch(err){}
}

Note that we can override even inline styles set directly on elements by adding " !important" to the value of the property, unless there already exist more specific "!important" style declarations for that property.

VB.NET Switch Statement GoTo Case

Why don't you just refactor the default case as a method and call it from both places? This should be more readable and will allow you to change the code later in a more efficient manner.

A simple explanation of Naive Bayes Classification

Ram Narasimhan explained the concept very nicely here below is an alternative explanation through the code example of Naive Bayes in action
It uses an example problem from this book on page 351
This is the data set that we will be using
enter image description here
In the above dataset if we give the hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'} then what is the probability that he will buy or will not buy a computer.
The code below exactly answers that question.
Just create a file called named new_dataset.csv and paste the following content.

Age,Income,Student,Creadit_Rating,Buys_Computer
<=30,high,no,fair,no
<=30,high,no,excellent,no
31-40,high,no,fair,yes
>40,medium,no,fair,yes
>40,low,yes,fair,yes
>40,low,yes,excellent,no
31-40,low,yes,excellent,yes
<=30,medium,no,fair,no
<=30,low,yes,fair,yes
>40,medium,yes,fair,yes
<=30,medium,yes,excellent,yes
31-40,medium,no,excellent,yes
31-40,high,yes,fair,yes
>40,medium,no,excellent,no

Here is the code the comments explains everything we are doing here! [python]

import pandas as pd 
import pprint 

class Classifier():
    data = None
    class_attr = None
    priori = {}
    cp = {}
    hypothesis = None


    def __init__(self,filename=None, class_attr=None ):
        self.data = pd.read_csv(filename, sep=',', header =(0))
        self.class_attr = class_attr

    '''
        probability(class) =    How many  times it appears in cloumn
                             __________________________________________
                                  count of all class attribute
    '''
    def calculate_priori(self):
        class_values = list(set(self.data[self.class_attr]))
        class_data =  list(self.data[self.class_attr])
        for i in class_values:
            self.priori[i]  = class_data.count(i)/float(len(class_data))
        print "Priori Values: ", self.priori

    '''
        Here we calculate the individual probabilites 
        P(outcome|evidence) =   P(Likelihood of Evidence) x Prior prob of outcome
                               ___________________________________________
                                                    P(Evidence)
    '''
    def get_cp(self, attr, attr_type, class_value):
        data_attr = list(self.data[attr])
        class_data = list(self.data[self.class_attr])
        total =1
        for i in range(0, len(data_attr)):
            if class_data[i] == class_value and data_attr[i] == attr_type:
                total+=1
        return total/float(class_data.count(class_value))

    '''
        Here we calculate Likelihood of Evidence and multiple all individual probabilities with priori
        (Outcome|Multiple Evidence) = P(Evidence1|Outcome) x P(Evidence2|outcome) x ... x P(EvidenceN|outcome) x P(Outcome)
        scaled by P(Multiple Evidence)
    '''
    def calculate_conditional_probabilities(self, hypothesis):
        for i in self.priori:
            self.cp[i] = {}
            for j in hypothesis:
                self.cp[i].update({ hypothesis[j]: self.get_cp(j, hypothesis[j], i)})
        print "\nCalculated Conditional Probabilities: \n"
        pprint.pprint(self.cp)

    def classify(self):
        print "Result: "
        for i in self.cp:
            print i, " ==> ", reduce(lambda x, y: x*y, self.cp[i].values())*self.priori[i]

if __name__ == "__main__":
    c = Classifier(filename="new_dataset.csv", class_attr="Buys_Computer" )
    c.calculate_priori()
    c.hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}

    c.calculate_conditional_probabilities(c.hypothesis)
    c.classify()

output:

Priori Values:  {'yes': 0.6428571428571429, 'no': 0.35714285714285715}

Calculated Conditional Probabilities: 

{
 'no': {
        '<=30': 0.8,
        'fair': 0.6, 
        'medium': 0.6, 
        'yes': 0.4
        },
'yes': {
        '<=30': 0.3333333333333333,
        'fair': 0.7777777777777778,
        'medium': 0.5555555555555556,
        'yes': 0.7777777777777778
      }
}

Result: 
yes  ==>  0.0720164609053
no  ==>  0.0411428571429

Hope it helps in better understanding the problem

peace

How to resolve TypeError: Cannot convert undefined or null to object

Below snippet is sufficient to understand how I encountered the same issue but in a different scenario and how I solved it using the guidance in the accepted answer. In my case I was trying to log the keys of object present in the 0th index of the 'defaultViewData' array using Object.keys() method.

defaultViewData = [{"name": "DEFAULT_VIEW_PLP","value": {"MSH25": "LIST"}}] 

console.log('DEFAULT_VIEW', Object.keys(this.props.defaultViewData[0]));

The console.log was not getting printed and I was getting the same error as posted in this question. To prevent that error I added below condition

    if(this.props.defaultViewData[0]) {
  console.log('DEFAULT_VIEW', Object.keys(this.props.defaultViewData[0]));
}

Adding this check ensured that I didn't get this error. I hope this helps for someone.

Note: This is React.js code. (although to understand the problem it doesn't matter).

How to include js and CSS in JSP with spring MVC

You should put the folder containing css and js files into "webapp/resources". If you've put them in "src/main/java", you must change it. It worked for me.

How to loop through elements of forms with JavaScript?

You can use getElementsByTagName function, it returns a HTMLCollection of elements with the given tag name.

var elements = document.getElementsByTagName("input")
for (var i = 0; i < elements.length; i++) {
    if(elements[i].value == "") {
        alert('empty');
        //Do something here
    }
}

DEMO

You can also use document.myform.getElementsByTagName provided you have given a name to yoy form

DEMO with form Name

MySQL - Get row number on select

SELECT @rn:=@rn+1 AS rank, itemID, ordercount
FROM (
  SELECT itemID, COUNT(*) AS ordercount
  FROM orders
  GROUP BY itemID
  ORDER BY ordercount DESC
) t1, (SELECT @rn:=0) t2;

Set the location in iPhone Simulator

Better late than never :)

I just came across this iSimulate which allows you to send Fake location to the app. The solution is NOT free.

> Q: How does iSimulate work? 

> A: When added to your project, the iSimulate
> SDK library creates a listening server
> on your iPhone Simulator that waits
> for a connection from an iPhone/iPod
> running the iSimulate client. When
> such connection is established, the
> iSimulate client running on your
> iPhone/iPod captures all data from the
> accelerometer sensor, the touch
> events, the location and device ID and
> streams them to the server. The
> iSimulate SDK library then recreates
> all input events synthetically. This
> is entirely transparent to your
> application and does not interfere
> with your application's functionality.

Anyway, i am planning to get this. will update more soon!

Optimal way to concatenate/aggregate strings

For those of us who found this and are not using Azure SQL Database:

STRING_AGG() in PostgreSQL, SQL Server 2017 and Azure SQL
https://www.postgresql.org/docs/current/static/functions-aggregate.html
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql

GROUP_CONCAT() in MySQL
http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat

(Thanks to @Brianjorden and @milanio for Azure update)

Example Code:

select Id
, STRING_AGG(Name, ', ') Names 
from Demo
group by Id

SQL Fiddle: http://sqlfiddle.com/#!18/89251/1

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Tools > Manage Add-ons, right click "Name" header and enable the "In Folder" section. go to the directory for the plugin you're interested in. Right click the plugin file, and click "remove".

Sleep function in ORACLE

Short of granting access to DBMS_LOCK.sleep, this will work but it's a horrible hack:

IN_TIME INT; --num seconds
v_now DATE;

-- 1) Get the date & time 
SELECT SYSDATE 
  INTO v_now
  FROM DUAL;

-- 2) Loop until the original timestamp plus the amount of seconds <= current date
LOOP
  EXIT WHEN v_now + (IN_TIME * (1/86400)) <= SYSDATE;
END LOOP;

How to trim white spaces of array values in php

function trimArray(&$value) 
{ 
    $value = trim($value); 
}
$pmcArray = array('php ','mysql ', ' code ');
array_walk($pmcArray, 'trimArray');

by using array_walk function, we can remove space from array elements and elements return the result in same array.

is there a css hack for safari only NOT chrome?

Sarari Only

.yourClass:not(:root:root){ 
    /* ^_^ */ 
}

error: use of deleted function

gcc 4.6 supports a new feature of deleted functions, where you can write

hdealt() = delete;

to disable the default constructor.

Here the compiler has obviously seen that a default constructor can not be generated, and =delete'd it for you.

How to add directory to classpath in an application run profile in IntelliJ IDEA?

Simply check that the directory/package of the class is marked as "Sources Root". I believe the package should be application or execution in your case.

To do so, right click on the package, and select Mark Directory As->Sources Root.

1

Check if table exists

DatabaseMetaData dbm = con.getMetaData();
// check if "employee" table is there
ResultSet tables = dbm.getTables(null, null, "employee", null);
if (tables.next()) {
  // Table exists
}
else {
  // Table does not exist
}

Getting list of pixel values from PIL

Looks like PILlow may have changed tostring() to tobytes(). When trying to extract RGBA pixels to get them into an OpenGL texture, the following worked for me (within the glTexImage2D call which I omit for brevity).

from PIL import Image
img = Image.open("mandrill.png").rotate(180).transpose(Image.FLIP_LEFT_RIGHT)

# use img.convert("RGBA").tobytes() as texels

C# binary literals

Update

C# 7.0 now has binary literals, which is awesome.

[Flags]
enum Days
{
    None = 0,
    Sunday    = 0b0000001,
    Monday    = 0b0000010,   // 2
    Tuesday   = 0b0000100,   // 4
    Wednesday = 0b0001000,   // 8
    Thursday  = 0b0010000,   // 16
    Friday    = 0b0100000,   // etc.
    Saturday  = 0b1000000,
    Weekend = Saturday | Sunday,
    Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}

Original Post

Since the topic seems to have turned to declaring bit-based flag values in enums, I thought it would be worth pointing out a handy trick for this sort of thing. The left-shift operator (<<) will allow you to push a bit to a specific binary position. Combine that with the ability to declare enum values in terms of other values in the same class, and you have a very easy-to-read declarative syntax for bit flag enums.

[Flags]
enum Days
{
    None        = 0,
    Sunday      = 1,
    Monday      = 1 << 1,   // 2
    Tuesday     = 1 << 2,   // 4
    Wednesday   = 1 << 3,   // 8
    Thursday    = 1 << 4,   // 16
    Friday      = 1 << 5,   // etc.
    Saturday    = 1 << 6,
    Weekend     = Saturday | Sunday,
    Weekdays    = Monday | Tuesday | Wednesday | Thursday | Friday
}

How can I add a new column and data to a datatable that already contains data?

Try this

> dt.columns.Add("ColumnName", typeof(Give the type you want));
> dt.Rows[give the row no like  or  or any no]["Column name in which you want to add data"] = Value;

Rules for C++ string literals escape character

I left something like this as a comment, but I feel it probably needs more visibility as none of the answers mention this method:

The method I now prefer for initializing a std::string with non-printing characters in general (and embedded null characters in particular) is to use the C++11 feature of initializer lists.

std::string const str({'\0', '6', '\a', 'H', '\t'});

I am not required to perform error-prone manual counting of the number of characters that I am using, so that if later on I want to insert a '\013' in the middle somewhere, I can and all of my code will still work. It also completely sidesteps any issues of using the wrong escape sequence by accident.

The only downside is all of those extra ' and , characters.

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],