Programs & Examples On #Lock free

Best Practice to Use HttpClient in Multithreaded Environment

I think you will want to use ThreadSafeClientConnManager.

You can see how it works here: http://foo.jasonhudgins.com/2009/08/http-connection-reuse-in-android.html

Or in the AndroidHttpClient which uses it internally.

How to edit my Excel dropdown list?

The answers above will work for changing the values.

If you want to change the number of cells in your list (e.g. I have a list called 'revisions' which has 4 items, I now need 7 items) you will find that you can't simply select your list and amend it on the sheet, So:

go to your 'Formulas' tab

choose "Name Manager"

a pop up box will show what is available for editing. Your list should be in it. Select your list and edit the range.

How to find server name of SQL Server Management Studio

Make sure you have installed SQL Server.

If not, follow this link and download. https://www.microsoft.com/en-us/sql-server/sql-server-downloads

Once SQL server is installed successfully. You will get server name. Refer to the below picture:

enter image description here

what is reverse() in Django

reverse() | Django documentation


Let's suppose that in your urls.py you have defined this:

url(r'^foo$', some_view, name='url_name'),

In a template you can then refer to this url as:

<!-- django <= 1.4 -->
<a href="{% url url_name %}">link which calls some_view</a>

<!-- django >= 1.5 or with {% load url from future %} in your template -->
<a href="{% url 'url_name' %}">link which calls some_view</a>

This will be rendered as:

<a href="/foo/">link which calls some_view</a>

Now say you want to do something similar in your views.py - e.g. you are handling some other url (not /foo/) in some other view (not some_view) and you want to redirect the user to /foo/ (often the case on successful form submission).

You could just do:

return HttpResponseRedirect('/foo/')

But what if you want to change the url in future? You'd have to update your urls.py and all references to it in your code. This violates DRY (Don't Repeat Yourself), the whole idea of editing one place only, which is something to strive for.

Instead, you can say:

from django.urls import reverse
return HttpResponseRedirect(reverse('url_name'))

This looks through all urls defined in your project for the url defined with the name url_name and returns the actual url /foo/.

This means that you refer to the url only by its name attribute - if you want to change the url itself or the view it refers to you can do this by editing one place only - urls.py.

HttpRequest maximum allowable size in tomcat?

Just to add to the answers, App Server Apache Geronimo 3.0 uses Tomcat 7 as the web server, and in that environment the file server.xml is located at <%GERONIMO_HOME%>/var/catalina/server.xml.

The configuration does take effect even when the Geronimo Console at Application Server->WebServer->TomcatWebConnector->maxPostSize still displays 2097152 (the default value)

pandas how to check dtype for all columns in a dataframe?

To go one step further, I assume you want to do something with these dtypes. df.dtypes.to_dict() comes in handy.

my_type = 'float64' #<---

dtypes = dataframe.dtypes.to_dict()

for col_nam, typ in dtypes.items():
    if (typ != my_type): #<---
        raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")

You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype will succeed when .dtype==np.float64.

Disabling SSL Certificate Validation in Spring RestTemplate

Add my response with cookie :

public static void main(String[] args) {
     MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
     params.add("username", testUser);
     params.add("password", testPass);
     NullHostnameVerifier verifier = new NullHostnameVerifier(); 
     MySimpleClientHttpRequestFactory requestFactory = new MySimpleClientHttpRequestFactory(verifier , rememberMeCookie);
     ResponseEntity<String> response = restTemplate.postForEntity(appUrl + "/login", params, String.class);

     HttpHeaders headers = response.getHeaders();
     String cookieResponse = headers.getFirst("Set-Cookie");
     String[] cookieParts = cookieResponse.split(";");
     rememberMeCookie = cookieParts[0];
     cookie.setCookie(rememberMeCookie);

     requestFactory = new  MySimpleClientHttpRequestFactory(verifier,cookie.getCookie());
          restTemplate.setRequestFactory(requestFactory);
}


public class MySimpleClientHttpRequestFactory extends SimpleClientHttpRequestFactory {

        private final HostnameVerifier verifier;
        private final String cookie;

        public MySimpleClientHttpRequestFactory(HostnameVerifier verifier ,String cookie) {
            this.verifier = verifier;
            this.cookie = cookie;
        }

        @Override
        protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
            if (connection instanceof HttpsURLConnection) {
                ((HttpsURLConnection) connection).setHostnameVerifier(verifier);
                ((HttpsURLConnection) connection).setSSLSocketFactory(trustSelfSignedSSL().getSocketFactory());
                ((HttpsURLConnection) connection).setAllowUserInteraction(true);
                String rememberMeCookie = cookie == null ? "" : cookie; 
                ((HttpsURLConnection) connection).setRequestProperty("Cookie", rememberMeCookie);
            }
            super.prepareConnection(connection, httpMethod);
        }

        public SSLContext trustSelfSignedSSL() {
            try {
                SSLContext ctx = SSLContext.getInstance("TLS");
                X509TrustManager tm = new X509TrustManager() {

                    public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                    }

                    public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };
                ctx.init(null, new TrustManager[] { tm }, null);
                SSLContext.setDefault(ctx);
                return ctx;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }

    }


    public class NullHostnameVerifier implements HostnameVerifier {
           public boolean verify(String hostname, SSLSession session) {
              return true;
           }
        }

"You may need an appropriate loader to handle this file type" with Webpack and Babel

Make sure you have the es2015 babel preset installed.

An example package.json devDependencies is:

"devDependencies": {
  "babel-core": "^6.0.20",
  "babel-loader": "^6.0.1",
  "babel-preset-es2015": "^6.0.15",
  "babel-preset-react": "^6.0.15",
  "babel-preset-stage-0": "^6.0.15",
  "webpack": "^1.9.6",
  "webpack-dev-middleware": "^1.2.0",
  "webpack-hot-middleware": "^2.0.0"
},

Now configure babel-loader in your webpack config:

{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }

add a .babelrc file to the root of your project where the node modules are:

{
  "presets": ["es2015", "stage-0", "react"]
}

More info:

How to turn off Wifi via ADB?

use with quotes

ex: adb shell "svc wifi enable"

this will work :)

What does 'super' do in Python?

What's the difference?

SomeBaseClass.__init__(self) 

means to call SomeBaseClass's __init__. while

super(Child, self).__init__()

means to call a bound __init__ from the parent class that follows Child in the instance's Method Resolution Order (MRO).

If the instance is a subclass of Child, there may be a different parent that comes next in the MRO.

Explained simply

When you write a class, you want other classes to be able to use it. super() makes it easier for other classes to use the class you're writing.

As Bob Martin says, a good architecture allows you to postpone decision making as long as possible.

super() can enable that sort of architecture.

When another class subclasses the class you wrote, it could also be inheriting from other classes. And those classes could have an __init__ that comes after this __init__ based on the ordering of the classes for method resolution.

Without super you would likely hard-code the parent of the class you're writing (like the example does). This would mean that you would not call the next __init__ in the MRO, and you would thus not get to reuse the code in it.

If you're writing your own code for personal use, you may not care about this distinction. But if you want others to use your code, using super is one thing that allows greater flexibility for users of the code.

Python 2 versus 3

This works in Python 2 and 3:

super(Child, self).__init__()

This only works in Python 3:

super().__init__()

It works with no arguments by moving up in the stack frame and getting the first argument to the method (usually self for an instance method or cls for a class method - but could be other names) and finding the class (e.g. Child) in the free variables (it is looked up with the name __class__ as a free closure variable in the method).

I prefer to demonstrate the cross-compatible way of using super, but if you are only using Python 3, you can call it with no arguments.

Indirection with Forward Compatibility

What does it give you? For single inheritance, the examples from the question are practically identical from a static analysis point of view. However, using super gives you a layer of indirection with forward compatibility.

Forward compatibility is very important to seasoned developers. You want your code to keep working with minimal changes as you change it. When you look at your revision history, you want to see precisely what changed when.

You may start off with single inheritance, but if you decide to add another base class, you only have to change the line with the bases - if the bases change in a class you inherit from (say a mixin is added) you'd change nothing in this class. Particularly in Python 2, getting the arguments to super and the correct method arguments right can be difficult. If you know you're using super correctly with single inheritance, that makes debugging less difficult going forward.

Dependency Injection

Other people can use your code and inject parents into the method resolution:

class SomeBaseClass(object):
    def __init__(self):
        print('SomeBaseClass.__init__(self) called')

class UnsuperChild(SomeBaseClass):
    def __init__(self):
        print('UnsuperChild.__init__(self) called')
        SomeBaseClass.__init__(self)

class SuperChild(SomeBaseClass):
    def __init__(self):
        print('SuperChild.__init__(self) called')
        super(SuperChild, self).__init__()

Say you add another class to your object, and want to inject a class between Foo and Bar (for testing or some other reason):

class InjectMe(SomeBaseClass):
    def __init__(self):
        print('InjectMe.__init__(self) called')
        super(InjectMe, self).__init__()

class UnsuperInjector(UnsuperChild, InjectMe): pass

class SuperInjector(SuperChild, InjectMe): pass

Using the un-super child fails to inject the dependency because the child you're using has hard-coded the method to be called after its own:

>>> o = UnsuperInjector()
UnsuperChild.__init__(self) called
SomeBaseClass.__init__(self) called

However, the class with the child that uses super can correctly inject the dependency:

>>> o2 = SuperInjector()
SuperChild.__init__(self) called
InjectMe.__init__(self) called
SomeBaseClass.__init__(self) called

Addressing a comment

Why in the world would this be useful?

Python linearizes a complicated inheritance tree via the C3 linearization algorithm to create a Method Resolution Order (MRO).

We want methods to be looked up in that order.

For a method defined in a parent to find the next one in that order without super, it would have to

  1. get the mro from the instance's type
  2. look for the type that defines the method
  3. find the next type with the method
  4. bind that method and call it with the expected arguments

The UnsuperChild should not have access to InjectMe. Why isn't the conclusion "Always avoid using super"? What am I missing here?

The UnsuperChild does not have access to InjectMe. It is the UnsuperInjector that has access to InjectMe - and yet cannot call that class's method from the method it inherits from UnsuperChild.

Both Child classes intend to call a method by the same name that comes next in the MRO, which might be another class it was not aware of when it was created.

The one without super hard-codes its parent's method - thus is has restricted the behavior of its method, and subclasses cannot inject functionality in the call chain.

The one with super has greater flexibility. The call chain for the methods can be intercepted and functionality injected.

You may not need that functionality, but subclassers of your code may.

Conclusion

Always use super to reference the parent class instead of hard-coding it.

What you intend is to reference the parent class that is next-in-line, not specifically the one you see the child inheriting from.

Not using super can put unnecessary constraints on users of your code.

Maven dependency for Servlet 3.0 API?

Just for newcomers.

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

Trying to make bootstrap modal wider

Always have handy the un-minified CSS for bootstrap so you can see what styles they have on their components, then create a CSS file AFTER it, if you don't use LESS and over-write their mixins or whatever

This is the default modal css for 768px and up:

@media (min-width: 768px) {
  .modal-dialog {
    width: 600px;
    margin: 30px auto;
  }
  ...
}

They have a class modal-lg for larger widths

@media (min-width: 992px) {
  .modal-lg {
    width: 900px;
  }
}

If you need something twice the 600px size, and something fluid, do something like this in your CSS after the Bootstrap css and assign that class to the modal-dialog.

@media (min-width: 768px) {
  .modal-xl {
    width: 90%;
   max-width:1200px;
  }
}

HTML

<div class="modal-dialog modal-xl">

Demo: http://jsbin.com/yefas/1

SQL statement to select all rows from previous day

Can't test it right now, but:

select * from tablename where date >= dateadd(day, datediff(day, 1, getdate()), 0) and date < dateadd(day, datediff(day, 0, getdate()), 0)

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript. Just use CSS3. Please take a look at

carousel.carousel-fade

in the CSS of the following examples:

how to call a function from another function in Jquery

wrap you shared code into another function:

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

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

How to execute command stored in a variable?

If you just do eval $cmd when we do cmd="ls -l" (interactively and in a script) we get the desired result. In your case, you have a pipe with a grep without a pattern, so the grep part will fail with an error message. Just $cmd will generate a "command not found" (or some such) message. So try use eval and use a finished command, not one that generates an error message.

Run a single migration file

If you want to run it from console, this is what you are looking for:

$ rails console
irb(main)> require "#{Rails.root.to_s}/db/migrate/XXXXX_my_migration.rb"
irb(main)> AddFoo.migrate(:up)

I tried the other answers, but requiring without Rails.root didnt work for me.

Also, .migrate(:up) part forces the migration to rerun regardless if it has already run or not. This is useful for when you already ran a migration, have kinda undone it by messing around with the db and want a quick solution to have it up again.

what is the unsigned datatype?

unsigned really is a shorthand for unsigned int, and so defined in standard C.

How to wait until WebBrowser is completely loaded in VB.NET?

Salvete! I needed, simply, a function I could call to make the code wait for the page to load before it continued. After scouring the web for answers, and fiddling around for several hours, I came up with this to solve for myself, the exact dilemma you present. I know I am late in the game with an answer, but I wish to post this for anyone else who comes along.

usage: just call WaitForPageLoad() just after a call to navigation:

whatbrowser.Navigate("http://www.google.com")
WaitForPageLoad()

another example we don't combine the navigate feature with the page load, because sometimes you need to wait for a load without also navigating, for example, you might need to wait for a page to load that was started with an invokemember event:

whatbrowser.Document.GetElementById("UserName").InnerText = whatusername
whatbrowser.Document.GetElementById("Password").InnerText = whatpassword
whatbrowser.Document.GetElementById("LoginButton").InvokeMember("click")
WaitForPageLoad()

Here is the code: You need both subs plus the accessible variable, pageready. First, make sure to fix the variable called whatbrowser to be your webbrowser control

Now, somewhere in your module or class, place this:

Private Property pageready As Boolean = False

#Region "Page Loading Functions"
    Private Sub WaitForPageLoad()
        AddHandler whatbrowser.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
        While Not pageready
            Application.DoEvents()
        End While
        pageready = False
    End Sub

    Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
        If whatbrowser.ReadyState = WebBrowserReadyState.Complete Then
            pageready = True
            RemoveHandler whatbrowser.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
        End If
    End Sub

#End Region

How to check ASP.NET Version loaded on a system?

Here is some code that will return the installed .NET details:

<%@ Page Language="VB" Debug="true" %>
<%@ Import namespace="System" %>
<%@ Import namespace="System.IO" %>
<% 
Dim cmnNETver, cmnNETdiv, aspNETver, aspNETdiv As Object
Dim winOSver, cmnNETfix, aspNETfil(2), aspNETtxt(2), aspNETpth(2), aspNETfix(2) As String

winOSver = Environment.OSVersion.ToString
cmnNETver = Environment.Version.ToString
cmnNETdiv = cmnNETver.Split(".")
cmnNETfix = "v" & cmnNETdiv(0) & "." & cmnNETdiv(1) & "." & cmnNETdiv(2)

For filndx As Integer = 0 To 2
  aspNETfil(0) = "ngen.exe"
  aspNETfil(1) = "clr.dll"
  aspNETfil(2) = "KernelBase.dll"

  If filndx = 2   
    aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), aspNETfil(filndx))
  Else
    aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64", cmnNETfix, aspNETfil(filndx))
  End If

  If File.Exists(aspNETpth(filndx)) Then
    aspNETver = Diagnostics.FileVersionInfo.GetVersionInfo(aspNETpth(filndx))
    aspNETtxt(filndx) = aspNETver.FileVersion.ToString
    aspNETdiv = aspNETtxt(filndx).Split(" ")
    aspNETfix(filndx) = aspNETdiv(0)
  Else
    aspNETfix(filndx) = "Path not found... No version found..."
  End If
Next

Response.Write("Common MS.NET Version (raw): " & cmnNETver & "<br>")
Response.Write("Common MS.NET path: " & cmnNETfix & "<br>")
Response.Write("Microsoft.NET full path: " & aspNETpth(0) & "<br>")
Response.Write("Microsoft.NET Version (raw): " & aspNETtxt(0) & "<br>")
Response.Write("<b>Microsoft.NET Version: " & aspNETfix(0) & "</b><br>")
Response.Write("ASP.NET full path: " & aspNETpth(1) & "<br>")
Response.Write("ASP.NET Version (raw): " & aspNETtxt(1) & "<br>")
Response.Write("<b>ASP.NET Version: " & aspNETfix(1) & "</b><br>")
Response.Write("OS Version (system): " & winOSver & "<br>")
Response.Write("OS Version full path: " & aspNETpth(2) & "<br>")
Response.Write("OS Version (raw): " & aspNETtxt(2) & "<br>")
Response.Write("<b>OS Version: " & aspNETfix(2) & "</b><br>")
%>

Here is the new output, cleaner code, more output:

Common MS.NET Version (raw): 4.0.30319.42000
Common MS.NET path: v4.0.30319
Microsoft.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe
Microsoft.NET Version (raw): 4.6.1586.0 built by: NETFXREL2
Microsoft.NET Version: 4.6.1586.0
ASP.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
ASP.NET Version (raw): 4.7.2110.0 built by: NET47REL1LAST
ASP.NET Version: 4.7.2110.0
OS Version (system): Microsoft Windows NT 10.0.14393.0
OS Version full path: C:\Windows\system32\KernelBase.dll
OS Version (raw): 10.0.14393.1715 (rs1_release_inmarket.170906-1810)
OS Version: 10.0.14393.1715

PHP - Debugging Curl

Another (crude) option is to utilize netcat for dumping the full request:

nc -l -p 8000 -w 3 | tee curldbg.txt

And of course sending the failing request to it:

curl_setup(CURLOPT_URL, "http://localhost/testytest");

Notably that will always hang+fail, since netcat won't ever construct a valid HTTP response. It's really just for inspecting what really got sent. The better option, of course, is using a http request debugging service.

document.getElementById('btnid').disabled is not working in firefox and chrome

stay true to native (Boolean) property support and its powerful syntax like:

[elem].disabled = condition ? true : false; //done!

and for our own good collective coding experience, -please insist on others to support it as well.

Should I put input elements inside a label element?

I prefer

<label>
  Firstname
  <input name="firstname" />
</label>

<label>
  Lastname
  <input name="lastname" />
</label>

over

<label for="firstname">Firstname</label>
<input name="firstname" id="firstname" />

<label for="lastname">Lastname</label>
<input name="lastname" id="lastname" />

Mainly because it makes the HTML more readable. And I actually think my first example is easier to style with CSS, as CSS works very well with nested elements.

But it's a matter of taste I suppose.


If you need more styling options, add a span tag.

<label>
  <span>Firstname</span>
  <input name="firstname" />
</label>

<label>
  <span>Lastname</span>
  <input name="lastname" />
</label>

Code still looks better in my opinion.

C#: Assign same value to multiple variables in single statement

This will do want you want:

int num1, num2;
num1 = num2 = 5;

'num2 = 5' assignment will return the assigned value.

This allows you to do crazy things like num1 = (num2 = 5) +3; which will assign 8 to num1, although I would not recommended doing it as not be very readable.

Difference between Inheritance and Composition

Inheritence means reusing the complete functionality of a class, Here my class have to use all the methods of the super class and my class will be titely coupled with the super class and code will be duplicated in both the classes in case of inheritence.

But we can overcome from all these problem when we use composition to talk with another class . composition is declaring an attribute of another class into my class to which we want to talk. and what functionality we want from that class we can get by using that attribute.

List of special characters for SQL LIKE clause

Sybase :

%              : Matches any string of zero or more characters.
_              : Matches a single character.
[specifier]    : Brackets enclose ranges or sets, such as [a-f] 
                 or [abcdef].Specifier  can take two forms:

                 rangespec1-rangespec2: 
                   rangespec1 indicates the start of a range of characters.
                   - is a special character, indicating a range.
                   rangespec2 indicates the end of a range of characters.

                 set: 
                  can be composed of any discrete set of values, in any 
                  order, such as [a2bR].The range [a-f], and the 
                  sets [abcdef] and [fcbdae] return the same 
                  set of values.

                 Specifiers are case-sensitive.

[^specifier]    : A caret (^) preceding a specifier indicates 
                  non-inclusion. [^a-f] means "not in the range 
                  a-f"; [^a2bR] means "not a, 2, b, or R."

JavaScript: How to get parent element by selector?

You may use closest() in modern browsers:

var div = document.querySelector('div#myDiv');
div.closest('div[someAtrr]');

Use object detection to supply a polyfill or alternative method for backwards compatability with IE.

Google Maps setCenter()

I searched and searched and finally found that ie needs to know the map size. Set the map size to match the div size.

map = new GMap2(document.getElementById("map_canvas2"), { size: new GSize(850, 600) });

<div id="map_canvas2" style="width: 850px; height: 600px">
</div>

How to strip HTML tags with jQuery?

The safest way is to rely on the browser TextNode to correctly escape content. Here's an example:

_x000D_
_x000D_
function stripHTML(dirtyString) {_x000D_
  var container = document.createElement('div');_x000D_
  var text = document.createTextNode(dirtyString);_x000D_
  container.appendChild(text);_x000D_
  return container.innerHTML; // innerHTML will be a xss safe string_x000D_
}_x000D_
_x000D_
document.write( stripHTML('<p>some <span>content</span></p>') );_x000D_
document.write( stripHTML('<script><p>some <span>content</span></p>') );
_x000D_
_x000D_
_x000D_

The thing to remember here is that the browser escape the special characters of TextNodes when we access the html strings (innerHTML, outerHTML). By comparison, accessing text values (innerText, textContent) will yield raw strings, meaning they're unsafe and could contains XSS.

If you use jQuery, then using .text() is safe and backward compatible. See the other answers to this question.

The simplest way in pure JavaScript if you work with browsers <= Internet Explorer 8 is:

string.replace(/(<([^>]+)>)/ig,"");

But there's some issue with parsing HTML with regex so this won't provide very good security. Also, this only takes care of HTML characters, so it is not totally xss-safe.

jQuery Datepicker with text input that doesn't allow user input

This question has a lot of older answers and readonly seems to be the generally accepted solution. I believe the better approach in modern browsers is to use the inputmode="none" in the HTML input tag:

<input type="text" ... inputmode="none" />

or, if you prefer to do it in script:

$(selector).attr('inputmode', 'none');

I haven't tested it extensively, but it is working well on the Android setups I have used it with.

How to include scripts located inside the node_modules folder?

If you are linking to many files, create a whitelist, and then use sendFile():

app.get('/npm/:pkg/:file', (req, res) => {
    const ok = ['jquery','bootstrap','interactjs'];
    if (!ok.includes(req.params.pkg)) res.status(503).send("Not Permitted.");
    res.sendFile(__dirname + `/node_modules/${req.params.pkg}/dist/${req.params.file}`);
    });

For example, You can then safely link to /npm/bootstrap/bootsrap.js, /npm/bootstrap/bootsrap.css, etc.

As an aside, I would love to know if there was a way to whitelist using express.static

How to nicely format floating numbers to string without unnecessary decimal 0's

String s = "1.210000";
while (s.endsWith("0")){
    s = (s.substring(0, s.length() - 1));
}

This will make the string to drop the tailing 0-s.

Setting HTTP headers

I know this is a different twist on the answer, but isn't this more of a concern for a web server? For example, nginx, could help.

The ngx_http_headers_module module allows adding the “Expires” and “Cache-Control” header fields, and arbitrary fields, to a response header

...

location ~ ^<REGXP MATCHING CORS ROUTES> {
    add_header Access-Control-Allow-Methods POST
    ...
}
...

Adding nginx in front of your go service in production seems wise. It provides a lot more feature for authorizing, logging,and modifying requests. Also, it gives the ability to control who has access to your service and not only that but one can specify different behavior for specific locations in your app, as demonstrated above.

I could go on about why to use a web server with your go api, but I think that's a topic for another discussion.

Using Jquery AJAX function with datatype HTML

Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.

Ajax call:

$.ajax({
  type : 'POST',
  url : 'post.php',
  dataType : 'html',
  data: {
      email : $('#email').val()
  },
  success : function(data){
      $('#waiting').hide(500);
      $('#message').removeClass().addClass((data == '') ? 'error' : 'success')
     .html(data).show(500);
      if (data == '') {
          $('#message').html("Format your email correcly");
          $('#demoForm').show(500);
      }
  },
  error : function(XMLHttpRequest, textStatus, errorThrown) {
      $('#waiting').hide(500);
      $('#message').removeClass().addClass('error')
      .text('There was an error.').show(500);
      $('#demoForm').show(500);
  }

});

post.php

<?php
sleep(1);

function processEmail($email) {
    if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
        // your logic here (ex: add into database)
        return true;
    }
    return false;
}

if (processEmail($_POST['email'])) {
    echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}

EL access a map value by Integer key

Just another helpful hint in addition to the above comment would be when you have a string value contained in some variable such as a request parameter. In this case, passing this in will also result in JSTL keying the value of say "1" as a sting and as such no match being found in a Map hashmap.

One way to get around this is to do something like this.

<c:set var="longKey" value="${param.selectedIndex + 0}"/>

This will now be treated as a Long object and then has a chance to match an object when it is contained withing the map Map or whatever.

Then, continue as usual with something like

${map[longKey]}

convert epoch time to date

Please take care that the epoch time is in second and Date object accepts Long value which is in milliseconds. Hence you would have to multiply epoch value with 1000 to use it as long value . Like below :-

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
Long dateLong=Long.parseLong(sdf.format(epoch*1000));

Closing WebSocket correctly (HTML5, Javascript)

please use this

var uri = "ws://localhost:5000/ws";
var socket = new WebSocket(uri);
socket.onclose = function (e){
    console.log(connection closed);
};
window.addEventListener("unload", function () {
    if(socket.readyState == WebSocket.OPEN)
        socket.close();
});

Close browser doesn't trigger websocket close event. You must call socket.close() manually.

Argument list too long error for rm, cp, mv commands

I ran into this problem a few times. Many of the solutions will run the rm command for each individual file that needs to be deleted. This is very inefficient:

find . -name "*.pdf" -print0 | xargs -0 rm -rf

I ended up writing a python script to delete the files based on the first 4 characters in the file-name:

import os
filedir = '/tmp/' #The directory you wish to run rm on 
filelist = (os.listdir(filedir)) #gets listing of all files in the specified dir
newlist = [] #Makes a blank list named newlist
for i in filelist: 
    if str((i)[:4]) not in newlist: #This makes sure that the elements are unique for newlist
        newlist.append((i)[:4]) #This takes only the first 4 charcters of the folder/filename and appends it to newlist
for i in newlist:
    if 'tmp' in i:  #If statment to look for tmp in the filename/dirname
        print ('Running command rm -rf '+str(filedir)+str(i)+'* : File Count: '+str(len(os.listdir(filedir)))) #Prints the command to be run and a total file count
        os.system('rm -rf '+str(filedir)+str(i)+'*') #Actual shell command
print ('DONE')

This worked very well for me. I was able to clear out over 2 million temp files in a folder in about 15 minutes. I commented the tar out of the little bit of code so anyone with minimal to no python knowledge can manipulate this code.

Case Function Equivalent in Excel

Sounds like a job for VLOOKUP!

You can put your 32 -> 1420 type mappings in a couple of columns somewhere, then use the VLOOKUP function to perform the lookup.

How often should you use git-gc?

Drop it in a cron job that runs every night (afternoon?) when you're sleeping.

What is difference between functional and imperative programming languages?

Here is the difference:

Imperative:

  • Start
  • Turn on your shoes size 9 1/2.
  • Make room in your pocket to keep an array[7] of keys.
  • Put the keys in the room for the keys in the pocket.
  • Enter garage.
  • Open garage.
  • Enter Car.

... and so on and on ...

  • Put the milk in the refrigerator.
  • Stop.

Declarative, whereof functional is a subcategory:

  • Milk is a healthy drink, unless you have problems digesting lactose.
  • Usually, one stores milk in a refrigerator.
  • A refrigerator is a box that keeps the things in it cool.
  • A store is a place where items are sold.
  • By "selling" we mean the exchange of things for money.
  • Also, the exchange of money for things is called "buying".

... and so on and on ...

  • Make sure we have milk in the refrigerator (when we need it - for lazy functional languages).

Summary: In imperative languages you tell the computer how to change bits, bytes and words in it's memory and in what order. In functional ones, we tell the computer what things, actions etc. are. For example, we say that the factorial of 0 is 1, and the factorial of every other natural number is the product of that number and the factorial of its predecessor. We don't say: To compute the factorial of n, reserve a memory region and store 1 there, then multiply the number in that memory region with the numbers 2 to n and store the result at the same place, and at the end, the memory region will contain the factorial.

how to configure lombok in eclipse luna

I have met with the exact same problem. And it turns out that the configuration file generated by gradle asks for java1.7.
While my system has java1.8 installed.

After modifying the compiler compliance level to 1.8. All things are working as expected.

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

Difference between Groovy Binary and Source release?

A source release will be compiled on your own machine while a binary release must match your operating system.

source releases are more common on linux systems because linux systems can dramatically vary in cpu, installed library versions, kernelversions and nearly every linux system has a compiler installed.

binary releases are common on ms-windows systems. most windows machines do not have a compiler installed.

What is WEB-INF used for in a Java EE web application?

There is a convention (not necessary) of placing jsp pages under WEB-INF directory so that they cannot be deep linked or bookmarked to. This way all requests to jsp page must be directed through our application, so that user experience is guaranteed.

HTML CSS Button Positioning

Use margins instead of line-height and then apply float to the buttons. By default they are displaying as inline-block, so when one is pushed down the hole line is pushed down with him. Float fixes this:

#header button {
    float:left;
}

Here's a working jsfidle.

How to assign a heredoc value to a variable in Bash?

this is variation of Dennis method, looks more elegant in the scripts.

function definition:

define(){ IFS='\n' read -r -d '' ${1} || true; }

usage:

define VAR <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF

echo "$VAR"

enjoy

p.s. made a 'read loop' version for shells that do not support read -d. should work with set -eu and unpaired backticks, but not tested very well:

define(){ o=; while IFS="\n" read -r a; do o="$o$a"'
'; done; eval "$1=\$o"; }

Android open camera from button

 Button b = (Button)findViewById(R.id.Button01);

    b.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
             Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
             startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
        }
    });
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_PIC_REQUEST) {
          Bitmap image = (Bitmap) data.getExtras().get("data");
          ImageView imageview = (ImageView) findViewById(R.id.ImageView01); //sets imageview as the bitmap
          imageview.setImageBitmap(image);
    }
}

How can I perform an inspect element in Chrome on my Galaxy S3 Android device?

Mainly follow the guide here https://developers.google.com/chrome-developer-tools/docs/remote-debugging. But ...

  • For Samsung devices don't forget to install Samsung Kies.
  • For me it worked only with Chrome Canary, not with Chrome.
  • You might also need to install Android SDK.

jQuery Ajax error handling, show custom exception messages

I believe the Ajax response handler uses the HTTP status code to check if there was an error.

So if you just throw a Java exception on your server side code but then the HTTP response doesn't have a 500 status code jQuery (or in this case probably the XMLHttpRequest object) will just assume that everything was fine.

I'm saying this because I had a similar problem in ASP.NET where I was throwing something like a ArgumentException("Don't know what to do...") but the error handler wasn't firing.

I then set the Response.StatusCode to either 500 or 200 whether I had an error or not.

git rebase merge conflict

Note: with Git 2.14.x/2.15 (Q3 2017), the git rebase message in case of conflicts will be clearer.

See commit 5fdacc1 (16 Jul 2017) by William Duclot (williamdclt).
(Merged by Junio C Hamano -- gitster -- in commit 076eeec, 11 Aug 2017)

rebase: make resolve message clearer for inexperienced users

Before:

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort"

After:

Resolve all conflicts manually, 
mark them as resolved with git add/rm <conflicted_files>
then run "git rebase --continue".

You can instead skip this commit: run "git rebase --skip".
To abort and get back to the state before "git rebase", run "git rebase --abort".')

The git UI can be improved by addressing the error messages to those they help: inexperienced and casual git users.
To this intent, it is helpful to make sure the terms used in those messages can be understood by this segment of users, and that they guide them to resolve the problem.

In particular, failure to apply a patch during a git rebase is a common problem that can be very destabilizing for the inexperienced user.
It is important to lead them toward the resolution of the conflict (which is a 3-steps process, thus complex) and reassure them that they can escape a situation they can't handle with "--abort".
This commit answer those two points by detailing the resolution process and by avoiding cryptic git linguo.

ng serve not detecting file changes automatically

For me what worked was:

rm -rf node_modules && npm install

And then

ng serve

How to format date in angularjs

{{convertToDate  | date :  dateformat}}                                             
$rootScope.dateFormat = 'MM/dd/yyyy';

How to find indices of all occurrences of one string in another in JavaScript?

I would recommend Tim's answer. However, this comment by @blazs states "Suppose searchStr=aaa and that str=aaaaaa. Then instead of finding 4 occurences your code will find only 2 because you're making skips by searchStr.length in the loop.", which is true by looking at Tim's code, specifically this line here: startIndex = index + searchStrLen; Tim's code would not be able to find an instance of the string that's being searched that is within the length of itself. So, I've modified Tim's answer:

_x000D_
_x000D_
function getIndicesOf(searchStr, str, caseSensitive) {
    var startIndex = 0, index, indices = [];
    if (!caseSensitive) {
        str = str.toLowerCase();
        searchStr = searchStr.toLowerCase();
    }
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        indices.push(index);
        startIndex = index + 1;
    }
    return indices;
}
var searchStr = prompt("Enter a string.");
var str = prompt("What do you want to search for in the string?");
var indices = getIndicesOf(str, searchStr);

document.getElementById("output").innerHTML = indices + "";
_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Changing it to + 1 instead of + searchStrLen will allow the index 1 to be in the indices array if I have an str of aaaaaa and a searchStr of aaa.

P.S. If anyone would like comments in the code to explain how the code works, please say so, and I'll be happy to respond to the request.

What is a regular expression for a MAC Address?

the best answer is for mac address validation regex

^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$

How to create strings containing double quotes in Excel formulas?

I use a function for this (if the workbook already has VBA).

Function Quote(inputText As String) As String
  Quote = Chr(34) & inputText & Chr(34)
End Function

This is from Sue Mosher's book "Microsoft Outlook Programming". Then your formula would be:

="Maurice "&Quote("Rocket")&" Richard"

This is similar to what Dave DuPlantis posted.

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

First of all: I'm the author of the The Single Page Interface Manifesto cited by raganwald

As raganwald has explained very well, the most important aspect of the Single Page Interface (SPI) approach used in FaceBook and Twitter is the use of hash # in URLs

The character ! is added only for Google purposes, this notation is a Google "standard" for crawling web sites intensive on AJAX (in the extreme Single Page Interface web sites). When Google's crawler finds an URL with #! it knows that an alternative conventional URL exists providing the same page "state" but in this case on load time.

In spite of #! combination is very interesting for SEO, is only supported by Google (as far I know), with some JavaScript tricks you can build SPI web sites SEO compatible for any web crawler (Yahoo, Bing...).

The SPI Manifesto and demos do not use Google's format of ! in hashes, this notation could be easily added and SPI crawling could be even easier (UPDATE: now ! notation is used and remains compatible with other search engines).

Take a look to this tutorial, is an example of a simple ItsNat SPI site but you can pick some ideas for other frameworks, this example is SEO compatible for any web crawler.

The hard problem is to generate any (or selected) "AJAX page state" as plain HTML for SEO, in ItsNat is very easy and automatic, the same site is in the same time SPI or page based for SEO (or when JavaScript is disabled for accessibility). With other web frameworks you can ever follow the double site approach, one site is SPI based and another page based for SEO, for instance Twitter uses this "double site" technique.

What is a mutex?

A Mutex is a mutually exclusive flag. It acts as a gate keeper to a section of code allowing one thread in and blocking access to all others. This ensures that the code being controled will only be hit by a single thread at a time. Just be sure to release the mutex when you are done. :)

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

Convert to/from DateTime and Time in Ruby

As an update to the state of the Ruby ecosystem, Date, DateTime and Time now have methods to convert between the various classes. Using Ruby 1.9.2+:

pry
[1] pry(main)> ts = 'Jan 1, 2000 12:01:01'
=> "Jan 1, 2000 12:01:01"
[2] pry(main)> require 'time'
=> true
[3] pry(main)> require 'date'
=> true
[4] pry(main)> ds = Date.parse(ts)
=> #<Date: 2000-01-01 (4903089/2,0,2299161)>
[5] pry(main)> ds.to_date
=> #<Date: 2000-01-01 (4903089/2,0,2299161)>
[6] pry(main)> ds.to_datetime
=> #<DateTime: 2000-01-01T00:00:00+00:00 (4903089/2,0,2299161)>
[7] pry(main)> ds.to_time
=> 2000-01-01 00:00:00 -0700
[8] pry(main)> ds.to_time.class
=> Time
[9] pry(main)> ds.to_datetime.class
=> DateTime
[10] pry(main)> ts = Time.parse(ts)
=> 2000-01-01 12:01:01 -0700
[11] pry(main)> ts.class
=> Time
[12] pry(main)> ts.to_date
=> #<Date: 2000-01-01 (4903089/2,0,2299161)>
[13] pry(main)> ts.to_date.class
=> Date
[14] pry(main)> ts.to_datetime
=> #<DateTime: 2000-01-01T12:01:01-07:00 (211813513261/86400,-7/24,2299161)>
[15] pry(main)> ts.to_datetime.class
=> DateTime

Easy way to build Android UI?

Not saying this is the best way to go, but its good to have options. Necessitas is a project that ports Qt to android. It is still in its early stages and lacking full features, but for those who know Qt and don't wanna bother with the terrible lack of good tools for Android UI would be wise to at least consider using this.

Sorting a vector in descending order

First approach refers:

    std::sort(numbers.begin(), numbers.end(), std::greater<>());

You may use the first approach because of getting more efficiency than second.
The first approach's time complexity less than second one.

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

You should use

 SSLContext.getInstance("TLSv1.2"); 

for specific protocol version.

The second exception occured because default socketFactory used fallback SSLv3 protocol for failures.

You can use NoSSLFactory from main answer here for its suppression How to disable SSLv3 in android for HttpsUrlConnection?

Also you should init SSLContext with all your certificates(client and trusted ones if you need them)

But all of that is useless without using

ProviderInstaller.installIfNeeded(getContext())

Here is more information with proper usage scenario https://developer.android.com/training/articles/security-gms-provider.html

Hope it helps.

How can I query for null values in entity framework?

There is a slightly simpler workaround that works with LINQ to Entities:

var result = from entry in table
         where entry.something == value || (value == null && entry.something == null)
         select entry;

This works becasuse, as AZ noticed, LINQ to Entities special cases x == null (i.e. an equality comparison against the null constant) and translates it to x IS NULL.

We are currently considering changing this behavior to introduce the compensating comparisons automatically if both sides of the equality are nullable. There are a couple of challenges though:

  1. This could potentially break code that already depends on the existing behavior.
  2. The new translation could affect the performance of existing queries even when a null parameter is seldom used.

In any case, whether we get to work on this is going to depend greatly on the relative priority our customers assign to it. If you care about the issue, I encourage you to vote for it in our new Feature Suggestion site: https://data.uservoice.com.

Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

I put the User import into the settings file for managing the rest call token like this

# settings.py
from django.contrib.auth.models import User
def jwt_get_username_from_payload_handler(payload):
   ....

JWT_AUTH = {
    'JWT_PAYLOAD_GET_USERNAME_HANDLER': jwt_get_username_from_payload_handler,
    'JWT_PUBLIC_KEY': PUBLIC_KEY,
    'JWT_ALGORITHM': 'RS256',
    'JWT_AUDIENCE': API_IDENTIFIER,
    'JWT_ISSUER': JWT_ISSUER,
    'JWT_AUTH_HEADER_PREFIX': 'Bearer',
}
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
       'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

Because at that moment, Django libs are not ready yet. Therefore, I put the import inside the function and it started to work. The function needs to be called after the server is started

Java difference between FileWriter and BufferedWriter

From the Java API specification:

FileWriter

Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable.

BufferedWriter

Write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

How to respond to clicks on a checkbox in an AngularJS directive?

This is the way I've been doing this sort of stuff. Angular tends to favor declarative manipulation of the dom rather than a imperative one(at least that's the way I've been playing with it).

The markup

<table class="table">
  <thead>
    <tr>
      <th>
        <input type="checkbox" 
          ng-click="selectAll($event)"
          ng-checked="isSelectedAll()">
      </th>
      <th>Title</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="e in entities" ng-class="getSelectedClass(e)">
      <td>
        <input type="checkbox" name="selected"
          ng-checked="isSelected(e.id)"
          ng-click="updateSelection($event, e.id)">
      </td>
      <td>{{e.title}}</td>
    </tr>
  </tbody>
</table>

And in the controller

var updateSelected = function(action, id) {
  if (action === 'add' && $scope.selected.indexOf(id) === -1) {
    $scope.selected.push(id);
  }
  if (action === 'remove' && $scope.selected.indexOf(id) !== -1) {
    $scope.selected.splice($scope.selected.indexOf(id), 1);
  }
};

$scope.updateSelection = function($event, id) {
  var checkbox = $event.target;
  var action = (checkbox.checked ? 'add' : 'remove');
  updateSelected(action, id);
};

$scope.selectAll = function($event) {
  var checkbox = $event.target;
  var action = (checkbox.checked ? 'add' : 'remove');
  for ( var i = 0; i < $scope.entities.length; i++) {
    var entity = $scope.entities[i];
    updateSelected(action, entity.id);
  }
};

$scope.getSelectedClass = function(entity) {
  return $scope.isSelected(entity.id) ? 'selected' : '';
};

$scope.isSelected = function(id) {
  return $scope.selected.indexOf(id) >= 0;
};

//something extra I couldn't resist adding :)
$scope.isSelectedAll = function() {
  return $scope.selected.length === $scope.entities.length;
};

EDIT: getSelectedClass() expects the entire entity but it was being called with the id of the entity only, which is now corrected

Jquery each - Stop loop and return object

"We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration."

from http://api.jquery.com/jquery.each/

Yea, this is old BUT, JUST to answer the question, this can be a bit simpler:

_x000D_
_x000D_
function findXX(word) {_x000D_
  $.each(someArray, function(index, value) {_x000D_
    $('body').append('-> ' + index + ":" + value + '<br />');_x000D_
    return !(value == word);_x000D_
  });_x000D_
}_x000D_
$(function() {_x000D_
  someArray = new Array();_x000D_
  someArray[0] = 't5';_x000D_
  someArray[1] = 'z12';_x000D_
  someArray[2] = 'b88';_x000D_
  someArray[3] = 's55';_x000D_
  someArray[4] = 'e51';_x000D_
  someArray[5] = 'o322';_x000D_
  someArray[6] = 'i22';_x000D_
  someArray[7] = 'k954';_x000D_
  findXX('o322');_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

A bit more with comments:

_x000D_
_x000D_
function findXX(myA, word) {_x000D_
  let br = '<br />';//create once_x000D_
  let myHolder = $("<div />");//get a holder to not hit DOM a lot_x000D_
  let found = false;//default return_x000D_
  $.each(myA, function(index, value) {_x000D_
    found = (value == word);_x000D_
    myHolder.append('-> ' + index + ":" + value + br);_x000D_
    return !found;_x000D_
  });_x000D_
  $('body').append(myHolder.html());// hit DOM once_x000D_
  return found;_x000D_
}_x000D_
$(function() {_x000D_
  // no horrid global array, easier array setup;_x000D_
  let someArray = ['t5', 'z12', 'b88', 's55', 'e51', 'o322', 'i22', 'k954'];_x000D_
  // pass the array and the value we want to find, return back a value_x000D_
  let test = findXX(someArray, 'o322');_x000D_
  $('body').append("<div>Found:" + test + "</div>");_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

NOTE: array .includes() may better suit here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Or just .find() to get that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

How do I collapse sections of code in Visual Studio Code for Windows?

Note: these shortcuts only work as expected if you edit your keybindings.json

I wasn't happy with the default shortcuts, I wanted them to work as follow:

  • Fold: Ctrl + Alt + ]
  • Fold recursively: Ctrl + ? Shift + Alt + ]
  • Fold all: Ctrl + k then Ctrl + ]
  • Unfold: Ctrl + Alt + [
  • Unfold recursively: Ctrl + ? Shift + Alt + [
  • Unfold all: Ctrl + k then Ctrl + [

To set it up:

  • Open Preferences: Open Keyboard Shortcuts (JSON) (Ctrl + ? Shift + p)
  • Add the following snippet to that file

    Already have custom keybindings for fold/unfold? Then you'd need to replace them.

    {
        "key": "ctrl+alt+]",
        "command": "editor.fold",
        "when": "editorTextFocus && foldingEnabled"
    },
    {
        "key": "ctrl+alt+[",
        "command": "editor.unfold",
        "when": "editorTextFocus && foldingEnabled"
    },
    {
        "key": "ctrl+shift+alt+]",
        "command": "editor.foldRecursively",
        "when": "editorTextFocus && foldingEnabled"
    },
    {
        "key": "ctrl+shift+alt+[",
        "command": "editor.unfoldRecursively",
        "when": "editorTextFocus && foldingEnabled"
    },
    {
        "key": "ctrl+k ctrl+[",
        "command": "editor.unfoldAll",
        "when": "editorTextFocus && foldingEnabled"
    },
    {
        "key": "ctrl+k ctrl+]",
        "command": "editor.foldAll",
        "when": "editorTextFocus && foldingEnabled"
    },

CSS/HTML: Create a glowing border around an Input Field

Below is the code that Bootstrap uses. Colors are bit different but the concept is same. This is if you are using LESS to compile CSS:

// Form control focus state
//
// Generate a customized focus state and for any input with the specified color,
// which defaults to the `@input-focus-border` variable.
//
// We highly encourage you to not customize the default value, but instead use
// this to tweak colors on an as-needed basis. This aesthetic change is based on
// WebKit's default styles, but applicable to a wider range of browsers. Its
// usability and accessibility should be taken into account with any change.
//
// Example usage: change the default blue border and shadow to white for better
// contrast against a dark gray background.

.form-control-focus(@color: @input-border-focus) {
  @color-rgba: rgba(red(@color), green(@color), blue(@color), .6);
  &:focus {
    border-color: @color;
    outline: 0;
    .box-shadow(~"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px @{color-rgba}");
  }
}

If you are not using LESS then here's the compiled version:

.form-control:focus {
    border-color: #66afe9;
    outline: 0;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
}

CASE WHEN statement for ORDER BY clause

declare @OrderByCmd  nvarchar(2000)
declare @OrderByName nvarchar(100)
declare @OrderByCity nvarchar(100)
set @OrderByName='Name'    
set @OrderByCity='city'
set @OrderByCmd= 'select * from customer Order By '+@OrderByName+','+@OrderByCity+''
EXECUTE sp_executesql @OrderByCmd 

Groovy write to file (newline)

It looks to me, like you're working in windows in which case a new line character in not simply \n but rather \r\n

You can always get the correct new line character through System.getProperty("line.separator") for example.

Java, How to implement a Shift Cipher (Caesar Cipher)

Hello...I have created a java client server application in swing for caesar cipher...I have created a new formula that can decrypt the text properly... sorry only for lower case..!

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class ceasarserver extends JFrame implements ActionListener {
    static String cs = "abcdefghijklmnopqrstuvwxyz";
    static JLabel l1, l2, l3, l5, l6;
    JTextField t1;
    JButton close, b1;
    static String en;
    int num = 0;
    JProgressBar progress;

    ceasarserver() {
        super("SERVER");
        JPanel p = new JPanel(new GridLayout(10, 1));
        l1 = new JLabel("");
        l2 = new JLabel("");
        l3 = new JLabel("");
        l5 = new JLabel("");
        l6 = new JLabel("Enter the Key...");
        t1 = new JTextField(30);
        progress = new JProgressBar(0, 20);
        progress.setValue(0);
        progress.setStringPainted(true);
        close = new JButton("Close");
        close.setMnemonic('C');
        close.setPreferredSize(new Dimension(300, 25));
        close.addActionListener(this);
        b1 = new JButton("Decrypt");
        b1.setMnemonic('D');
        b1.addActionListener(this);
        p.add(l1);
        p.add(l2);
        p.add(l3);
        p.add(l6);
        p.add(t1);
        p.add(b1);
        p.add(progress);
        p.add(l5);
        p.add(close);
        add(p);
        setVisible(true);
        pack();
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == close)
            System.exit(0);
        else if (e.getSource() == b1) {
            int key = Integer.parseInt(t1.getText());
            String d = "";
            int i = 0, j, k;
            while (i < en.length()) {
                j = cs.indexOf(en.charAt(i));
                k = (j + (26 - key)) % 26;
                d = d + cs.charAt(k);
                i++;
            }
            while (num < 21) {
                progress.setValue(num);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                }
                progress.setValue(num);
                Rectangle progressRect = progress.getBounds();
                progressRect.x = 0;
                progressRect.y = 0;
                progress.paintImmediately(progressRect);
                num++;
            }
            l5.setText("Decrypted text: " + d);
        }
    }

    public static void main(String args[]) throws IOException {
        new ceasarserver();
        String strm = new String();
        ServerSocket ss = new ServerSocket(4321);
        l1.setText("Secure data transfer Server Started....");
        Socket s = ss.accept();
        l2.setText("Client Connected !");
        while (true) {
            Scanner br1 = new Scanner(s.getInputStream());
            en = br1.nextLine();
            l3.setText("Client:" + en);
        }
    }

The client class:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class ceasarclient extends JFrame {
    String cs = "abcdefghijklmnopqrstuvwxyz";
    static JLabel l1, l2, l3, l4, l5;
    JButton b1, b2, b3;
    JTextField t1, t2;
    JProgressBar progress;
    int num = 0;
    String en = "";

    ceasarclient(final Socket s) {
        super("CLIENT");
        JPanel p = new JPanel(new GridLayout(10, 1));
        setSize(500, 500);
        t1 = new JTextField(30);
        b1 = new JButton("Send");
        b1.setMnemonic('S');
        b2 = new JButton("Close");
        b2.setMnemonic('C');
        l1 = new JLabel("Welcome to Secure Data transfer!");
        l2 = new JLabel("Enter the word here...");
        l3 = new JLabel("");
        l4 = new JLabel("Enter the Key:");
        b3 = new JButton("Encrypt");
        b3.setMnemonic('E');
        t2 = new JTextField(30);
        progress = new JProgressBar(0, 20);
        progress.setValue(0);
        progress.setStringPainted(true);
        p.add(l1);
        p.add(l2);
        p.add(t1);
        p.add(l4);
        p.add(t2);
        p.add(b3);
        p.add(progress);
        p.add(b1);
        p.add(l3);
        p.add(b2);
        add(p);
        setVisible(true);
        b1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
                    pw.println(en);
                } catch (Exception ex) {
                }
                ;
                l3.setText("Encrypted Text Sent.");
            }
        });
        b3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String strw = t1.getText();
                int key = Integer.parseInt(t2.getText());
                int i = 0, j, k;
                while (i < strw.length()) {
                    j = cs.indexOf(strw.charAt(i));
                    k = (j + key) % 26;
                    en = en + cs.charAt(k);
                    i++;
                }
                while (num < 21) {
                    progress.setValue(num);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException exe) {
                    }
                    progress.setValue(num);
                    Rectangle progressRect = progress.getBounds();
                    progressRect.x = 0;
                    progressRect.y = 0;
                    progress.paintImmediately(progressRect);
                    num++;
                }
            }
        });
        b2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        pack();
    }

    public static void main(String args[]) throws IOException {
        final Socket s = new Socket(InetAddress.getLocalHost(), 4321);
        new ceasarclient(s);
    }
}

How to get the path of running java program

Use

System.getProperty("java.class.path")

see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

You can also split it into it's elements easily

String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);

sh: 0: getcwd() failed: No such file or directory on cited drive

if some directory/folder does not exist but somehow you navigated to that directory in that case you can see this Error,

for example:

  • currently, you are in "mno" directory (path = abc/def/ghi/jkl/mno
  • run "sudo su" and delete mno
  • goto the "ghi" directory and delete "jkl" directory
  • now you are in "ghi" directory (path abc/def/ghi)
  • run "exit"
  • after running the "exit", you will get that Error
  • now you will be in "mno"(path = abc/def/ghi/jkl/mno) folder. that does not exist.

so, Generally this Error will show when Directory doesn't exist.

to fix this, simply run "cd;" or you can move to any other directory which exists.

Python if-else short-hand

The most readable way is

x = 10 if a > b else 11

but you can use and and or, too:

x = a > b and 10 or 11

The "Zen of Python" says that "readability counts", though, so go for the first way.

Also, the and-or trick will fail if you put a variable instead of 10 and it evaluates to False.

However, if more than the assignment depends on this condition, it will be more readable to write it as you have:

if A[i] > B[j]:
  x = A[i]
  i += 1
else:
  x = A[j]
  j += 1

unless you put i and j in a container. But if you show us why you need it, it may well turn out that you don't.

Knockout validation

Knockout.js validation is handy but it is not robust. You always have to create server side validation replica. In your case (as you use knockout.js) you are sending JSON data to server and back asynchronously, so you can make user think that he sees client side validation, but in fact it would be asynchronous server side validation.

Take a look at example here upida.cloudapp.net:8080/org.upida.example.knockout/order/create?clientId=1 This is a "Create Order" link. Try to click "save", and play with products. This example is done using upida library (there are spring mvc version and asp.net mvc of this library) from codeplex.

How can I start and check my MySQL log?

Enable general query log by the following query in mysql command line

SET GLOBAL general_log = 'ON';

Now open C:/xampp/mysql/data/mysql.log and check query log

If it fails, open your my.cnf file. For windows its my.ini file and enable it there. Just make sure its in the [mysqld] section

[mysqld]
general_log             = 1

Note: In xampp my.ini file can be either found in xampp\mysql or in c:\windows directory

Read a file in Node.js

Use path.join(__dirname, '/start.html');

var fs = require('fs'),
    path = require('path'),    
    filePath = path.join(__dirname, 'start.html');

fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
    if (!err) {
        console.log('received data: ' + data);
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(data);
        response.end();
    } else {
        console.log(err);
    }
});

Thanks to dc5.

Using if-else in JSP

You may try this example:

_x000D_
_x000D_
<form>_x000D_
  <h1>Hello! I'm duke! What's you name?</h1>_x000D_
  <input type="text" name="user">_x000D_
  <br>_x000D_
  <br>_x000D_
  <input type="submit" value="submit">&nbsp;&nbsp;&nbsp;&nbsp;_x000D_
  <input type="reset">_x000D_
</form>_x000D_
<h1>Hello ${param.user}</h1> _x000D_
<!-- its Expression Language -->
_x000D_
_x000D_
_x000D_

How to vertically align an image inside a div

I have been playing around with using padding for center alignment. You will need to define the top level outer-container size, but the inner container should resize, and you can set the padding at different percentage values.

jsfiddle

<div class='container'>
  <img src='image.jpg' />
</div>

.container {
  padding: 20%;
  background-color: blue;
}

img {
  width: 100%;
}

Adding elements to object

push is an method of arrays , so for object you can get the index of last element ,and you can probably do the same job as push for object as below

var lastIndex = Object.keys(element)[Object.keys(element).length-1];

then add object to the new index of element

element[parseInt(lastIndex) +1] = { id: id, quantity: quantity };

What is the difference between null and System.DBNull.Value?

DataRow has a method that is called IsNull() that you can use to test the column if it has a null value - regarding to the null as it's seen by the database.

DataRow["col"]==null will allways be false.

use

DataRow r;
if (r.IsNull("col")) ...

instead.

SSIS how to set connection string dynamically from a config file

Here's some background on the mechanism you should use, called Package Configurations: Understanding Integration Services Package Configurations. The article describes 5 types of configurations:

  • XML configuration file
  • Environment variable
  • Registry entry
  • Parent package variable
  • SQL Server

Here's a walkthrough of setting up a configuration on a Connection Manager: SQL Server Integration Services SSIS Package Configuration - I do realize this is using an environment variable for the connection string (not a great idea), but the basics are identical to using an XML file. The only step(s) you have to change in that walkthrough are the configuration type, and then a path.

update query with join on two tables

this is Postgres UPDATE JOIN format:

UPDATE address 
SET cid = customers.id
FROM customers 
WHERE customers.id = address.id

Here's the other variations: http://mssql-to-postgresql.blogspot.com/2007/12/updates-in-postgresql-ms-sql-mysql.html

Turn a simple socket into an SSL socket

Here my example ssl socket server threads (multiple connection) https://github.com/breakermind/CppLinux/blob/master/QtSslServerThreads/breakermindsslserver.cpp

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <iostream>

#include <breakermindsslserver.h>

using namespace std;

int main(int argc, char *argv[])
{
    BreakermindSslServer boom;
    boom.Start(123,"/home/user/c++/qt/BreakermindServer/certificate.crt", "/home/user/c++/qt/BreakermindServer/private.key");
    return 0;
}

CSS image resize percentage of itself?

Another solution is to use:

<img srcset="example.png 2x">

It won't validate because the src attribute is required, but it works (except on any version of IE because srcset is not supported).

How to retry after exception?

You can use Python retrying package. Retrying

It is written in Python to simplify the task of adding retry behavior to just about anything.

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

I had this problem with a brand new web service. Solved it by adding read-only access for Everyone on Properties->Security for the folder that the service was in.

Git stash pop- needs merge, unable to refresh index

I was having this issue, then resolving the conflict and commiting, and doing git stash pop again was restoring the same stash again (causing the same conflict :-( ).

What I had to do (WARNING: back up your stash first) is git stash drop to get rid of it.

Initialising mock objects - MockIto

There is a neat way of doing this.

  • If it's an Unit Test you can do this:

    @RunWith(MockitoJUnitRunner.class)
    public class MyUnitTest {
    
        @Mock
        private MyFirstMock myFirstMock;
    
        @Mock
        private MySecondMock mySecondMock;
    
        @Spy
        private MySpiedClass mySpiedClass = new MySpiedClass();
    
        // It's gonna inject the 2 mocks and the spied object per reflection to this object
        // The java doc of @InjectMocks explains it really well how and when it does the injection
        @InjectMocks
        private MyClassToTest myClassToTest;
    
        @Test
        public void testSomething() {
        }
    }
    
  • EDIT: If it's an Integration test you can do this(not intended to be used that way with Spring. Just showcase that you can initialize mocks with diferent Runners):

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("aplicationContext.xml")
    public class MyIntegrationTest {
    
        @Mock
        private MyFirstMock myFirstMock;
    
        @Mock
        private MySecondMock mySecondMock;
    
        @Spy
        private MySpiedClass mySpiedClass = new MySpiedClass();
    
        // It's gonna inject the 2 mocks and the spied object per reflection to this object
        // The java doc of @InjectMocks explains it really well how and when it does the injection
        @InjectMocks
        private MyClassToTest myClassToTest;
    
        @Before
        public void setUp() throws Exception {
              MockitoAnnotations.initMocks(this);
        }
    
        @Test
        public void testSomething() {
        }
    }
    

maxReceivedMessageSize and maxBufferSize in app.config

The currently accepted answer is incorrect. It is NOT required to set maxBufferSize and maxReceivedMessageSize on the client and the server binding. It depends!

If your request is too large (i.e., method parameters of the service operation are memory intensive) set the properties on the server-side, if the response is too large (i.e., the method return value of the service operation is memory intensive) set the values on the client-side.

For the difference between maxBufferSize and maxReceivedMessageSize see MaxBufferSize property?.

Python and pip, list all versions of a package that's available?

Here's my answer that sorts the list inside jq (for those who use systems where sort -V is not avalable) :

$ pythonPackage=certifi
$ curl -Ls https://pypi.org/pypi/$pythonPackage/json | jq -r '.releases | keys_unsorted | sort_by( split(".") | map(tonumber) )'
  ............. 
  "2019.3.9",
  "2019.6.16",
  "2019.9.11",
  "2019.11.28",
  "2020.4.5",
  "2020.4.5.1",
  "2020.4.5.2",
  "2020.6.20",
  "2020.11.8"
]

And to fetch the last version number of the package :

$ curl -Ls https://pypi.org/pypi/$pythonPackage/json | jq -r '.releases | keys_unsorted | sort_by( split(".") | map(tonumber) )[-1]'
2020.11.8

or a bit faster :

$ curl -Ls https://pypi.org/pypi/$pythonPackage/json | jq -r '.releases | keys_unsorted | max_by( split(".") | map(tonumber) )'
2020.11.8

Or even more simple :) :

$ curl -Ls https://pypi.org/pypi/$pythonPackage/json | jq -r .info.version
2020.11.8

How to uninstall downloaded Xcode simulator?

NOTE: This will only remove a device configuration from the Xcode devices list. To remove the simulator files from your hard drive see the previous answer.

For Xcode 7 just use Window \ Devices menu in Xcode:

Devices menu

Then select emulator to delete in the list on the left side and right click on it. Here is Delete option: enter image description here

That's all.

location.host vs location.hostname and cross-browser compatibility?

Your primary question has been answered above. I just wanted to point out that the regex you're using has a bug. It will also succeed on foo-domain.com which is not a subdomain of domain.com

What you really want is this:

/(^|\.)domain\.com$/

Using variables in Nginx location rules

A modified python version of @danack's PHP generate script. It generates all files & folders that live inside of build/ to the parent directory, replacing all {{placeholder}} matches. You need to cd into build/ before running the script.

File structure

build/
-- (files/folders you want to generate)
-- build.py

sites-available/...
sites-enabled/...
nginx.conf
...

build.py

import os, re

# Configurations
target = os.path.join('.', '..')
variables = {
  'placeholder': 'your replacement here'
}


# Loop files
def loop(cb, subdir=''):
  dir = os.path.join('.', subdir);

  for name in os.listdir(dir):
    file = os.path.join(dir, name)
    newsubdir = os.path.join(subdir, name)

    if name == 'build.py': continue
    if os.path.isdir(file): loop(cb, newsubdir)
    else: cb(subdir, name)


# Update file
def replacer(subdir, name):
  dir  = os.path.join(target, subdir)
  file = os.path.join(dir, name)
  oldfile = os.path.join('.', subdir, name)

  with open(oldfile, "r") as fin:
    data = fin.read()

  for key, replacement in variables.iteritems():
    data = re.sub(r"{{\s*" + key + "\s*}}", replacement, data)

  if not os.path.exists(dir):
    os.makedirs(dir)

  with open(file, "w") as fout:
    fout.write(data)


# Start variable replacements.
loop(replacer)

jQuery append text inside of an existing paragraph tag

If you want to append text or html to span then you can do it as below.

$('p span#add_here').append('text goes here');

append will add text to span tag at the end.

to replace entire text or html inside of span you can use .text() or .html()

long long in C/C++

The letters 100000000000 make up a literal integer constant, but the value is too large for the type int. You need to use a suffix to change the type of the literal, i.e.

long long num3 = 100000000000LL;

The suffix LL makes the literal into type long long. C is not "smart" enough to conclude this from the type on the left, the type is a property of the literal itself, not the context in which it is being used.

How do I draw a shadow under a UIView?

To those who failed in getting this to work (As myself!) after trying all the answers here, just make sure Clip Subviews is not enabled at the Attributes inspector...

You are trying to add a non-nullable field 'new_field' to userprofile without a default

If "website" can be empty than new_field should also be set to be empty.

Now if you want to add logic on save where if new_field is empty to grab the value from "website" all you need to do is override the save function for your Model like this:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    website = models.URLField(blank=True, default='DEFAULT VALUE')
    new_field = models.CharField(max_length=140, blank=True, default='DEFAULT VALUE')

    def save(self, *args, **kwargs):
        if not self.new_field:
            # Setting the value of new_field with website's value
            self.new_field = self.website

        # Saving the object with the default save() function
        super(UserProfile, self).save(*args, **kwargs)

CSS3 transition on click using pure CSS

Method #1: CSS :focus pseudo-class

As pure CSS solution, you could achieve sort of the effect by using a tabindex attribute for the image, and :focus pseudo-class as follows:

<img class="crossRotate" src="http://placehold.it/100" tabindex="1" />
.crossRotate {
    outline: 0;
    /* other styles... */
}

.crossRotate:focus {
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}

WORKING DEMO.

Note: Using this approach, the image gets rotated onclick (focused), to negate the rotation, you'll need to click somewhere out of the image (blured).

Method #2: Hidden input & :checked pseudo-class

This is one of my favorite methods. In this approach, there's a hidden checkbox input and a <label> element which wraps the image.

Once you click on the image, the hidden input is checked because of using for attribute for the label.

Hence by using the :checked pseudo-class and adjacent sibling selector +, we could get the image to be rotated:

<input type="checkbox" id="hacky-input">

<label for="hacky-input">
  <img class="crossRotate" src="http://placehold.it/100">
</label>
#hacky-input {
  display: none; /* Hide the input */
}

#hacky-input:checked + label img.crossRotate {
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}

WORKING DEMO #1.

WORKING DEMO #2 (Applying the rotate to the label gives a better experience).

Method #3: Toggling a class via JavaScript

If using JavaScript/jQuery is an option, you could toggle a .active class by .toggleClass() to trigger the rotation effect, as follows:

$('.crossRotate').on('click', function(){
    $(this).toggleClass('active');
});
.crossRotate.active {
    /* vendor-prefixes here... */
    transform: rotate(45deg);
}

WORKING DEMO.

Returning first x items from array

A more object oriented way would be to provide a range to the #[] method. For instance:

Say you want the first 3 items from an array.

numbers = [1,2,3,4,5,6]

numbers[0..2] # => [1,2,3]

Say you want the first x items from an array.

numbers[0..x-1]

The great thing about this method is if you ask for more items than the array has, it simply returns the entire array.

numbers[0..100] # => [1,2,3,4,5,6]

Pandas - Get first row value of a given column

Another way to do this:

first_value = df['Btime'].values[0]

This way seems to be faster than using .iloc:

In [1]: %timeit -n 1000 df['Btime'].values[20]
5.82 µs ± 142 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [2]: %timeit -n 1000 df['Btime'].iloc[20]
29.2 µs ± 1.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

plain count up timer in javascript

The following code works as a count-up timer. It's pure JavaScript code which shows hour:minute:second. It also has a STOP button:

_x000D_
_x000D_
var timerVar = setInterval(countTimer, 1000);
var totalSeconds = 0;
function countTimer() {
           ++totalSeconds;
           var hour = Math.floor(totalSeconds /3600);
           var minute = Math.floor((totalSeconds - hour*3600)/60);
           var seconds = totalSeconds - (hour*3600 + minute*60);
           if(hour < 10)
             hour = "0"+hour;
           if(minute < 10)
             minute = "0"+minute;
           if(seconds < 10)
             seconds = "0"+seconds;
           document.getElementById("timer").innerHTML = hour + ":" + minute + ":" + seconds;
        }

    
_x000D_
<div id="timer"></div>
<div id ="stop_timer" onclick="clearInterval(timerVar)">Stop time</div>
        
        
_x000D_
_x000D_
_x000D_

Google Maps V3 - How to calculate the zoom level for a given bounds

The calculation of the zoom level for the longitudes of Giles Gardam works fine for me. If you want to calculate the zoom factor for latitude, this is an easy solution that works fine:

double minLat = ...;
double maxLat = ...;
double midAngle = (maxLat+minLat)/2;
//alpha is the non-negative angle distance of alpha and beta to midangle
double alpha  = maxLat-midAngle;
//Projection screen is orthogonal to vector with angle midAngle
//portion of horizontal scale:
double yPortion = Math.sin(alpha*Math.pi/180) / 2;
double latZoom = Math.log(mapSize.height / GLOBE_WIDTH / yPortion) / Math.ln2;

//return min (max zoom) of both zoom levels
double zoom = Math.min(lngZoom, latZoom);

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

Incorrect string value: '\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL

Change database charset and collation

ALTER DATABASE
    database_name
    CHARACTER SET = utf8mb4
    COLLATE = utf8mb4_unicode_ci;

change specific table's charset and collation

ALTER TABLE
    table_name
    CONVERT TO CHARACTER SET utf8mb4
    COLLATE utf8mb4_unicode_ci;

change connection charset in mysql driver

before

charset=utf8&parseTime=True&loc=Local

after

charset=utf8mb4&collation=utf8mb4_unicode_ci&parseTime=True&loc=Local

From this article https://hackernoon.com/today-i-learned-storing-emoji-to-mysql-with-golang-204a093454b7

How to remove title bar from the android activity?

Add this two line in your style.xml

<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>

Rebuild all indexes in a Database

Try the following script:

Exec sp_msforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER INDEX ALL ON ? REBUILD'
GO

Also

I prefer(After a long search) to use the following script, it contains @fillfactor determines how much percentage of the space on each leaf-level page is filled with data.

DECLARE @TableName VARCHAR(255)
DECLARE @sql NVARCHAR(500)
DECLARE @fillfactor INT
SET @fillfactor = 80 
DECLARE TableCursor CURSOR FOR
SELECT QUOTENAME(OBJECT_SCHEMA_NAME([object_id]))+'.' + QUOTENAME(name) AS TableName
FROM sys.tables
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER INDEX ALL ON ' + @TableName + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @TableName
END
CLOSE TableCursor
DEALLOCATE TableCursor
GO

for more info, check the following link:

https://blog.sqlauthority.com/2009/01/30/sql-server-2008-2005-rebuild-every-index-of-all-tables-of-database-rebuild-index-with-fillfactor/

and if you want to Check Index Fragmentation on Indexes in a Database, try the following script:

SELECT dbschemas.[name] as 'Schema',
dbtables.[name] as 'Table',
dbindexes.[name] as 'Index',
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
WHERE indexstats.database_id = DB_ID() AND dbtables.[name] like '%%'
ORDER BY indexstats.avg_fragmentation_in_percent desc

For more information, Check the following link:

http://www.schneider-electric.com/en/faqs/FA234246/

How to convert date to timestamp in PHP?

function date_to_stamp( $date, $slash_time = true, $timezone = 'Europe/London', $expression = "#^\d{2}([^\d]*)\d{2}([^\d]*)\d{4}$#is" ) {
    $return = false;
    $_timezone = date_default_timezone_get();
    date_default_timezone_set( $timezone );
    if( preg_match( $expression, $date, $matches ) )
        $return = date( "Y-m-d " . ( $slash_time ? '00:00:00' : "h:i:s" ), strtotime( str_replace( array($matches[1], $matches[2]), '-', $date ) . ' ' . date("h:i:s") ) );
    date_default_timezone_set( $_timezone );
    return $return;
}

// expression may need changing in relation to timezone
echo date_to_stamp('19/03/1986', false) . '<br />';
echo date_to_stamp('19**03**1986', false) . '<br />';
echo date_to_stamp('19.03.1986') . '<br />';
echo date_to_stamp('19.03.1986', false, 'Asia/Aden') . '<br />';
echo date('Y-m-d h:i:s') . '<br />';

//1986-03-19 02:37:30
//1986-03-19 02:37:30
//1986-03-19 00:00:00
//1986-03-19 05:37:30
//2012-02-12 02:37:30

notifyDataSetChanged not working on RecyclerView

Just to complement the other answers as I don't think anyone mentioned this here: notifyDataSetChanged() should be executed on the main thread (other notify<Something> methods of RecyclerView.Adapter as well, of course)

From what I gather, since you have the parsing procedures and the call to notifyDataSetChanged() in the same block, either you're calling it from a worker thread, or you're doing JSON parsing on main thread (which is also a no-no as I'm sure you know). So the proper way would be:

protected void parseResponse(JSONArray response, String url) {
    // insert dummy data for demo
    // <yadda yadda yadda>
    mBusinessAdapter = new BusinessAdapter(mBusinesses);
    // or just use recyclerView.post() or [Fragment]getView().post()
    // instead, but make sure views haven't been destroyed while you were
    // parsing
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        public void run() {
            mBusinessAdapter.notifyDataSetChanged();
        }
    });

}

PS Weird thing is, I don't think you get any indications about the main thread thing from either IDE or run-time logs. This is just from my personal observations: if I do call notifyDataSetChanged() from a worker thread, I don't get the obligatory Only the original thread that created a view hierarchy can touch its views message or anything like that - it just fails silently (and in my case one off-main-thread call can even prevent succeeding main-thread calls from functioning properly, probably because of some kind of race condition)

Moreover, neither the RecyclerView.Adapter api reference nor the relevant official dev guide explicitly mention the main thread requirement at the moment (the moment is 2017) and none of the Android Studio lint inspection rules seem to concern this issue either.

But, here is an explanation of this by the author himself

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

the problem was you have to set

Do you want to make this app and all its live features available to the general public?

set status and review to ON and problem solved

enjoy coding

How do I mount a host directory as a volume in docker compose

Checkout their documentation

From the looks of it you could do the following on your docker-compose.yml

volumes:
    - ./:/app

Where ./ is the host directory, and /app is the target directory for the containers.


EDIT:
Previous documentation source now leads to version history, you'll have to select the version of compose you're using and look for the reference.

For the lazy – v3 / v2 / v1

Side note: Syntax remains the same for all versions as of this edit

SELECT with a Replace()

SELECT *
FROM Contacts
WHERE ContactId IN
    (SELECT a.ContactID
    FROM
        (SELECT ContactId, Replace(Postcode, ' ', '') AS P
        FROM Contacts
        WHERE Postcode LIKE '%N%W%1%0%1%') a
    WHERE a.P LIKE 'NW101%')

ThreeJS: Remove object from scene

I started to save this as a function, and call it as needed for whatever reactions require it:

function Remove(){
    while(scene.children.length > 0){ 
    scene.remove(scene.children[0]); 
}
}

Now you can call the Remove(); function where appropriate.

Common MySQL fields and their appropriate data types

In my experience, first name/last name fields should be at least 48 characters -- there are names from some countries such as Malaysia or India that are very long in their full form.

Phone numbers and postcodes you should always treat as text, not numbers. The normal reason given is that there are postcodes that begin with 0, and in some countries, phone numbers can also begin with 0. But the real reason is that they aren't numbers -- they're identifiers that happen to be made up of numerical digits (and that's ignoring countries like Canada that have letters in their postcodes). So store them in a text field.

In MySQL you can use VARCHAR fields for this type of information. Whilst it sounds lazy, it means you don't have to be too concerned about the right minimum size.

PHP Fatal error when trying to access phpmyadmin mb_detect_encoding

Try to install mysqli and pdo. Put it in terminal:

./configure --with-mysql=/usr/bin/mysql_config  \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd

Good Free Alternative To MS Access

Apache Derby is a nice db alternative.

How to make use of ng-if , ng-else in angularJS

You can write as:

<div class="case" ng-if="mydata.id === '5' ">
    <p> this will execute </p>
</div>
<div class="case" ng-if="mydata.id !== '5' ">
    <p> this will execute </p>
</div> 

How to create a sticky navigation bar that becomes fixed to the top after scrolling

I have found this simple javascript snippet very useful.

$(document).ready(function()
{
    var navbar = $('#navbar');

    navbar.after('<div id="more-div" style="height: ' + navbar.outerHeight(true) + 'px" class="hidden"></div>');
    var afternavbar = $('#more-div');

    var abovenavbar = $('#above-navbar');

    $(window).on('scroll', function()
    {
        if ($(window).scrollTop() > abovenavbar.height())
        {
            navbar.addClass('navbar-fixed-top');
            afternavbar.removeClass('hidden');
        }
        else
        {
            navbar.removeClass('navbar-fixed-top');
            afternavbar.addClass('hidden');
        }
    });
});

Split string in C every white space

Just as an idea of a different style of string manipulation in C, here's an example which does not modify the source string, and does not use malloc. To find spaces I use the libc function strpbrk.

int print_words(const char *string, FILE *f)
{
   static const char space_characters[] = " \t";
   const char *next_space;

   // Find the next space in the string
   //
   while ((next_space = strpbrk(string, space_characters)))
   {
      const char *p;

      // If there are non-space characters between what we found
      // and what we started from, print them.
      //
      if (next_space != string)
      {
         for (p=string; p<next_space; p++)
         {
            if(fputc(*p, f) == EOF)
            {
               return -1;
            }
         }

         // Print a newline
         //
         if (fputc('\n', f) == EOF)
         {
            return -1;
         }
      }

      // Advance next_space until we hit a non-space character
      //
      while (*next_space && strchr(space_characters, *next_space))
      {
         next_space++;
      }

      // Advance the string
      //
      string = next_space;
   }

   // Handle the case where there are no spaces left in the string
   //
   if (*string)
   {
      if (fprintf(f, "%s\n", string) < 0)
      {
         return -1;
      }
   }

   return 0;
}

How to round up the result of integer division?

HOW TO ROUND UP THE RESULT OF INTEGER DIVISION IN C#

I was interested to know what the best way is to do this in C# since I need to do this in a loop up to nearly 100k times. Solutions posted by others using Math are ranked high in the answers, but in testing I found them slow. Jarod Elliott proposed a better tactic in checking if mod produces anything.

int result = (int1 / int2);
if (int1 % int2 != 0) { result++; }

I ran this in a loop 1 million times and it took 8ms. Here is the code using Math:

int result = (int)Math.Ceiling((double)int1 / (double)int2);

Which ran at 14ms in my testing, considerably longer.

How to create .pfx file from certificate and private key?

I know a few users have talked about installing this and that and adding command lines programmes and downloading...

Personally I am lazy and find all these methods cumbersome and slow, plus I don't want to download anything and find the correct cmd lines if I don't have to.

Best way for me on my personal IIS server is to use RapidSSLOnline. This is a tool that's on a server allows you to upload your certificate and private key and is able to generate a pfx file for you that you can directly import into IIS.

The link is here: https://www.rapidsslonline.com/ssl-tools/ssl-converter.php

Below is the steps used for the scenario requested.

  1. Select Current Type = PEM
  2. Change for = PFX
  3. Upload your certificate
  4. Upload your private key
  5. If you have ROOT CA cert or intermediate certs upload them too
  6. Set a password of your choosing, used in IIS
  7. Click the reCaptcha to prove you're not a bot
  8. Click Convert

And that's it you should have a PFX downloaded and use this in your Import process on IIS.

Hope this helps other like minded, lazy tech people.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

Mac install and open mysql using terminal

In the terminal, I typed:

/usr/local/mysql/bin/mysql -u root -p

I was then prompted to enter the temporary password that was given to me upon completion of the installation.

I'm getting an error "invalid use of incomplete type 'class map'

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

Fatal error: unexpectedly found nil while unwrapping an Optional values

I don't know is it bug or something but your labels and other UIs does not initialized automatically when you use custom cell. You should try this in your UICollectionViewController class. It worked for me.

override func viewDidLoad() {
    super.viewDidLoad()

    let nib = UINib(nibName: "<WhateverYourNibName>", bundle: nil)
    self.collectionView.registerNib(nib, forCellReuseIdentifier: "title")
}

"static const" vs "#define" vs "enum"

The difference between static const and #define is that the former uses the memory and the later does not use the memory for storage. Secondly, you cannot pass the address of an #define whereas you can pass the address of a static const. Actually it is depending on what circumstance we are under, we need to select one among these two. Both are at their best under different circumstances. Please don't assume that one is better than the other... :-)

If that would have been the case, Dennis Ritchie would have kept the best one alone... hahaha... :-)

How can I find my php.ini on wordpress?

I am adding an answer based on my experience and also thanks to Michael Cropper and Salman von Abbas for their inputs.

The php.ini file is created when php is installed on the server. I believe that wordpress installation requires php to be installed on the server. So your webhost typically installs it on their server and then sells you the hosting space. Then you install your wordpress on it.

Hence, it follows clearly from this that the php.ini file will not be present in the wp-admin folder.

So you need to look for it either at your root folder (but most likely it won't be there if you're on a shared webhosting plan). Then you need to create a file as such:

create a new file in the location = /public_html/your_domain/any_name.php

Put the following code inside the file:

<?php
$inipath = php_ini_loaded_file();

if ($inipath) {
    echo 'Loaded php.ini: ' . $inipath;
} else {
    echo 'A php.ini file is not loaded';
}

Now try to access the file through your browser as follows:

https://your_domain/any_name.php

This should show a message that clearly states the location of your php.ini file.

If you're on a shared hosting plan then you probably won't have access to this folder. You will need to inform the web hosting support to take care of this for you.

Hope this helps!

What's the difference between a POST and a PUT HTTP REQUEST?

PUT is meant as a a method for "uploading" stuff to a particular URI, or overwriting what is already in that URI.

POST, on the other hand, is a way of submitting data RELATED to a given URI.

Refer to the HTTP RFC

How can I list all tags for a Docker image on a remote registry?

I've managed to get it working using curl:

curl -u <username>:<password> https://myrepo.example/v1/repositories/<username>/<image_name>/tags

Note that image_name should not contain user details etc. For example if you're pushing image named myrepo.example/username/x then image_name should be x.

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

You can consider to replace default WordPress jQuery script with Google Library by adding something like the following into theme functions.php file:

function modify_jquery() {
    if (!is_admin()) {
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false, '1.10.2');
        wp_enqueue_script('jquery');
    }
}
add_action('init', 'modify_jquery');

Code taken from here: http://www.wpbeginner.com/wp-themes/replace-default-wordpress-jquery-script-with-google-library/

Generating a drop down list of timezones with PHP

Despite the number of existing answers, I've made yet another solution to this problem. The pro's of my implementation are:

  • The list of timezones is generated dynamically, and thus automatically updates when timezones might change (in PHP).
  • Timezone names are prettified. For example, "America/St_Barthelemy" becomes "America, St. Barthelemy".
  • Timezones are sorted on offset and name. Toland's answer only sorts on offset, resulting in unsorted groups of timezones within the same offset.
  • Offset information is not retrieved from DateTimeZone::listAbbreviations, since that method also returns historical timezone information. Favio's answer does use this method, which results in incorrect (historical) offsets
  • The list of timezones is only generated when first requested (and 'cached' using a static variable).

Here is the full code:

function timezone_list() {
    static $timezones = null;

    if ($timezones === null) {
        $timezones = [];
        $offsets = [];
        $now = new DateTime('now', new DateTimeZone('UTC'));

        foreach (DateTimeZone::listIdentifiers() as $timezone) {
            $now->setTimezone(new DateTimeZone($timezone));
            $offsets[] = $offset = $now->getOffset();
            $timezones[$timezone] = '(' . format_GMT_offset($offset) . ') ' . format_timezone_name($timezone);
        }

        array_multisort($offsets, $timezones);
    }

    return $timezones;
}

function format_GMT_offset($offset) {
    $hours = intval($offset / 3600);
    $minutes = abs(intval($offset % 3600 / 60));
    return 'GMT' . ($offset ? sprintf('%+03d:%02d', $hours, $minutes) : '');
}

function format_timezone_name($name) {
    $name = str_replace('/', ', ', $name);
    $name = str_replace('_', ' ', $name);
    $name = str_replace('St ', 'St. ', $name);
    return $name;
}

And here's an example of the output

Array
(
    [Pacific/Midway]    => (GMT-11:00) Pacific, Midway
    [Pacific/Niue]      => (GMT-11:00) Pacific, Niue
    [Pacific/Pago_Pago] => (GMT-11:00) Pacific, Pago Pago
    [America/Adak]      => (GMT-10:00) America, Adak
    [Pacific/Honolulu]  => (GMT-10:00) Pacific, Honolulu
    [Pacific/Johnston]  => (GMT-10:00) Pacific, Johnston
    [Pacific/Rarotonga] => (GMT-10:00) Pacific, Rarotonga
    [Pacific/Tahiti]    => (GMT-10:00) Pacific, Tahiti
    [Pacific/Marquesas] => (GMT-09:30) Pacific, Marquesas
    [America/Anchorage] => (GMT-09:00) America, Anchorage
    ...
)

How to copy directories in OS X 10.7.3?

Is there something special with that directory or are you really just asking how to copy directories?

Copy recursively via CLI:

cp -R <sourcedir> <destdir>

If you're only seeing the files under the sourcedir being copied (instead of sourcedir as well), that's happening because you kept the trailing slash for sourcedir:

cp -R <sourcedir>/ <destdir>

The above only copies the files and their directories inside of sourcedir. Typically, you want to include the directory you're copying, so drop the trailing slash:

cp -R <sourcedir> <destdir>

How to increment datetime by custom months in python without using library

from datetime import timedelta
try:
    next = (x.replace(day=1) + timedelta(days=31)).replace(day=x.day)
except ValueError:  # January 31 will return last day of February.
    next = (x + timedelta(days=31)).replace(day=1) - timedelta(days=1)

If you simply want the first day of the next month:

next = (x.replace(day=1) + timedelta(days=31)).replace(day=1)

How to iterate over array of objects in Handlebars?

I had a similar issue I was getting the entire object in this but the value was displaying while doing #each.

Solution: I re-structure my array of object like this:

let list = results.map((item)=>{
    return { name:item.name, author:item.author }
});

and then in template file:

{{#each list}}
    <tr>
        <td>{{name }}</td>
        <td>{{author}}</td>      
    </tr>
{{/each}} 

C++ Dynamic Shared Library on Linux

The following shows an example of a shared class library shared.[h,cpp] and a main.cpp module using the library. It's a very simple example and the makefile could be made much better. But it works and may help you:

shared.h defines the class:

class myclass {
   int myx;

  public:

    myclass() { myx=0; }
    void setx(int newx);
    int  getx();
};

shared.cpp defines the getx/setx functions:

#include "shared.h"

void myclass::setx(int newx) { myx = newx; }
int  myclass::getx() { return myx; }

main.cpp uses the class,

#include <iostream>
#include "shared.h"

using namespace std;

int main(int argc, char *argv[])
{
  myclass m;

  cout << m.getx() << endl;
  m.setx(10);
  cout << m.getx() << endl;
}

and the makefile that generates libshared.so and links main with the shared library:

main: libshared.so main.o
    $(CXX) -o main  main.o -L. -lshared

libshared.so: shared.cpp
    $(CXX) -fPIC -c shared.cpp -o shared.o
    $(CXX) -shared  -Wl,-soname,libshared.so -o libshared.so shared.o

clean:
    $rm *.o *.so

To actual run 'main' and link with libshared.so you will probably need to specify the load path (or put it in /usr/local/lib or similar).

The following specifies the current directory as the search path for libraries and runs main (bash syntax):

export LD_LIBRARY_PATH=.
./main

To see that the program is linked with libshared.so you can try ldd:

LD_LIBRARY_PATH=. ldd main

Prints on my machine:

  ~/prj/test/shared$ LD_LIBRARY_PATH=. ldd main
    linux-gate.so.1 =>  (0xb7f88000)
    libshared.so => ./libshared.so (0xb7f85000)
    libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb7e74000)
    libm.so.6 => /lib/libm.so.6 (0xb7e4e000)
    libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb7e41000)
    libc.so.6 => /lib/libc.so.6 (0xb7cfa000)
    /lib/ld-linux.so.2 (0xb7f89000)

Get first element from a dictionary

For anyone coming to this that wants a linq-less way to get an element from a dictionary

var d = new Dictionary<string, string>();
d.Add("a", "b");
var e = d.GetEnumerator();
e.MoveNext();
var anElement = e.Current;
// anElement/e.Current is a KeyValuePair<string,string>
// where Key = "a", Value = "b"

I'm not sure if this is implementation specific, but if your Dictionary doesn't have any elements, Current will contain a KeyValuePair<string, string> where both the key and value are null.

(I looked at the logic behind linq's First method to come up with this, and tested it via LinqPad 4)

Select a Dictionary<T1, T2> with LINQ

The extensions methods also provide a ToDictionary extension. It is fairly simple to use, the general usage is passing a lambda selector for the key and getting the object as the value, but you can pass a lambda selector for both key and value.

class SomeObject
{
    public int ID { get; set; }
    public string Name { get; set; }
}

SomeObject[] objects = new SomeObject[]
{
    new SomeObject { ID = 1, Name = "Hello" },
    new SomeObject { ID = 2, Name = "World" }
};

Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);

Then objectDictionary[1] Would contain the value "Hello"

belongs_to through associations

The has_many :choices creates an association named choices, not choice. Try using current_user.choices instead.

See the ActiveRecord::Associations documentation for information about about the has_many magic.

Creating a Facebook share button with customized url, title and image

This is the code as 2017:

<i class="fa fa-facebook-square"></i>
<a href="#" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(location.href),'facebook-share-dialog','width=626,height=436');return false;">Share on Facebook</a>

Facebook now takes all data from OG metatags.

NOTE: This code assumes you have OG metatags on in site's code.

Source

Read a plain text file with php

You can read a group of txt files in a folder and echo the contents like this.

 <?php
$directory = "folder/";
$dir = opendir($directory);
$filenames = [];
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if($type !== 'file') continue;
$filenames[] = $filename;
}
closedir($dir);
?>

Passing parameters to JavaScript files

Check out this URL. It is working perfectly for the requirement.

http://feather.elektrum.org/book/src.html

Thanks a lot to the author. For quick reference I pasted the main logic below:

var scripts = document.getElementsByTagName('script');
var myScript = scripts[ scripts.length - 1 ];

var queryString = myScript.src.replace(/^[^\?]+\??/,'');

var params = parseQuery( queryString );

function parseQuery ( query ) {
  var Params = new Object ();
  if ( ! query ) return Params; // return empty object
  var Pairs = query.split(/[;&]/);
  for ( var i = 0; i < Pairs.length; i++ ) {
    var KeyVal = Pairs[i].split('=');
    if ( ! KeyVal || KeyVal.length != 2 ) continue;
    var key = unescape( KeyVal[0] );
    var val = unescape( KeyVal[1] );
    val = val.replace(/\+/g, ' ');
    Params[key] = val;
  }
  return Params;
}

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

How does numpy.histogram() work?

A bin is range that represents the width of a single bar of the histogram along the X-axis. You could also call this the interval. (Wikipedia defines them more formally as "disjoint categories".)

The Numpy histogram function doesn't draw the histogram, but it computes the occurrences of input data that fall within each bin, which in turns determines the area (not necessarily the height if the bins aren't of equal width) of each bar.

In this example:

 np.histogram([1, 2, 1], bins=[0, 1, 2, 3])

There are 3 bins, for values ranging from 0 to 1 (excl 1.), 1 to 2 (excl. 2) and 2 to 3 (incl. 3), respectively. The way Numpy defines these bins if by giving a list of delimiters ([0, 1, 2, 3]) in this example, although it also returns the bins in the results, since it can choose them automatically from the input, if none are specified. If bins=5, for example, it will use 5 bins of equal width spread between the minimum input value and the maximum input value.

The input values are 1, 2 and 1. Therefore, bin "1 to 2" contains two occurrences (the two 1 values), and bin "2 to 3" contains one occurrence (the 2). These results are in the first item in the returned tuple: array([0, 2, 1]).

Since the bins here are of equal width, you can use the number of occurrences for the height of each bar. When drawn, you would have:

  • a bar of height 0 for range/bin [0,1] on the X-axis,
  • a bar of height 2 for range/bin [1,2],
  • a bar of height 1 for range/bin [2,3].

You can plot this directly with Matplotlib (its hist function also returns the bins and the values):

>>> import matplotlib.pyplot as plt
>>> plt.hist([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]), <a list of 3 Patch objects>)
>>> plt.show()

enter image description here

How to force maven update?

We can force to get latest update of release and snapshot repository with below command :

mvn --update-snapshots clean install

What is a Python egg?

The .egg file is a distribution format for Python packages. It’s just an alternative to a source code distribution or Windows exe. But note that for pure Python, the .egg file is completely cross-platform.

The .egg file itself is essentially a .zip file. If you change the extension to “zip”, you can see that it will have folders inside the archive.

Also, if you have an .egg file, you can install it as a package using easy_install

Example: To create an .egg file for a directory say mymath which itself may have several python scripts, do the following step:

# setup.py
from setuptools import setup, find_packages
setup(
    name = "mymath",
    version = "0.1",
    packages = find_packages()
    )

Then, from the terminal do:

 $ python setup.py bdist_egg

This will generate lot of outputs, but when it’s completed you’ll see that you have three new folders: build, dist, and mymath.egg-info. The only folder that we care about is the dist folder where you'll find your .egg file, mymath-0.1-py3.5.egg with your default python (installation) version number(mine here: 3.5)

Source: Python library blog

jQuery: how to scroll to certain anchor/div on page load?

    /* START --- scroll till anchor */
        (function($) {
             $.fn.goTo = function() {
                  var top_menu_height=$('#div_menu_header').height() + 5 ;
                  //alert ( 'top_menu_height is:' + top_menu_height );
                  $('html, body').animate({
                        scrollTop: (-1)*top_menu_height + $(this).offset().top + 'px'
                  }, 500);
                  return this; // for chaining...
             }
        })(jQuery);

        $(document).ready(function(){

          var url = document.URL, idx = url.indexOf("#") ;
          var hash = idx != -1 ? url.substring(idx+1) : "";

          $(window).load(function(){
             // Remove the # from the hash, as different browsers may or may not include it
             var anchor_to_scroll_to = location.hash.replace('#','');
             if ( anchor_to_scroll_to != '' ) {
                 anchor_to_scroll_to = '#' + anchor_to_scroll_to ;
                 $(anchor_to_scroll_to).goTo();
             }
            });
        });
    /* STOP --- scroll till anchror */

JavaScript get child element

ULs don't have a name attribute, but you can reference the ul by tag name.

Try replacing line 3 in your script with this:

var sub = cat.getElementsByTagName("UL");

How to fix "unable to write 'random state' " in openssl

I did not find where the .rnd file is so I ran the cmd as administrator and it worked like a charm.

How to select first parent DIV using jQuery?

Use .closest(), which gets the first ancestor element that matches the given selector 'div':

var classes = $(this).closest('div').attr('class').split(' ');

EDIT:

As @Shef noted, .closest() will return the current element if it happens to be a DIV also. To take that into account, use .parent() first:

var classes = $(this).parent().closest('div').attr('class').split(' ');

How to scroll up or down the page to an anchor using jQuery?

Ok simplest method is : -

Within the click function (Jquery) : -

$('html,body').animate({scrollTop: $("#resultsdiv").offset().top},'slow');

HTML

<div id="resultsdiv">Where I want to scroll to</div>

How do I add the Java API documentation to Eclipse?

I went through the same problem and I did not find some of the above answer useful because they are old and with new JDK 1.8 , documentation section has been moved to src.zip in JDK folder (C:\Program Files\Java\jdk1.8.0_101 ) .

Now I tried everything from above and it was showing me the same problem if I press ctrl and click on (for example String or System) in my program I get the Source not found.

Now you can do this, go to the folder where JDK (C:\Program Files\Java\jdk1.8.0_101) is installed and try to unzip src.zip. Here you might face an issue as sometime due to administrative rights on this folder it would not allow you to unzip this src.zip. For solving the issue , copy src.zip and paste in any other folder ( example Desktop) and then create a folder src and unzip in it. Now copy this folder back to JDK 1.8 folder**(C:\Program Files\Java\jdk1.8.0_101).**

Now just go to eclipse and open any program and press ctrl and click on any external objects or anything (for example String or System) .You will get Source not found , Now Click Attach source -> External Location -> External Folder and add your src location (C:\Program Files\Java\jdk1.8.0_101\src). Now you are good to go , I tried and it worked for me.

All the above folder location are from my system , so It might be different for you.

How to create and write to a txt file using VBA

Dim SaveVar As Object

Sub Main()

    Console.WriteLine("Enter Text")

    Console.WriteLine("")

    SaveVar = Console.ReadLine

    My.Computer.FileSystem.WriteAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt", "Text: " & SaveVar & ", ", True)

    Console.WriteLine("")

    Console.WriteLine("File Saved")

    Console.WriteLine("")

    Console.WriteLine(My.Computer.FileSystem.ReadAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt"))
    Console.ReadLine()

End Sub()

When to use 'raise NotImplementedError'?

One could also do a raise NotImplementedError() inside the child method of an @abstractmethod-decorated base class method.


Imagine writing a control script for a family of measurement modules (physical devices). The functionality of each module is narrowly-defined, implementing just one dedicated function: one could be an array of relays, another a multi-channel DAC or ADC, another an ammeter etc.

Much of the low-level commands in use would be shared between the modules for example to read their ID numbers or to send a command to them. Let's see what we have at this point:

Base Class

from abc import ABC, abstractmethod  #< we'll make use of these later

class Generic(ABC):
    ''' Base class for all measurement modules. '''

    # Shared functions
    def __init__(self):
        # do what you must...

    def _read_ID(self):
        # same for all the modules

    def _send_command(self, value):
        # same for all the modules

Shared Verbs

We then realise that much of the module-specific command verbs and, therefore, the logic of their interfaces is also shared. Here are 3 different verbs whose meaning would be self-explanatory considering a number of target modules.

  • get(channel)

  • relay: get the on/off status of the relay on channel

  • DAC: get the output voltage on channel

  • ADC: get the input voltage on channel

  • enable(channel)

  • relay: enable the use of the relay on channel

  • DAC: enable the use of the output channel on channel

  • ADC: enable the use of the input channel on channel

  • set(channel)

  • relay: set the relay on channel on/off

  • DAC: set the output voltage on channel

  • ADC: hmm... nothing logical comes to mind.


Shared Verbs Become Enforced Verbs

I'd argue that there is a strong case for the above verbs to be shared across the modules as we saw that their meaning is evident for each one of them. I'd continue writing my base class Generic like so:

class Generic(ABC):  # ...continued
    
    @abstractmethod
    def get(self, channel):
        pass

    @abstractmethod
    def enable(self, channel):
        pass

    @abstractmethod
    def set(self, channel):
        pass

Subclasses

We now know that our subclasses will all have to define these methods. Let's see what it could look like for the ADC module:

class ADC(Generic):

    def __init__(self):
        super().__init__()  #< applies to all modules
        # more init code specific to the ADC module
    
    def get(self, channel):
        # returns the input voltage measured on the given 'channel'

    def enable(self, channel):
        # enables accessing the given 'channel'

You may now be wondering:

But this won't work for the ADC module as set makes no sense there as we've just seen this above!

You're right: not implementing set is not an option as Python would then fire the error below when you tried to instantiate your ADC object.

TypeError: Can't instantiate abstract class 'ADC' with abstract methods 'set'

So you must implement something, because we made set an enforced verb (aka '@abstractmethod'), which is shared by two other modules but, at the same time, you must also not implement anything as set does not make sense for this particular module.

NotImplementedError to the Rescue

By completing the ADC class like this:

class ADC(Generic): # ...continued

    def set(self, channel):
        raise NotImplementedError("Can't use 'set' on an ADC!")

You are doing three very good things at once:

  1. You are protecting a user from erroneously issuing a command ('set') that is not (and shouldn't!) be implemented for this module.
  2. You are telling them explicitly what the problem is (see TemporalWolf's link about 'Bare exceptions' for why this is important)
  3. You are protecting the implementation of all the other modules for which the enforced verbs do make sense. I.e. you ensure that those modules for which these verbs do make sense will implement these methods and that they will do so using exactly these verbs and not some other ad-hoc names.

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Quote: I would like to know how to display the div in the middle of the screen, whether user has scrolled up/down.

Change

position: absolute;

To

position: fixed;

W3C specifications for position: absolute and for position: fixed.

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

On OSX and VSCode 1.50.0 all I had to do was to close and restart VSCode and the problem went away.

Extracting the top 5 maximum values in excel

Put the data into a Pivot Table and do a top n filter on it

Excel Demo

Oracle Insert via Select from multiple tables where one table may not have a row

insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)
select account_type_standard_seq.nextval,
   ts.tax_status_id, 
   ( select r.recipient_id
     from recipient r
     where r.recipient_code = ?
   )
from tax_status ts
where ts.tax_status_code = ?

Can Flask have optional URL parameters?

@user.route('/<userId>/')  # NEED '/' AFTER LINK
@user.route('/<userId>/<username>')
def show(userId, username=None):
    pass

https://flask.palletsprojects.com/en/1.1.x/quickstart/#unique-urls-redirection-behavior

How to use WinForms progress bar?

I would suggest you have a look at BackgroundWorker. If you have a loop that large in your WinForm it will block and your app will look like it has hanged.

Look at BackgroundWorker.ReportProgress() to see how to report progress back to the UI thread.

For example:

private void Calculate(int i)
{
    double pow = Math.Pow(i, i);
}

private void button1_Click(object sender, EventArgs e)
{
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;
    progressBar1.Value = 0;
    backgroundWorker.RunWorkerAsync();
}

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    var backgroundWorker = sender as BackgroundWorker;
    for (int j = 0; j < 100000; j++)
    {
        Calculate(j);
        backgroundWorker.ReportProgress((j * 100) / 100000);
    }
}

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // TODO: do something with final calculation.
}

Perl read line by line

#!/usr/bin/perl
use utf8                       ;
use 5.10.1                     ;
use strict                     ;
use autodie                    ;
use warnings FATAL => q  ?all?;
binmode STDOUT     => q ?:utf8?;                  END {
close   STDOUT                 ;                     }
our    $FOLIO      =  q + SnPmaster.txt +            ;
open    FOLIO                  ;                 END {
close   FOLIO                  ;                     }
binmode FOLIO      => q{       :crlf
                               :encoding(CP-1252)    };
while (<FOLIO>)  { print       ;                     }
       continue  { ${.} ^015^  __LINE__  ||   exit   }
                                                                                                                                                                                                                                              __END__
unlink  $FOLIO                 ;
unlink ~$HOME ||
  clri ~$HOME                  ;
reboot                         ;

Splitting a dataframe string column into multiple different columns

A very direct way is to just use read.table on your character vector:

> read.table(text = text, sep = ".", colClasses = "character")
   V1 V2  V3  V4
1   F US CLE V13
2   F US CA6 U13
3   F US CA6 U13
4   F US CA6 U13
5   F US CA6 U13
6   F US CA6 U13
7   F US CA6 U13
8   F US CA6 U13
9   F US  DL U13
10  F US  DL U13
11  F US  DL U13
12  F US  DL Z13
13  F US  DL Z13

colClasses needs to be specified, otherwise F gets converted to FALSE (which is something I need to fix in "splitstackshape", otherwise I would have recommended that :) )


Update (> a year later)...

Alternatively, you can use my cSplit function, like this:

cSplit(as.data.table(text), "text", ".")
#     text_1 text_2 text_3 text_4
#  1:      F     US    CLE    V13
#  2:      F     US    CA6    U13
#  3:      F     US    CA6    U13
#  4:      F     US    CA6    U13
#  5:      F     US    CA6    U13
#  6:      F     US    CA6    U13
#  7:      F     US    CA6    U13
#  8:      F     US    CA6    U13
#  9:      F     US     DL    U13
# 10:      F     US     DL    U13
# 11:      F     US     DL    U13
# 12:      F     US     DL    Z13
# 13:      F     US     DL    Z13

Or, separate from "tidyr", like this:

library(dplyr)
library(tidyr)

as.data.frame(text) %>% separate(text, into = paste("V", 1:4, sep = "_"))
#    V_1 V_2 V_3 V_4
# 1    F  US CLE V13
# 2    F  US CA6 U13
# 3    F  US CA6 U13
# 4    F  US CA6 U13
# 5    F  US CA6 U13
# 6    F  US CA6 U13
# 7    F  US CA6 U13
# 8    F  US CA6 U13
# 9    F  US  DL U13
# 10   F  US  DL U13
# 11   F  US  DL U13
# 12   F  US  DL Z13
# 13   F  US  DL Z13

ImportError: No module named request

The SpeechRecognition library requires Python 3.3 or up:

Requirements

[...]

The first software requirement is Python 3.3 or better. This is required to use the library.

and from the Trove classifiers:

Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4

The urllib.request module is part of the Python 3 standard library; in Python 2 you'd use urllib2 here.

How to define an enum with string value?

I wish there were a more elegant solution, like just allowing string type enum in the language level, but it seems that it is not supported yet. The code below is basically the same idea as other answers, but I think it is shorter and it can be reused. All you have to do is adding a [Description("")] above each enum entry and add a class that has 10 lines.

The class:

public static class Extensions
{
    public static string ToStringValue(this Enum en)
    {
        var type = en.GetType();
        var memInfo = type.GetMember(en.ToString());
        var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
        var stringValue = ((DescriptionAttribute)attributes[0]).Description;
        return stringValue;
    }
}

Usage:

    enum Country
    {
        [Description("Deutschland")]
        Germany,
        [Description("Nippon")]
        Japan,
        [Description("Italia")]
        Italy,
    }

    static void Main(string[] args)
    {
        Show(new[] {Country.Germany, Country.Japan, Country.Italy});

        void Show(Country[] countries)
        {
            foreach (var country in countries)
            {
                Debug.WriteLine(country.ToStringValue());
            }
        }
    }

How to turn off caching on Firefox?

In higher versions of Firefox, like Nightly, there is an options named "disable cache", you can find it by clicking the gear. And that options works only in current session, which means when you close inspector and restart it, you have to check it again if you want catch disabled.

How to Set OnClick attribute with value containing function in ie8?

You don't need to use setAttribute for that - This code works (IE8 also)

<div id="something" >Hello</div>
<script type="text/javascript" >
    (function() {
        document.getElementById("something").onclick = function() { 
            alert('hello'); 
        };
    })();
</script>

Convert number to varchar in SQL with formatting

Here's an alternative following the last answer

declare @t tinyint,@v tinyint
set @t=23
set @v=232
Select replace(str(@t,4),' ','0'),replace(str(@t,5),' ','0')

This will work on any number and by varying the length of the str() function you can stipulate how many leading zeros you require. Provided of course that your string length is always >= maximum number of digits your number type can hold.

How to specify the default error page in web.xml?

On Servlet 3.0 or newer you could just specify

<web-app ...>
    <error-page>
        <location>/general-error.html</location>
    </error-page>
</web-app>

But as you're still on Servlet 2.5, there's no other way than specifying every common HTTP error individually. You need to figure which HTTP errors the enduser could possibly face. On a barebones webapp with for example the usage of HTTP authentication, having a disabled directory listing, using custom servlets and code which can possibly throw unhandled exceptions or does not have all methods implemented, then you'd like to set it for HTTP errors 401, 403, 500 and 503 respectively.

<error-page>
    <!-- Missing login -->
    <error-code>401</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Forbidden directory listing -->
    <error-code>403</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Missing resource -->
    <error-code>404</error-code>
    <location>/Error404.html</location>
</error-page>
<error-page>
    <!-- Uncaught exception -->
    <error-code>500</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Unsupported servlet method -->
    <error-code>503</error-code>
    <location>/general-error.html</location>
</error-page>

That should cover the most common ones.

Copy directory contents into a directory with python

You can also use glob2 to recursively collect all paths (using ** subfolders wildcard) and then use shutil.copyfile, saving the paths

glob2 link: https://code.activestate.com/pypm/glob2/

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

For Intellij IDEA version 11.0.2

File | Project Structure | Artifacts then you should press alt+insert or click the plus icon and create new artifact choose --> jar --> From modules with dependencies.

Next goto Build | Build artifacts --> choose your artifact.

source: http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/

How to remove an id attribute from a div using jQuery?

The capitalization is wrong, and you have an extra argument.

Do this instead:

$('img#thumb').removeAttr('id');

For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.

What is the best way to left align and right align two div tags?

<div style="float: left;">Left Div</div>
<div style="float: right;">Right Div</div>

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

I was facing same problem when I installed JRE by Oracle and solved this problem after my research.

I moved the environment path C:\Program Files (x86)\Common Files\Oracle\Java\javapath below H:\Program Files\Java\jdk-13.0.1\bin

Like this:

Path

H:\Program Files\Java\jdk-13.0.1\bin
C:\Program Files (x86)\Common Files\Oracle\Java\javapath

OR

Path

%JAVA_HOME%
%JRE_HOME%

How to remove a TFS Workspace Mapping?

You don't have to delete the entire Cache folder. you lose all settings / preferences The workspace mappings are stored in a file called:

VersionControl.config under the users local settings/application data directory. located here in windows 7:

%LocalAppData%\Microsoft\Team Foundation\x.0\Cache\Volatile

where x= 3.0,4.0, 5.0,6.0 etc.

Inside this you will find guid named folders , open each of them, manually editing the forementioned file, to remove the workspace mapping(directory path will be present in mappedpaths attribute) from that local folder to the TFS server (which is no longer in usage).

'was not declared in this scope' error

Here's a simplified example based on of your problem:

if (test) 
{//begin scope 1
    int y = 1; 
}//end scope 1
else 
{//begin scope 2
    int y = 2;//error, y is not in scope
}//end scope 2
int x = y;//error, y is not in scope

In the above version you have a variable called y that is confined to scope 1, and another different variable called y that is confined to scope 2. You then try to refer to a variable named y after the end of the if, and not such variable y can be seen because no such variable exists in that scope.

You solve the problem by placing y in the outermost scope which contains all references to it:

int y;
if (test) 
{
    y = 1; 
}
else 
{
    y = 2;
}
int x = y;

I've written the example with simplified made up code to make it clearer for you to understand the issue. You should now be able to apply the principle to your code.

What properties can I use with event.target?

//Do it like---
function dragStart(this_,event) {
    var row=$(this_).attr('whatever');
    event.dataTransfer.setData("Text", row);
}

How to create a remote Git repository from a local one?

A note for people who created the local copy on Windows and want to create a corresponding remote repository on a Unix-line system, where text files get LF endings on further clones by developers on Unix-like systems, but CRLF endings on Windows.

If you created your Windows repository before setting up line-ending translation then you have a problem. Git's default setting is no translation, so your working set uses CRLF but your repository (i.e. the data stored under .git) has saved the files as CRLF too.

When you push to the remote, the saved files are copied as-is, no line ending translation occurs. (Line ending translation occurs when files are commited to a repository, not when repositories are pushed). You end up with CRLF in your Unix-like repository, which is not what you want.

To get LF in the remote repository you have to make sure LF is in the local repository first, by re-normalizing your Windows repository. This will have no visible effect on your Windows working set, which still has CRLF endings, however when you push to remote, the remote will get LF correctly.

I'm not sure if there's an easy way to tell what line endings you have in your Windows repository - I guess you could test it by setting core.autocrlf=false and then cloning (If the repo has LF endings, the clone will have LF too).

What is the difference between Class.getResource() and ClassLoader.getResource()?

Had to look it up in the specs:

Class's getResource() - documentation states the difference:

This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource.

canvas.toDataURL() SecurityError

Just use the crossOrigin attribute and pass 'anonymous' as the second parameter

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;

PDOException SQLSTATE[HY000] [2002] No such file or directory

I encountered the [PDOException] SQLSTATE[HY000] [2002] No such file or directory error for a different reason. I had just finished building a brand new LAMP stack on Ubuntu 12.04 with Apache 2.4.7, PHP v5.5.10 and MySQL 5.6.16. I moved my sites back over and fired them up. But, I couldn't load my Laravel 4.2.x based site because of the [PDOException] above. So, I checked php -i | grep pdo and noticed this line:

pdo_mysql.default_socket => /tmp/mysql.sock => /tmp/mysql.sock

But, in my /etc/my.cnf the sock file is actually in /var/run/mysqld/mysqld.sock.

So, I opened up my php.ini and set the value for pdo_mysql.default_socket:

pdo_mysql.default_socket=/var/run/mysqld/mysqld.sock

Then, I restarted apache and checked php -i | grep pdo:

pdo_mysql.default_socket => /var/run/mysqld/mysqld.sock => /var/run/mysqld/mysqld.sock

That fixed it for me.

Get a worksheet name using Excel VBA

You can use below code to get the Active Sheet name and change it to yours preferred name.

Sub ChangeSheetName()

Dim shName As String
Dim currentName As String
currentName = ActiveSheet.Name
shName = InputBox("What name you want to give for your sheet")
ThisWorkbook.Sheets(currentName).Name = shName

End Sub

Getting file names without extensions

Below is my code to get a picture to load into a PictureBox and Display a Picture name in to a TextBox without Extension.

private void browse_btn_Click(object sender, EventArgs e)
    {
        OpenFileDialog Open = new OpenFileDialog();
        Open.Filter = "image files|*.jpg;*.png;*.gif;*.icon;.*;";
        if (Open.ShowDialog() == DialogResult.OK)
        {
            imageLocation = Open.FileName.ToString();
            string picTureName = null;
            picTureName = Path.ChangeExtension(Path.GetFileName(imageLocation), null);

            pictureBox_Gift.ImageLocation = imageLocation;
            GiftName_txt.Text = picTureName.ToString();
            Savebtn.Enabled = true;
        }
    }

VBScript -- Using error handling

Note that On Error Resume Next is not set globally. You can put your unsafe part of code eg into a function, which will interrupted immediately if error occurs, and call this function from sub containing precedent OERN statement.

ErrCatch()

Sub ErrCatch()
    Dim Res, CurrentStep

    On Error Resume Next

    Res = UnSafeCode(20, CurrentStep)
    MsgBox "ErrStep " & CurrentStep & vbCrLf & Err.Description

End Sub

Function UnSafeCode(Arg, ErrStep)

    ErrStep = 1
    UnSafeCode = 1 / (Arg - 10)

    ErrStep = 2
    UnSafeCode = 1 / (Arg - 20)

    ErrStep = 3
    UnSafeCode = 1 / (Arg - 30)

    ErrStep = 0
End Function

Garbage collector in Android

There is no need to call the garbage collector after an OutOfMemoryError.

It's Javadoc clearly states:

Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

So, the garbage collector already tried to free up memory before generating the error but was unsuccessful.

Why do I get access denied to data folder when using adb?

This works if your Android device is rooted by any means (not sure if it works for non-rooted).

  1. adb shell - access the shell
  2. su - become the superuser.

You can now read all files in all directories.

ORACLE and TRIGGERS (inserted, updated, deleted)

Separate it into 2 triggers. One for the deletion and one for the insertion\ update.

Eclipse: How do I add the javax.servlet package to a project?

  1. Download the file from http://www.java2s.com/Code/Jar/STUVWXYZ/Downloadjavaxservletjar.htm

  2. Make a folder ("lib") inside the project folder and move that jar file to there.

  3. In Eclipse, right click on project > BuildPath > Configure BuildPath > Libraries > Add External Jar

Thats all

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

PostgreSQL: How to change PostgreSQL user password?

If you are on windows.

Open pg_hba.conf file and change from md5 to peer

Open cmd, type psql postgres postgres

Then type \password to be prompted for a new password.

Refer to this medium post for further information & granular steps.

@viewChild not working - cannot read property nativeElement of undefined

Initializing the Canvas like below works for TypeScript/Angular solutions.

const canvas = <HTMLCanvasElement> document.getElementById("htmlElemId"); 

const context = canvas.getContext("2d"); 

Excel: VLOOKUP that returns true or false?

You can use:

=IF(ISERROR(VLOOKUP(lookup value,table array,column no,FALSE)),"FALSE","TRUE")

get client time zone from browser

I used an approach similar to the one taken by Josh Fraser, which determines the browser time offset from UTC and whether it recognizes DST or not (but somewhat simplified from his code):

var ClientTZ = {
    UTCoffset:  0,          // Browser time offset from UTC in minutes
    UTCoffsetT: '+0000S',   // Browser time offset from UTC in '±hhmmD' form
    hasDST:     false,      // Browser time observes DST

    // Determine browser's timezone and DST
    getBrowserTZ: function () {
        var self = ClientTZ;

        // Determine UTC time offset
        var now = new Date();
        var date1 = new Date(now.getFullYear(), 1-1, 1, 0, 0, 0, 0);    // Jan
        var diff1 = -date1.getTimezoneOffset();
        self.UTCoffset = diff1;

        // Determine DST use
        var date2 = new Date(now.getFullYear(), 6-1, 1, 0, 0, 0, 0);    // Jun
        var diff2 = -date2.getTimezoneOffset();
        if (diff1 != diff2) {
            self.hasDST = true;
            if (diff1 - diff2 >= 0)
                self.UTCoffset = diff2;     // East of GMT
        }

        // Convert UTC offset to ±hhmmD form
        diff2 = (diff1 < 0 ? -diff1 : diff1) / 60;
        var hr = Math.floor(diff2);
        var min = diff2 - hr;
        diff2 = hr * 100 + min * 60;
        self.UTCoffsetT = (diff1 < 0 ? '-' : '+') + (hr < 10 ? '0' : '') + diff2.toString() + (self.hasDST ? 'D' : 'S');

        return self.UTCoffset;
    }
};

// Onload
ClientTZ.getBrowserTZ();

Upon loading, the ClientTZ.getBrowserTZ() function is executed, which sets:

  • ClientTZ.UTCoffset to the browser time offset from UTC in minutes (e.g., CST is -360 minutes, which is -6.0 hours from UTC);
  • ClientTZ.UTCoffsetT to the offset in the form '±hhmmD' (e.g., '-0600D'), where the suffix is D for DST and S for standard (non-DST);
  • ClientTZ.hasDST (to true or false).

The ClientTZ.UTCoffset is provided in minutes instead of hours, because some timezones have fractional hourly offsets (e.g., +0415).

The intent behind ClientTZ.UTCoffsetT is to use it as a key into a table of timezones (not provided here), such as for a drop-down <select> list.

Merge 2 DataTables and store in a new one

This is what i did for merging two datatables and bind the final result to the gridview

        DataTable dtTemp=new DataTable();
        for (int k = 0; k < GridView2.Rows.Count; k++)
        {
            string roomno = GridView2.Rows[k].Cells[1].Text;
            DataTable dtx = GetRoomDetails(chk, roomno, out msg);
            if (dtx.Rows.Count > 0)
            {
                dtTemp.Merge(dtx);
                dtTemp.AcceptChanges();

            }
        }

How can I get the application's path in a .NET console application?

Try this simple line of code:

 string exePath = Path.GetDirectoryName( Application.ExecutablePath);

How to select last two characters of a string

You should use substring, not jQuery, to do this.

Try something like this:

member.substring(member.length - 2, member.length)

W3Schools (not official, but occasionally helpful): http://www.w3schools.com/jsref/jsref_substring.asp

Adding MDN link as requested by commenter: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring

how to sort an ArrayList in ascending order using Collections and Comparator

This might work?

Comparator mycomparator = 
    Collections.reverseOrder(Collections.reverseOrder());

How to clear APC cache entries?

A good solution for me was to simply not using the outdated user cache any more after deploy.

If you add prefix to each of you keys you can change the prefix on changing the data structure of cache entries. This will help you to get the following behavior on deploy:

  1. Don't use outdated cache entries after deploy of only updated structures
  2. Don't clean the whole cache on deploy to not slow down your page
  3. Some old cached entries can be reused after reverting your deploy (If the entries wasn't automatically removed already)
  4. APC will remove old cache entries after expire OR on missing cache space

This is possible for user cache only.

How to check the maximum number of allowed connections to an Oracle database?

I thought this would work, based on this source.

SELECT
  'Currently, ' 
  || (SELECT COUNT(*) FROM V$SESSION)
  || ' out of ' 
  || DECODE(VL.SESSIONS_MAX,0,'unlimited',VL.SESSIONS_MAX) 
  || ' connections are used.' AS USAGE_MESSAGE
FROM 
  V$LICENSE VL

However, Justin Cave is right. This query gives better results:

SELECT
  'Currently, ' 
  || (SELECT COUNT(*) FROM V$SESSION)
  || ' out of ' 
  || VP.VALUE 
  || ' connections are used.' AS USAGE_MESSAGE
FROM 
  V$PARAMETER VP
WHERE VP.NAME = 'sessions'