Programs & Examples On #Npoi

.NET version of the Apache POI (Java) project

How to read file using NPOI

private static ISheet GetFileStream(string fullFilePath)
    {
        var fileExtension = Path.GetExtension(fullFilePath);
        string sheetName;
        ISheet sheet = null;
        switch (fileExtension)
        {
            case ".xlsx":
                using (var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read))
                {
                    var wb = new XSSFWorkbook(fs);
                    sheetName = wb.GetSheetAt(0).SheetName;
                    sheet = (XSSFSheet) wb.GetSheet(sheetName);
                }
                break;
            case ".xls":
                using (var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read))
                {
                    var wb = new HSSFWorkbook(fs);
                    sheetName = wb.GetSheetAt(0).SheetName;
                    sheet = (HSSFSheet) wb.GetSheet(sheetName);
                }
                break;
        }
        return sheet;
    }

    private static DataTable GetRequestsDataFromExcel(string fullFilePath)
    {
        try
        {
            var sh = GetFileStream(fullFilePath);
            var dtExcelTable = new DataTable();
            dtExcelTable.Rows.Clear();
            dtExcelTable.Columns.Clear();
            var headerRow = sh.GetRow(0);
            int colCount = headerRow.LastCellNum;
            for (var c = 0; c < colCount; c++)
                dtExcelTable.Columns.Add(headerRow.GetCell(c).ToString());
            var i = 1;
            var currentRow = sh.GetRow(i);
            while (currentRow != null)
            {
                var dr = dtExcelTable.NewRow();
                for (var j = 0; j < currentRow.Cells.Count; j++)
                {
                    var cell = currentRow.GetCell(j);

                    if (cell != null)
                        switch (cell.CellType)
                        {
                            case CellType.Numeric:
                                dr[j] = DateUtil.IsCellDateFormatted(cell)
                                    ? cell.DateCellValue.ToString(CultureInfo.InvariantCulture)
                                    : cell.NumericCellValue.ToString(CultureInfo.InvariantCulture);
                                break;
                            case CellType.String:
                                dr[j] = cell.StringCellValue;
                                break;
                            case CellType.Blank:
                                dr[j] = string.Empty;
                                break;
                        }
                }
                dtExcelTable.Rows.Add(dr);
                i++;
                currentRow = sh.GetRow(i);
            }
            return dtExcelTable;
        }
        catch (Exception e)
        {
            throw;
        }
    }

How to decrease prod bundle size?

Use latest angular cli version and use command ng build --prod --build-optimizer It will definitely reduce the build size for prod env.

This is what the build optimizer does under the hood:

The build optimizer has two main jobs. First, we are able to mark parts of your application as pure,this improves the tree shaking provided by the existing tools, removing additional parts of your application that aren’t needed.

The second thing the build optimizer does is to remove Angular decorators from your application’s runtime code. Decorators are used by the compiler, and aren’t needed at runtime and can be removed. Each of these jobs decrease the size of your JavaScript bundles, and increase the boot speed of your application for your users.

Note : One update for Angular 5 and up, the ng build --prod automatically take care of above process :)

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

Which TensorFlow and CUDA version combinations are compatible?

if you are coding in jupyter notebook, and want to check which cuda version tf is using, run the follow command directly into jupyter cell:

!conda list cudatoolkit

!conda list cudnn

and to check if the gpu is visible to tf:

tf.test.is_gpu_available(
    cuda_only=False, min_cuda_compute_capability=None
)

What does DIM stand for in Visual Basic and BASIC?

DIM stands for Declaration In Memory DIM x As New Integer creates a space in memory where the variable x is stored

How to preview selected image in input type="file" in popup using jQuery?

Just check my scripts it's working well:

  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
#list img{
  width: auto;
  height: 100px;
  margin: 10px ;
}

What is EOF in the C programming language?

int c;

while((c = getchar())!= 10)
{
    if( getchar() == EOF )
        break;

     printf(" %d\n", c);
}

Include another JSP file

What you're doing is a static include. A static include is resolved at compile time, and may thus not use a parameter value, which is only known at execution time.

What you need is a dynamic include:

<jsp:include page="..." />

Note that you should use the JSP EL rather than scriptlets. It also seems that you're implementing a central controller with index.jsp. You should use a servlet to do that instead, and dispatch to the appropriate JSP from this servlet. Or better, use an existing MVC framework like Stripes or Spring MVC.

Open Facebook page from Android app?

This works on the latest version:

  1. Go to https://graph.facebook.com/<user_name_here> (https://graph.facebook.com/fsintents for instance)
  2. Copy your id
  3. Use this method:

    public static Intent getOpenFacebookIntent(Context context) {
    
       try {
        context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
        return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/<id_here>"));
       } catch (Exception e) {
        return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/<user_name_here>"));
       }
    }
    

This will open the Facebook app if the user has it installed. Otherwise, it will open Facebook in the browser.

EDIT: since version 11.0.0.11.23 (3002850) Facebook App do not support this way anymore, there's another way, check the response below from Jared Rummler.

Variable length (Dynamic) Arrays in Java

Simple code for dynamic array. In below code then array will become full of size we copy all element to new double size array(variable size array).sample code is below 

public class DynamicArray {
 static   int []increaseSizeOfArray(int []arr){
          int []brr=new int[(arr.length*2)];
          for (int i = 0; i < arr.length; i++) {
         brr[i]=arr[i];     
          }
          return brr;
     }
public static void main(String[] args) {
     int []arr=new int[5];
      for (int i = 0; i < 11; i++) {
          if (i<arr.length) {
              arr[i]=i+100;
          }
          else {
              arr=increaseSizeOfArray(arr);
              arr[i]=i+100;
          }        
     }

for (int i = 0; i < arr.length; i++) {
     System.out.println("arr="+arr[i]);
}    
}

}

Source : How to make dynamic array

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You don't have to repeat those format identifiers . For yyyy you just need to have Y, etc.

gmdate('Y-m-d h:i:s \G\M\T', time());

In fact you don't even need to give it a default time if you want current time

gmdate('Y-m-d h:i:s \G\M\T');  // This is fine for your purpose

Manual

You can get that list of identifiers Here

Reloading/refreshing Kendo Grid

If you are desiring the grid to be automatically refreshed on a timed basis, you can use the following example which has the interval set at 30 seconds:

   <script type="text/javascript" language="javascript">
      $(document).ready(function () {
         setInterval(function () {
            var grid = $("#GridName").data("kendoGrid");
            grid.dataSource.read();
         }, 30000);
      });
   </script>

Check if option is selected with jQuery, if not select a default

I found a good way to check, if option is selected and select a default when it isn't.

    if(!$('#some_select option[selected="selected"]').val()) {
        //here code if it HAS NOT selected value
        //for exaple adding the first value as "placeholder"
        $('#some_select option:first-child').before('<option disabled selected>Wybierz:</option>');
    }

If #some_select has't default selected option then .val() is undefined

Android replace the current fragment with another fragment

If you have a handle to an existing fragment you can just replace it with the fragment's ID.

Example in Kotlin:

fun aTestFuction() {
   val existingFragment = MyExistingFragment() //Get it from somewhere, this is a dirty example
   val newFragment = MyNewFragment()
   replaceFragment(existingFragment, newFragment, "myTag")
}

fun replaceFragment(existing: Fragment, new: Fragment, tag: String? = null) {
    supportFragmentManager.beginTransaction().replace(existing.id, new, tag).commit()
}

About the Full Screen And No Titlebar from manifest

If your Manifest.xml has the default android:theme="@style/AppTheme"

Go to res/values/styles.xml and change

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

to

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

And the ActionBar is disappeared!

Is there a Pattern Matching Utility like GREP in Windows?

May be Everything? It supports regexps and has a console util too.

Calling a parent window function from an iframe

<a onclick="parent.abc();" href="#" >Call Me </a>

See window.parent

Returns a reference to the parent of the current window or subframe.

If a window does not have a parent, its parent property is a reference to itself.

When a window is loaded in an <iframe>, <object>, or <frame>, its parent is the window with the element embedding the window.

Chrome not rendering SVG referenced via <img> tag

Be careful that you don't have transition css property for you svg images

I don't now why, but if you make: "transition: all ease 0.3s" for svg image on Chrome the images do not appear

e.g:

* {
   transition: all ease 0.3s
  }

Chrome do not render svg.

Remove any transition css property and try again

ALTER TABLE add constraint

alter table User 
    add constraint userProperties
    foreign key (properties)
    references Properties(ID)

Change the background color of a pop-up dialog

For any dialog called myDialog, after calling myDialog.show(); you can call:

myDialog.getWindow().getDecorView().getBackground().setColorFilter(new LightingColorFilter(0xFF000000, CUSTOM_COLOR));

where CUSTOM_COLOR is in 8-digit hex format, ex. 0xFF303030. Here, FF is the alpha value and the rest is the color value in hex.

CSS3 transitions inside jQuery .css()

Your code can get messy fast when dealing with CSS3 transitions. I would recommend using a plugin such as jQuery Transit that handles the complexity of CSS3 animations/transitions.

Moreover, the plugin uses webkit-transform rather than webkit-transition, which allows for mobile devices to use hardware acceleration in order to give your web apps that native look and feel when the animations occur.

JS Fiddle Live Demo

Javascript:

$("#startTransition").on("click", function()
{

    if( $(".boxOne").is(":visible")) 
    {
        $(".boxOne").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxOne").hide(); });
        $(".boxTwo").css({ x: '100%' });
        $(".boxTwo").show().transition({ x: '0%', opacity: 1.0 });
        return;        
    }

    $(".boxTwo").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxTwo").hide(); });
    $(".boxOne").css({ x: '100%' });
    $(".boxOne").show().transition({ x: '0%', opacity: 1.0 });

});

Most of the hard work of getting cross-browser compatibility is done for you as well and it works like a charm on mobile devices.

Twitter bootstrap scrollable modal

I also added

.modal { position: absolute; }

to the stylesheet to allow the dialog to scroll, but if the user has moved down to the bottom of a long page the modal can end up hidden off the top of the visible area.

I understand this is no longer an issue in bootstrap 3, but looking for a relatively quick fix until we upgrade I ended up with the above plus calling the following before opening the modal

$('.modal').css('top', $(document).scrollTop() + 50);

Seems to be happy in FireFox, Chrome, IE10 8 & 7 (the browsers I had to hand)

How to check if array is not empty?

if self.table:
    print 'It is not empty'

Is fine too

Convert a list to a dictionary in Python

You can also do it like this (string to list conversion here, then conversion to a dictionary)

    string_list = """
    Hello World
    Goodbye Night
    Great Day
    Final Sunset
    """.split()

    string_list = dict(zip(string_list[::2],string_list[1::2]))

    print string_list

How do I update pip itself from inside my virtual environment?

The more safe method is to run pip though a python module:

python -m pip install -U pip

On windows there seem to be a problem with binaries that try to replace themselves, this method works around that limitation.

Deleting array elements in JavaScript - delete vs splice

As stated many times above, using splice() seems like a perfect fit. Documentation at Mozilla:

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

myFish.splice(2, 0, 'drum'); 
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]

myFish.splice(2, 1); 
// myFish is ["angel", "clown", "mandarin", "sturgeon"]

Syntax

array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)

Parameters

start

Index at which to start changing the array. If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end.

deleteCount

An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. If deleteCount is greater than the number of elements left in the array starting at start, then all of the elements through the end of the array will be deleted.

If deleteCount is omitted, deleteCount will be equal to (arr.length - start).

item1, item2, ...

The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.

Return value

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

[...]

How to write a multiline command?

In the Windows Command Prompt the ^ is used to escape the next character on the command line. (Like \ is used in strings.) Characters that need to be used in the command line as they are should have a ^ prefixed to them, hence that's why it works for the newline.

For reference the characters that need escaping (if specified as command arguments and not within quotes) are: &|()

So the equivalent of your linux example would be (the More? being a prompt):

C:\> dir ^
More? C:\Windows

How to persist data in a dockerized postgres database using volumes

I would avoid using a relative path. Remember that docker is a daemon/client relationship.

When you are executing the compose, it's essentially just breaking down into various docker client commands, which are then passed to the daemon. That ./database is then relative to the daemon, not the client.

Now, the docker dev team has some back and forth on this issue, but the bottom line is it can have some unexpected results.

In short, don't use a relative path, use an absolute path.

How to read and write to a text file in C++?

To read you should create an instance of ifsteam and not ofstream.

ifstream iusrfile;

You should open the file in read mode.

iusrfile.open("usrfile.txt", ifstream::in);

Also this statement is not correct.

cout<<iusrfile;

If you are trying to print the data you read from the file you should do:

cout<<usr;

You can read more about ifstream and its API here

changing the language of error message in required field in html5 contact form

your forget this in oninvalid, change your code with this:

    oninvalid="this.setCustomValidity('Lütfen isaretli yerleri doldurunuz')"

enter image description here

_x000D_
_x000D_
<form><input type="text" name="company_name"  oninvalid="this.setCustomValidity('Lütfen isaretli yerleri doldurunuz')" required /><input type="submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Correct way to integrate jQuery plugins in AngularJS

Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link function of the directive.

There are a couple of points in the documentation that you could take a look at. You can find them here:
Common Pitfalls

Using controllers correctly

Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.

EDIT: Rather than using $(element), you can make use of angular.element(element) when using AngularJS with jQuery

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

iOS: how to perform a HTTP POST request?

I thought I would update this post a bit and say that alot of the iOS community has moved over to AFNetworking after ASIHTTPRequest was abandoned. I highly recommend it. It's a great wrapper around NSURLConnection and allows for asynchronous calls, and basically anything you might need.

Using CookieContainer with WebClient class

I think there's cleaner way where you don't have to create a new webclient (and it'll work with 3rd party libraries as well)

internal static class MyWebRequestCreator
{
    private static IWebRequestCreate myCreator;

    public static IWebRequestCreate MyHttp
    {
        get
        {
            if (myCreator == null)
            {
                myCreator = new MyHttpRequestCreator();
            }
            return myCreator;
        }
    }

    private class MyHttpRequestCreator : IWebRequestCreate
    {
        public WebRequest Create(Uri uri)
        {
            var req = System.Net.WebRequest.CreateHttp(uri);
            req.CookieContainer = new CookieContainer();
            return req;
        }
    }
}

Now all you have to do is opt in for which domains you want to use this:

    WebRequest.RegisterPrefix("http://example.com/", MyWebRequestCreator.MyHttp);

That means ANY webrequest that goes to example.com will now use your custom webrequest creator, including the standard webclient. This approach means you don't have to touch all you code. You just call the register prefix once and be done with it. You can also register for "http" prefix to opt in for everything everywhere.

How to set a Timer in Java?

Ok, I think I understand your problem now. You can use a Future to try to do something and then timeout after a bit if nothing has happened.

E.g.:

FutureTask<Void> task = new FutureTask<Void>(new Callable<Void>() {
  @Override
  public Void call() throws Exception {
    // Do DB stuff
    return null;
  }
});

Executor executor = Executors.newSingleThreadScheduledExecutor();
executor.execute(task);

try {
  task.get(5, TimeUnit.SECONDS);
}
catch(Exception ex) {
  // Handle your exception
}

How can I set a website image that will show as preview on Facebook?

If you're using Weebly, start by viewing the published site and right-clicking the image to Copy Image Address. Then in Weebly, go to Edit Site, Pages, click the page you wish to use, SEO Settings, under Header Code enter the code from Shef's answer:

<meta property="og:image" content="/uploads/..." />

just replacing /uploads/... with the copied image address. Click Publish to apply the change.

You can skip the part of Shef's answer about namespace, because that's already set by default in Weebly.

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

You should initialize yours recordings. You are passing to adapter null

ArrayList<String> recordings = null; //You are passing this null

Android: How to open a specific folder via Intent and show its content in a file browser?

Intent chooser = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getDownloadCacheDirectory().getPath().toString());
chooser.addCategory(Intent.CATEGORY_OPENABLE);
chooser.setDataAndType(uri, "*/*");
// startActivity(chooser);
try {
startActivityForResult(chooser, SELECT_FILE);
}
catch (android.content.ActivityNotFoundException ex)
{
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}

In code above, if setDataAndType is "*/*" a builtin file browser is opened to pick any file, if I set "text/plain" Dropbox is opened. I have Dropbox, Google Drive installed. If I uninstall Dropbox only "*/*" works to open file browser. This is Android 4.4.2. I can download contents from Dropbox and for Google Drive, by getContentResolver().openInputStream(data.getData()).

bootstrap 3 tabs not working properly

My problem was that I sillily concluded bootstrap documentation is the latest one.
If you are using Bootstrap 4, the necessary working tab markub is: http://v4-alpha.getbootstrap.com/components/navs/#javascript-behavior

<ul>
  <li class="nav-item"><a class="active" href="#a" data-toggle="tab">a</a></li>
  <li class="nav-item"><a                href="#b" data-toggle="tab">b</a></li>
</ul>

<div class="tab-content">
  <div class="tab-pane active" id="a">a</div>
  <div class="tab-pane"        id="b">b</div>
</div>

C# Set collection?

Have a look at PowerCollections over at CodePlex. Apart from Set and OrderedSet it has a few other usefull collection types such as Deque, MultiDictionary, Bag, OrderedBag, OrderedDictionary and OrderedMultiDictionary.

For more collections, there is also the C5 Generic Collection Library.

Plotting 4 curves in a single plot, with 3 y-axes

One possibility you can try is to create 3 axes stacked one on top of the other with the 'Color' properties of the top two set to 'none' so that all the plots are visible. You would have to adjust the axes width, position, and x-axis limits so that the 3 y axes are side-by-side instead of on top of one another. You would also want to remove the x-axis tick marks and labels from 2 of the axes since they will lie on top of one another.

Here's a general implementation that computes the proper positions for the axes and offsets for the x-axis limits to keep the plots lined up properly:

%# Some sample data:
x = 0:20;
N = numel(x);
y1 = rand(1,N);
y2 = 5.*rand(1,N)+5;
y3 = 50.*rand(1,N)-50;

%# Some initial computations:
axesPosition = [110 40 200 200];  %# Axes position, in pixels
yWidth = 30;                      %# y axes spacing, in pixels
xLimit = [min(x) max(x)];         %# Range of x values
xOffset = -yWidth*diff(xLimit)/axesPosition(3);

%# Create the figure and axes:
figure('Units','pixels','Position',[200 200 330 260]);
h1 = axes('Units','pixels','Position',axesPosition,...
          'Color','w','XColor','k','YColor','r',...
          'XLim',xLimit,'YLim',[0 1],'NextPlot','add');
h2 = axes('Units','pixels','Position',axesPosition+yWidth.*[-1 0 1 0],...
          'Color','none','XColor','k','YColor','m',...
          'XLim',xLimit+[xOffset 0],'YLim',[0 10],...
          'XTick',[],'XTickLabel',[],'NextPlot','add');
h3 = axes('Units','pixels','Position',axesPosition+yWidth.*[-2 0 2 0],...
          'Color','none','XColor','k','YColor','b',...
          'XLim',xLimit+[2*xOffset 0],'YLim',[-50 50],...
          'XTick',[],'XTickLabel',[],'NextPlot','add');
xlabel(h1,'time');
ylabel(h3,'values');

%# Plot the data:
plot(h1,x,y1,'r');
plot(h2,x,y2,'m');
plot(h3,x,y3,'b');

and here's the resulting figure:

enter image description here

pass **kwargs argument to another function with **kwargs

For #2 args will be only a formal parameter with dict value, but not a keyword type parameter.

If you want to pass a keyword type parameter into a keyword argument You need to specific ** before your dictionary, which means **args

check this out for more detail on using **kw

http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

Directory.GetFiles of certain extension

If you would like to do your filtering in LINQ, you can do it like this:

var ext = new List<string> { "jpg", "gif", "png" };
var myFiles = Directory
    .EnumerateFiles(dir, "*.*", SearchOption.AllDirectories)
    .Where(s => ext.Contains(Path.GetExtension(s).TrimStart(".").ToLowerInvariant()));

Now ext contains a list of allowed extensions; you can add or remove items from it as necessary for flexible filtering.

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

HTTPS using Jersey Client

Waking up a dead question here but the answers provided will not work with jdk 7 (I read somewhere that a bug is open for this for Oracle Engineers but not fixed yet). Along with the link that @Ryan provided, you will have to also add :

System.setProperty("jsse.enableSNIExtension", "false");

(Courtesy to many stackoverflow answers combined together to figure this out)

The complete code will look as follows which worked for me (without setting the system property the Client Config did not work for me):

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
public class ClientHelper
{
    public static ClientConfig configureClient()
    {
        System.setProperty("jsse.enableSNIExtension", "false");
        TrustManager[] certs = new TrustManager[]
        {
            new X509TrustManager()
            {
                @Override
                public X509Certificate[] getAcceptedIssuers()
                {
                    return null;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException
                {
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException
                {
                }
            }
        };
        SSLContext ctx = null;
        try
        {
            ctx = SSLContext.getInstance("SSL");
            ctx.init(null, certs, new SecureRandom());
        }
        catch (java.security.GeneralSecurityException ex)
        {
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        ClientConfig config = new DefaultClientConfig();
        try
        {
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(
                    new HostnameVerifier()
            {
                @Override
                public boolean verify(String hostname, SSLSession session)
                {
                    return true;
                }
            },
                    ctx));
        }
        catch (Exception e)
        {
        }
        return config;
    }

    public static Client createClient()
    {
        return Client.create(ClientHelper.configureClient());
    }

How to implement endless list with RecyclerView?

I let you my aproximation. Works fine for me.

I hope it helps you.

/**
 * Created by Daniel Pardo Ligorred on 03/03/2016.
 */
public abstract class BaseScrollListener extends RecyclerView.OnScrollListener {

    protected RecyclerView.LayoutManager layoutManager;

    public BaseScrollListener(RecyclerView.LayoutManager layoutManager) {

        this.layoutManager = layoutManager;

        this.init();
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

        super.onScrolled(recyclerView, dx, dy);

        this.onScroll(recyclerView, this.getFirstVisibleItem(), this.layoutManager.getChildCount(), this.layoutManager.getItemCount(), dx, dy);
    }

    private int getFirstVisibleItem(){

        if(this.layoutManager instanceof LinearLayoutManager){

            return ((LinearLayoutManager) this.layoutManager).findFirstVisibleItemPosition();
        } else if (this.layoutManager instanceof StaggeredGridLayoutManager){

            int[] spanPositions = null; //Should be null -> StaggeredGridLayoutManager.findFirstVisibleItemPositions makes the work.

            try{

                return ((StaggeredGridLayoutManager) this.layoutManager).findFirstVisibleItemPositions(spanPositions)[0];
            }catch (Exception ex){

                // Do stuff...
            }
        }

        return 0;
    }

    public abstract void init();

    protected abstract void onScroll(RecyclerView recyclerView, int firstVisibleItem, int visibleItemCount, int totalItemCount, int dx, int dy);

}

Shortcut to open file in Vim

You can search for a file in the current path by using **:

:tabe **/header.h

Hit tab to see various completions if there is more than one match.

Instagram API: How to get all user media?

Use the next_url object to get the next 20 images.

In the JSON response there is an pagination array:

 "pagination":{
      "next_max_tag_id":"1411892342253728",
      "deprecation_warning":"next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
      "next_max_id":"1411892342253728",
      "next_min_id":"1414849145899763",
      "min_tag_id":"1414849145899763",
      "next_url":"https:\/\/api.instagram.com\/v1\/tags\/lemonbarclub\/media\/recent?client_id=xxxxxxxxxxxxxxxxxx\u0026max_tag_id=1411892342253728"
 }

This is the information on specific API call and the object next_url shows the URL to get the next 20 pictures so just take that URL and call it for the next 20 pictures.

For more information about the Instagram API check out this blogpost: Getting Friendly With Instagram’s API

How do I get a div to float to the bottom of its container?

I had been find this solution for a long time as well. This is what I get:

align-self: flex-end;

link: https://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/ However, I can't remember from where I opened this link. Hope it helps

How to create a bash script to check the SSH connection?

You can check this with the return-value ssh gives you:

$ ssh -q user@downhost exit
$ echo $?
255

$ ssh -q user@uphost exit
$ echo $?
0

EDIT: Another approach would be to use nmap (you won't need to have keys or login-stuff):

$ a=`nmap uphost -PN -p ssh | grep open`
$ b=`nmap downhost -PN -p ssh | grep open`

$ echo $a
22/tcp open ssh
$ echo $b
(empty string)

But you'll have to grep the message (nmap does not use the return-value to show if a port was filtered, closed or open).

EDIT2:

If you're interested in the actual state of the ssh-port, you can substitute grep open with egrep 'open|closed|filtered':

$ nmap host -PN -p ssh | egrep 'open|closed|filtered'

Just to be complete.

How can I install a previous version of Python 3 in macOS using homebrew?

The easiest way for me was to install Anaconda: https://docs.anaconda.com/anaconda/install/

There I can create as many environments with different Python versions as I want and switch between them with a mouse click. It could not be easier.

To install different Python versions just follow these instructions https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-python.html

A new development environment with a different Python version was done within 2 minutes. And in the future I can easily switch back and forth.

TreeMap sort by value

import java.util.*;

public class Main {

public static void main(String[] args) {
    TreeMap<String, Integer> initTree = new TreeMap();
    initTree.put("D", 0);
    initTree.put("C", -3);
    initTree.put("A", 43);
    initTree.put("B", 32);
    System.out.println("Sorted by keys:");
    System.out.println(initTree);
    List list = new ArrayList(initTree.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        @Override
        public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
            return e1.getValue().compareTo(e2.getValue());
        }
    });
    System.out.println("Sorted by values:");
    System.out.println(list);
}
}

How to auto-reload files in Node.js?

Nowadays WebPack dev server with hot option is used. you can add a script like this in your package.json : "hot": "cross-env NODE_ENV=development webpack-dev-server --hot --inline --watch-poll",

and every change in your files will trigger a recompile automatically

std::cin input with spaces?

The Standard Library provides an input function called ws, which consumes whitespace from an input stream. You can use it like this:

std::string s;
std::getline(std::cin >> std::ws, s);

Use index in pandas to plot data

monthly_mean.plot(y='A')

Uses index as x-axis by default.

How do I install TensorFlow's tensorboard?

The steps to install Tensorflow are here: https://www.tensorflow.org/install/

For example, on Linux for CPU-only (no GPU), you would type this command:

pip install -U pip
pip install tensorflow

Since TensorFlow depends on TensorBoard, running the following command should not be necessary:

pip install tensorboard

How to correctly represent a whitespace character

Which whitespace character? The empty string is pretty unambiguous - it's a sequence of 0 characters. However, " ", "\t" and "\n" are all strings containing a single character which is characterized as whitespace.

If you just mean a space, use a space. If you mean some other whitespace character, there may well be a custom escape sequence for it (e.g. "\t" for tab) or you can use a Unicode escape sequence ("\uxxxx"). I would discourage you from including non-ASCII characters in your source code, particularly whitespace ones.

EDIT: Now that you've explained what you want to do (which should have been in your question to start with) you'd be better off using Regex.Split with a regular expression of \s which represents whitespace:

Regex regex = new Regex(@"\s");
string[] bits = regex.Split(text.ToLower());

See the Regex Character Classes documentation for more information on other character classes.

How can I dynamically switch web service addresses in .NET without a recompile?

Just a note about difference beetween static and dynamic.

  • Static: you must set URL property every time you call web service. This because base URL if web service is in the proxy class constructor.
  • Dynamic: a special configuration key will be created for you in your web.config file. By default proxy class will read URL from this key.

Trigger change event of dropdown

alternatively you can put onchange attribute on the dropdownlist itself, that onchange will call certain jquery function like this.

<input type="dropdownlist" onchange="jqueryFunc()">

<script type="text/javascript">
$(function(){
    jqueryFunc(){
        //something goes here
    }
});
</script>

hope this one helps you, and please note that this code is just a rough draft, not tested on any ide. thanks

How to connect to a MySQL Data Source in Visual Studio

Visual Studio requires that DDEX Providers (Data Designer Extensibility) be registered by adding certain entries in the Windows Registry during installation (HKLM\SOFTWARE\Microsoft\VisualStudio\{version}\DataProviders) . See DDEX Provider Registration in MSDN for more details.

Optional Parameters in Web Api Attribute Routing

Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:

[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]

The ? character is put always before the last } character

For more information see: Optional URI Parameters and Default Values

Assign output of a program to a variable using a MS batch file

One way is:

application arg0 arg1 > temp.txt
set /p VAR=<temp.txt

Another is:

for /f %%i in ('application arg0 arg1') do set VAR=%%i

Note that the first % in %%i is used to escape the % after it and is needed when using the above code in a batch file rather than on the command line. Imagine, your test.bat has something like:

for /f %%i in ('c:\cygwin64\bin\date.exe +"%%Y%%m%%d%%H%%M%%S"') do set datetime=%%i
echo %datetime%

Windows CMD command for accessing usb?

You can access the USB drive by its drive letter. To know the drive letter you can run this command:

C:\>wmic logicaldisk where drivetype=2 get deviceid, volumename, description

From here you will get the drive letter (Device ID) of your USB drive.

For example if its F: then run the following command in command prompt to see its contents:

C:\> F:

F:\> dir

Regular Expression for matching parentheses

Two options:

Firstly, you can escape it using a backslash -- \(

Alternatively, since it's a single character, you can put it in a character class, where it doesn't need to be escaped -- [(]

Excel VBA If cell.Value =... then

You can determine if as certain word is found in a cell by using

If InStr(cell.Value, "Word1") > 0 Then

If Word1 is found in the string the InStr() function will return the location of the first character of Word1 in the string.

Displaying a Table in Django from Database

The easiest way is to use a for loop template tag.

Given the view:

def MyView(request):
    ...
    query_results = YourModel.objects.all()
    ...
    #return a response to your template and add query_results to the context

You can add a snippet like this your template...

<table>
    <tr>
        <th>Field 1</th>
        ...
        <th>Field N</th>
    </tr>
    {% for item in query_results %}
    <tr> 
        <td>{{ item.field1 }}</td>
        ...
        <td>{{ item.fieldN }}</td>
    </tr>
    {% endfor %}
</table>

This is all covered in Part 3 of the Django tutorial. And here's Part 1 if you need to start there.

Barcode scanner for mobile phone for Website in form

Check out https://github.com/serratus/quaggaJS

"QuaggaJS is a barcode-scanner entirely written in JavaScript supporting real- time localization and decoding of various types of barcodes such as EAN, CODE 128, CODE 39, EAN 8, UPC-A, UPC-C, I2of5, 2of5, CODE 93 and CODABAR. The library is also capable of using getUserMedia to get direct access to the user's camera stream. Although the code relies on heavy image-processing even recent smartphones are capable of locating and decoding barcodes in real-time."

Data binding to SelectedItem in a WPF Treeview

This can be accomplished in a 'nicer' way using only binding and the GalaSoft MVVM Light library's EventToCommand. In your VM add a command which will be called when the selected item is changed, and initialize the command to perform whatever action is necessary. In this example I used a RelayCommand and will just set the SelectedCluster property.

public class ViewModel
{
    public ViewModel()
    {
        SelectedClusterChanged = new RelayCommand<Cluster>( c => SelectedCluster = c );
    }

    public RelayCommand<Cluster> SelectedClusterChanged { get; private set; } 

    public Cluster SelectedCluster { get; private set; }
}

Then add the EventToCommand behavior in your xaml. This is really easy using blend.

<TreeView
      x:Name="lstClusters"
      ItemsSource="{Binding Path=Model.Clusters}" 
      ItemTemplate="{StaticResource HoofdCLusterTemplate}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectedItemChanged">
            <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding SelectedClusterChanged}" CommandParameter="{Binding ElementName=lstClusters,Path=SelectedValue}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TreeView>

Docker - Cannot remove dead container

Removing container by force worked for me.

docker rm -f <id_of_the_dead_container>

Notes:

Be aware that this command might throw this error Error response from daemon: Driver devicemapper failed to remove root filesystem <id_of_the_dead_container>: Device is Busy

The mount of your's dead container device mapper should be removed despite this message. That is, you will no longer access this path:

/var/lib/docker/devicemapper/mnt/<id_of_the_dead_container>

Iterating through a List Object in JSP

Before teaching yourself Spring and Struts, you should probably learn Java. Output like this

org.classes.database.Employee@d9b02

is the result of the Object#toString() method which all objects inherit from the Object class, the superclass of all classes in Java.

The List sub classes implement this by iterating over all the elements and calling toString() on those. It seems, however, that you haven't implemented (overriden) the method in your Employee class.

Your JSTL here

<c:forEach items="${eList}" var="employee">
    <tr>
        <td>Employee ID: <c:out value="${employee.eid}"/></td>
        <td>Employee Pass: <c:out value="${employee.ename}"/></td>  
    </tr>
</c:forEach>

is fine except for the fact that you don't have a page, request, session, or application scoped attribute named eList.

You need to add it

<% List eList = (List)session.getAttribute("empList");
   request.setAttribute("eList", eList);
%>

Or use the attribute empList in the forEach.

<c:forEach items="${empList}" var="employee">
    <tr>
        <td>Employee ID: <c:out value="${employee.eid}"/></td>
        <td>Employee Pass: <c:out value="${employee.ename}"/></td>  
    </tr>
</c:forEach>

How to undo a successful "git cherry-pick"?

Faced with this same problem, I discovered if you have committed and/or pushed to remote since your successful cherry-pick, and you want to remove it, you can find the cherry-pick's SHA by running:

git log --graph --decorate --oneline

Then, (after using :wq to exit the log) you can remove the cherry-pick using

git rebase -p --onto YOUR_SHA_HERE^ YOUR_SHA_HERE

where YOUR_SHA_HERE equals the cherry-picked commit's 40- or abbreviated 7-character SHA.

At first, you won't be able to push your changes because your remote repo and your local repo will have different commit histories. You can force your local commits to replace what's on your remote by using

git push --force origin YOUR_REPO_NAME

(I adapted this solution from Seth Robertson: See "Removing an entire commit.")

Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this?

From https://pypi.org/project/pytesseract/ :

pytesseract.pytesseract.tesseract_cmd = '<full_path_to_your_tesseract_executable>'
# Include the above line, if you don't have tesseract executable in your PATH
# Example tesseract_cmd: 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract'

Angularjs - simple form submit

I think the reason AngularJS does not say much about form submission because it depends more on 'two-way data binding'. In traditional html development you had one way data binding, i.e. once DOM rendered any changes you make to DOM element did not reflect in JS Object, however in AngularJS it works both way. Hence there's in fact no need to form submission. I have done a mid sized application using AngularJS without the need to form submission. If you are keen to submit form you can write a directive wrapping up your form which handles ENTER keydown and SUBMIT button click events and call form.submit().

If you want the sample source code of such a directive, please let me know by commenting on this. I figured out it would a simple directive that you can write yourself.

Comparing arrays in JUnit assertions, concise built-in way?

I know the question is for JUnit4, but if you happen to be stuck at JUnit3, you could create a short utility function like that:

private void assertArrayEquals(Object[] esperado, Object[] real) {
    assertEquals(Arrays.asList(esperado), Arrays.asList(real));     
}

In JUnit3, this is better than directly comparing the arrays, since it will detail exactly which elements are different.

Fastest Way to Find Distance Between Two Lat/Long Points

Have a read of Geo Distance Search with MySQL, a solution based on implementation of Haversine Formula to MySQL. This is a complete solution description with theory, implementation and further performance optimization. Although the spatial optimization part didn't work correctly in my case.

I noticed two mistakes in this:

  1. the use of abs in the select statement on p8. I just omitted abs and it worked.

  2. the spatial search distance function on p27 does not convert to radians or multiply longitude by cos(latitude), unless his spatial data is loaded with this in consideration (cannot tell from context of article), but his example on p26 indicates that his spatial data POINT is not loaded with radians or degrees.

How to find a value in an array of objects in JavaScript?

I had to search a nested sitemap structure for the first leaf item that machtes a given path. I came up with the following code just using .map() .filter() and .reduce. Returns the last item found that matches the path /c.

var sitemap = {
  nodes: [
    {
      items: [{ path: "/a" }, { path: "/b" }]
    },
    {
      items: [{ path: "/c" }, { path: "/d" }]
    },
    {
      items: [{ path: "/c" }, { path: "/d" }]
    }
  ]
};

const item = sitemap.nodes
  .map(n => n.items.filter(i => i.path === "/c"))
  .reduce((last, now) => last.concat(now))
  .reduce((last, now) => now);

Edit 4n4904z07

How to create strings containing double quotes in Excel formulas?

Alternatively, you can use the CHAR function:

= "Maurice " & CHAR(34) & "Rocket" & CHAR(34) & " Richard"

Getting visitors country from their IP

Many different ways to do it...

Solution #1:

One third party service you could use is http://ipinfodb.com. They provide hostname, geolocation and additional information.

Register for an API key here: http://ipinfodb.com/register.php. This will allow you to retrieve results from their server, without this it will not work.

Copy and past the following PHP code:

$ipaddress = $_SERVER['REMOTE_ADDR'];
$api_key = 'YOUR_API_KEY_HERE';

$data = file_get_contents("http://api.ipinfodb.com/v3/ip-city/?key=$api_key&ip=$ipaddress&format=json");
$data = json_decode($data);
$country = $data['Country'];

Downside:

Quoting from their website:

Our free API is using IP2Location Lite version which provides lower accuracy.

Solution #2:

This function will return country name using the http://www.netip.de/ service.

$ipaddress = $_SERVER['REMOTE_ADDR'];
function geoCheckIP($ip)
{
    $response=@file_get_contents('http://www.netip.de/search?query='.$ip);

    $patterns=array();
    $patterns["country"] = '#Country: (.*?)&nbsp;#i';

    $ipInfo=array();

    foreach ($patterns as $key => $pattern)
    {
        $ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';
    }

        return $ipInfo;
}

print_r(geoCheckIP($ipaddress));

Output:

Array ( [country] => DE - Germany )  // Full Country Name

Multiple contexts with the same path error running web service in Eclipse using Tomcat

  1. In your project's Properties, choose "Web Project Settings".
  2. Change "Context root".
  3. Clean your server
  4. now you can restart your server

How do I get a python program to do nothing?

You can use continue

if condition:
    continue
else:
    #do something

scp copy directory to another server with private key auth

Putty doesn't use openssh key files - there is a utility in putty suite to convert them.

edit: it is called puttygen

Difference between PACKETS and FRAMES

A packet is a general term for a formatted unit of data carried by a network. It is not necessarily connected to a specific OSI model layer.

For example, in the Ethernet protocol on the physical layer (layer 1), the unit of data is called an "Ethernet packet", which has an Ethernet frame (layer 2) as its payload. But the unit of data of the Network layer (layer 3) is also called a "packet".

A frame is also a unit of data transmission. In computer networking the term is only used in the context of the Data link layer (layer 2).

Another semantical difference between packet and frame is that a frame envelops your payload with a header and a trailer, just like a painting in a frame, while a packet usually only has a header.

But in the end they mean roughly the same thing and the distinction is used to avoid confusion and repetition when talking about the different layers.

Set line spacing

I am not sure if this is what you meant:

line-height: size;

Compress images on client side before uploading

I read about an experiment here: http://webreflection.blogspot.com/2010/12/100-client-side-image-resizing.html

The theory is that you can use canvas to resize the images on the client before uploading. The prototype example seems to work only in recent browsers, interesting idea though...

However, I’m not sure about using canvas to compress images, but you can certainly resize them.

How to subtract hours from a date in Oracle so it affects the day also

Others have commented on the (incorrect) use of 2/11 to specify the desired interval.

I personally however prefer writing things like that using ANSI interval literals which makes reading the query much easier:

sysdate - interval '2' hour

It also has the advantage of being portable, many DBMS support this. Plus I don't have to fire up a calculator to find out how many hours the expression means - I'm pretty bad with mental arithmetics ;)

HTML 5 Geo Location Prompt in Chrome

if you're hosting behind a server, and still facing issues: try changing localhost to 127.0.0.1 e.g. http://localhost:8080/ to http://127.0.0.1:8080/

The issue I was facing was that I was serving a site using apache tomcat within an eclipse IDE (eclipse luna).

For my sanity check I was using Remy Sharp's demo: https://github.com/remy/html5demos/blob/eae156ca2e35efbc648c381222fac20d821df494/demos/geo.html

and was getting the error after making minor tweaks to the error function despite hosting the code on the server (was only working on firefox and failing on chrome and safari):

"User denied Geolocation"

I made the following change to get more detailed error message:

function error(msg) {
  var s = document.querySelector('#status');
  msg = msg.message ? msg.message : msg; //add this line
  s.innerHTML = typeof msg == 'string' ? msg : "failed";
  s.className = 'fail';

  // console.log(arguments);
}

failing on internet explorer behind virtualbox IE10 on http://10.0.2.2:8080 :

"The current location cannot be determined"

TSQL Default Minimum DateTime

I agree with the sentiment in "don't use magic values". But I would like to point out that there are times when it's legit to resort to such solutions.

There is a price to pay for setting columns nullable: NULLs are not indexable. A query like "get all records that haven't been modified since the start of 2010" includes those that have never been modified. If we use a nullable column we're thus forced to use [modified] < @cutoffDate OR [modified] IS NULL, and this in turn forces the database engine to perform a table scan, since the nulls are not indexed. And this last can be a problem.

In practice, one should go with NULL if this does not introduce a practical, real-world performance penalty. But it can be difficult to know, unless you have some idea what realistic data volumes are today and will be in the so-called forseeable future. You also need to know if there will be a large proportion of the records that have the special value - if so, there's no point in indexing it anyway.

In short, by deafult/rule of thumb one should go for NULL. But if there's a huge number of records, the data is frequently queried, and only a small proportion of the records have the NULL/special value, there could be significant performance gain for locating records based on this information (provided of course one creates the index!) and IMHO this can at times justify the use of "magic" values.

Taking the record with the max date

You could also use:

SELECT t.*
  FROM 
        TABLENAME t
    JOIN
        ( SELECT A, MAX(col_date) AS col_date
          FROM TABLENAME
          GROUP BY A
        ) m
      ON  m.A = t.A
      AND m.col_date = t.col_date

How do I find out what version of WordPress is running?

Open the blog, Check source once the blog is open. It should have a meta tag like:

<meta name="generator" content="WordPress 2.8.4" />

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

You can delete individual names with del:

del x

or you can remove them from the globals() object:

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.

Modules you've imported (import os) are going to remain imported because they are referenced by sys.modules; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.

cast a List to a Collection

Casting never needs a new:

Collection<T> collection = myList;

You don't even make the cast explicit, because Collection is a super-type of List, so it will work just like this.

Hash Map in Python

All you wanted (at the time the question was originally asked) was a hint. Here's a hint: In Python, you can use dictionaries.

Find if listA contains any elements not in listB

This piece of code compares two lists both containing a field for a CultureCode like 'en-GB'. This will leave non existing translations in the list. (we needed a dropdown list for not-translated languages for articles)

var compared = supportedLanguages.Where(sl => !existingTranslations.Any(fmt => fmt.CultureCode == sl.Culture)).ToList();

What is the difference between Trap and Interrupt?

Traps and interrupts are closely related. Traps are a type of exception, and exceptions are similar to interrupts.

Intel x86 defines two overlapping categories, vectored events (interrupts vs exceptions), and exception classes (faults vs traps vs aborts).

All of the quotes in this post are from the April 2016 version of the Intel Software Developer Manual. For the (definitive and complex) x86 perspective, I recommend reading the SDM's chapter on Interrupt and Exception handling.

Vectored Events

Vectored Events (interrupts and exceptions) cause the processor to jump into an interrupt handler after saving much of the processor's state (enough such that execution can continue from that point later).

Exceptions and interrupts have an ID, called a vector, that determines which interrupt handler the processor jumps to. Interrupt handlers are described within the Interrupt Descriptor Table.

Interrupts

Interrupts occur at random times during the execution of a program, in response to signals from hardware. System hardware uses interrupts to handle events external to the processor, such as requests to service peripheral devices. Software can also generate interrupts by executing the INT n instruction.

Exceptions

Exceptions occur when the processor detects an error condition while executing an instruction, such as division by zero. The processor detects a variety of error conditions including protection violations, page faults, and internal machine faults.

Exception Classifications

Exceptions are classified as faults, traps, or aborts depending on the way they are reported and whether the instruction that caused the exception can be restarted without loss of program or task continuity.

Summary: traps increment the instruction pointer, faults do not, and aborts 'explode'.

Trap

A trap is an exception that is reported immediately following the execution of the trapping instruction. Traps allow execution of a program or task to be continued without loss of program continuity. The return address for the trap handler points to the instruction to be executed after the trapping instruction.

Fault

A fault is an exception that can generally be corrected and that, once corrected, allows the program to be restarted with no loss of continuity. When a fault is reported, the processor restores the machine state to the state prior to the beginning of execution of the faulting instruction. The return address (saved contents of the CS and EIP registers) for the fault handler points to the faulting instruction, rather than to the instruction following the faulting instruction.

Example: A page fault is often recoverable. A piece of an application's address space may have been swapped out to disk from ram. The application will trigger a page fault when it tries to access memory that was swapped out. The kernel can pull that memory from disk to ram, and hand control back to the application. The application will continue where it left off (at the faulting instruction that was accessing swapped out memory), but this time the memory access should succeed without faulting.

An illegal-instruction fault handler that emulates floating-point or other missing instructions would have to manually increment the return address to get the trap-like behaviour it needs, after seeing if the faulting instruction was one it could handle. x86 #UD is a "fault", not a "trap". (The handler would need a pointer to the faulting instruction to figure out which instruction it was.)

Abort

An abort is an exception that does not always report the precise location of the instruction causing the exception and does not allow a restart of the program or task that caused the exception. Aborts are used to report severe errors, such as hardware errors and inconsistent or illegal values in system tables.

Edge Cases

Software invoked interrupts (triggered by the INT instruction) behave in a trap-like manner. The instruction completes before the processor saves its state and jumps to the interrupt handler.

Where should my npm modules be installed on Mac OS X?

Second Thomas David Kehoe, with the following caveat --

If you are using node version manager (nvm), your global node modules will be stored under whatever version of node you are using at the time you saved the module.

So ~/.nvm/versions/node/{version}/lib/node_modules/.

How to fix the error "Windows SDK version 8.1" was not found?

  • Install the required version of Windows SDK or change the SDK version in the project property pages

    or

  • by right-clicking the solution and selecting "Retarget solution"

If you do visual studio guide, you will resolve the problem.

How do I list all the files in a directory and subdirectories in reverse chronological order?

try this:

ls -ltraR |egrep -v '\.$|\.\.|\.:|\.\/|total' |sed '/^$/d'

1067 error on attempt to start MySQL

I ran into the same errors. Similar approach for me. From what I can tell, there is something weird going on with the reference to the datadir in the my.ini file. Even when I manually edited it I could not seem to have any effect on it, until I blew EVERYTHING AWAY. Wish I had better news...do a DB backup first.

For me the key to getting this to work was:

1) Remove the previous installation from settings->control panel. Restart your machine.

2) Once machine comes back up, forcefully delete the previous installation directory. [mine is C:\apps\MySQL\MySQLServer-5.5\, as I REFUSE to use c:\program files\..]

3) Forcefully delete the previous datadir directory [mine was c:\data\mysql].

4) Forcefully delete the previous default data directory [C:\Documents and Settings\All Users\Application Data\MySQL].

5) Re-run the install, selected the same installation directory. Skip the instance configurator/wizard at the end of the install.

6) Make sure the ../bin directory gets added to the path. Verify it.

7) Manually run the instance configurator/wizard.
Set the root password, port [3306]. It will try to start it. Again, mine FAILED to start [duh! nothing new there!!!]

8) Now, manually edit the my.ini file in the install directory, and correct the datadir setting to be [datadir="C:/Data/MySQL/"] MATCH CAPITALIZATION !!!!

9) Verify the service is setup correctly via the command-prompt [sc qc mysql <enter>].
Should look like:

C:\dev\cmdz>sc qc mysql

[SC] GetServiceConfig SUCCESS

SERVICE_NAME: mysql
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : "C:\apps\MySQL\MySQLServer-5.5\bin\mysqld" --defaults-file="C:\apps\MySQL\MySQLServer-5.5\my.ini" MySQL
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : MySQL
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem

10) Copy the contents of the default data-directory created under C:\Documents and Settings\All Users\Application Data\MySQL [basically everything in this directory to your desired data directory c:\data\mysql]. Make sure you get the C:\Documents and Settings\All Users\Application Data\MySQL\mysql directory. This has host.frm file, and others.
You should end up with a directory now of c:\data\MySQL\mysql...

11) Rename the default directory C:\Documents and Settings\All Users\Application Data\MySQL To C:\Documents and Settings\All Users\Application Data\MySQLxxx So it cannot find it...

12) Say a quick prayer...

13) Give it a kick start from command line with [net start mysql]

That got it working for me...

Best of Luck!

How to create text file and insert data to that file on Android

First create a Project With PdfCreation in Android Studio

Then Follow below steps:

1.Download itextpdf-5.3.2.jar library from this link [https://sourceforge.net/projects/itext/files/iText/iText5.3.2/][1] and then
2.Add to app>libs>itextpdf-5.3.2.jar
3.Right click on jar file then click on add to library
4. Document document = new Document(PageSize.A4); // Create Directory in External Storage
        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/PDF");
        System.out.print(myDir.toString());
        myDir.mkdirs(); // Create Pdf Writer for Writting into New Created Document
        try {
            PdfWriter.getInstance(document, new FileOutputStream(FILE));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } // Open Document for Writting into document
        document.open(); // User Define Method
        addMetaData(document);
        try {
            addTitlePage(document);
        } catch (DocumentException e) {
            e.printStackTrace();
        } // Close Document after writting all content
        document.close();

5.   public void addMetaData(Document document)
    {
        document.addTitle("RESUME");
        document.addSubject("Person Info");
        document.addKeywords("Personal, Education, Skills");
                document.addAuthor("TAG");
        document.addCreator("TAG");
    }
    public void addTitlePage(Document document) throws DocumentException
    { // Font Style for Document
        Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
        Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD
                | Font.UNDERLINE, BaseColor.GRAY);
        Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
        Font normal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL); // Start New Paragraph
        Paragraph prHead = new Paragraph(); // Set Font in this Paragraph
        prHead.setFont(titleFont); // Add item into Paragraph
        prHead.add("RESUME – Name\n"); // Create Table into Document with 1 Row
        PdfPTable myTable = new PdfPTable(1); // 100.0f mean width of table is same as Document size
        myTable.setWidthPercentage(100.0f); // Create New Cell into Table
        PdfPCell myCell = new PdfPCell(new Paragraph(""));
        myCell.setBorder(Rectangle.BOTTOM); // Add Cell into Table
        myTable.addCell(myCell);
        prHead.setFont(catFont);
        prHead.add("\nName1 Name2\n");
        prHead.setAlignment(Element.ALIGN_CENTER); // Add all above details into Document
        document.add(prHead);
        document.add(myTable);
        document.add(myTable); // Now Start another New Paragraph
        Paragraph prPersinalInfo = new Paragraph();
        prPersinalInfo.setFont(smallBold);
        prPersinalInfo.add("Address 1\n");
        prPersinalInfo.add("Address 2\n");
        prPersinalInfo.add("City: SanFran. State: CA\n");
        prPersinalInfo.add("Country: USA Zip Code: 000001\n");
        prPersinalInfo.add("Mobile: 9999999999 Fax: 1111111 Email: [email protected] \n");
        prPersinalInfo.setAlignment(Element.ALIGN_CENTER);
        document.add(prPersinalInfo);
        document.add(myTable);
        document.add(myTable);
        Paragraph prProfile = new Paragraph();
        prProfile.setFont(smallBold);
        prProfile.add("\n \n Profile : \n ");
        prProfile.setFont(normal);
        prProfile.add("\nI am Mr. XYZ. I am Android Application Developer at TAG.");
        prProfile.setFont(smallBold);
        document.add(prProfile); // Create new Page in PDF
        document.newPage();
    }

change cursor to finger pointer

 <! ––  add this code in your class called menu_links -->
<style> 
.menu_links{
cursor: pointer;
}
</style>

In the above code [cursor:pointer] is used to access the hand like cursor that appears when you hover over a link.

And if you use [cursor: default] it will show the usual arrow cursor that appears.

To know more about cursors and their appearance click the below link: https://www.w3schools.com/cssref/pr_class_cursor.asp

Reload an iframe with jQuery

This is possible with simple JavaScript.

  • In iFrame1, make a JavaScript function that is called in the body tag onload. I have it check a server side variable that I set, so it does not try to run the JavaScript function in iframe2 unless I have taken a specific action in iframe1. You could set this up as a function fired by a button press or however you want to in iframe1.
  • Then in iframe2, you have the second function I list below. The function in iframe1 basically goes to the parent page and then uses the window.frames syntax to fire a JavaScript function in iframe2. Just make sure to use the id/name of iframe2 and not the src.
//function in iframe1
function refreshIframe2()
{
    if (<cfoutput>#didValidation#</cfoutput> == 1)
    {   
         parent.window.frames.iframe2.refreshPage();
    }
}

//function in iframe2
function refreshPage()
{   
    document.location.reload();
}

How to check if a variable is an integer or a string?

The isdigit method of the str type returns True iff the given string is nothing but one or more digits. If it's not, you know the string should be treated as just a string.

push multiple elements to array

There are many answers recommend to use: Array.prototype.push(a, b). It's nice way, BUT if you will have really big b, you will have stack overflow error (because of too many args). Be careful here.

See What is the most efficient way to concatenate N arrays? for more details.

No more data to read from socket error

Downgrading the JRE from 7 to 6 fixed this issue for me.

Javascript - check array for value

This should do it:

for (var i = 0; i < bank_holidays.length; i++) {
    if (bank_holidays[i] === '06/04/2012') {
        alert('LOL');
    }
}

jsFiddle

Detect click inside/outside of element with single event handler

Using jQuery, and assuming that you have <div id="foo">:

jQuery(function($){
  $('#foo').click(function(e){
    console.log( 'clicked on div' );
    e.stopPropagation(); // Prevent bubbling
  });
  $('body').click(function(e){
    console.log( 'clicked outside of div' );
  });
});

Edit: For a single handler:

jQuery(function($){
  $('body').click(function(e){
    var clickedOn = $(e.target);
    if (clickedOn.parents().andSelf().is('#foo')){
      console.log( "Clicked on", clickedOn[0], "inside the div" );
    }else{
      console.log( "Clicked outside the div" );
  });
});

Use jQuery to navigate away from page

window.location.href = "/somewhere/else";

Returning JSON from a PHP Script

As said above:

header('Content-Type: application/json');

will make the job. but keep in mind that :

  • Ajax will have no problem to read json even if this header is not used, except if your json contains some HTML tags. In this case you need to set the header as application/json.

  • Make sure your file is not encoded in UTF8-BOM. This format add a character in the top of the file, so your header() call will fail.

Find and replace Android studio

If you use refactor->rename for the name of the file, everywhere the file is used in your project the refactor will replace it.

I have already rename variables, xml file, java file, multiple drawable and after the operation I could build directly without error.

Do a back-up of your project and try to see if it work for you.

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

As others pointed out, this message is coming from your shell prompt. The problem is that in a freshly created repository HEAD (.git/HEAD) points to a ref that doesn't exist yet.

% git init test
Initialized empty shared Git repository in /Users/jhelwig/tmp/test/.git/
% cd test
% cat .git/HEAD
ref: refs/heads/master
% ls -l .git/refs/heads
total 0
% git rev-parse HEAD
HEAD
fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions

It looks like rev-parse is being used without sufficient error checking before-hand. After the first commit has been created .git/refs/heads looks a bit different and git rev-parse HEAD will no longer fail.

% ls -l .git/refs/heads
total 4
-rw------- 1 jhelwig staff 41 Oct 14 16:07 master
% git rev-parse HEAD
af0f70f8962f8b88eef679a1854991cb0f337f89

In the function that updates the Git information for the rest of my shell prompt (heavily modified version of wunjo prompt theme for ZSH), I have the following to get around this:

zgit_info_update() {
    zgit_info=()

    local gitdir=$(git rev-parse --git-dir 2>/dev/null)
    if [ $? -ne 0 ] || [ -z "$gitdir" ]; then
        return
    fi

    # More code ...
}

Laravel Eloquent - Get one Row

You can do this too

Before you use this you must declare the DB facade in the controller Simply put this line for that

use Illuminate\Support\Facades\DB;

Now you can get a row using this

$getUserByEmail = DB::table('users')->where('email', $email)->first();

or by this too

$getUserByEmail = DB::select('SELECT * FROM users WHERE email = ?' , ['[email protected]']);

This one returns an array with only one item in it and while the first one returns an object. Keep that in mind.

Hope this helps.

Dynamic SELECT TOP @var In SQL Server

Or you just put the variable in parenthesis

DECLARE @top INT = 10;

SELECT TOP (@Top) *
FROM <table_name>;

Is there an equivalent of 'which' on the Windows command line?

I have a function in my PowerShell profile named 'which'

function which {
    get-command $args[0]| format-list
}

Here's what the output looks like:

PS C:\Users\fez> which python


Name            : python.exe
CommandType     : Application
Definition      : C:\Python27\python.exe
Extension       : .exe
Path            : C:\Python27\python.exe
FileVersionInfo : File:             C:\Python27\python.exe
                  InternalName:
                  OriginalFilename:
                  FileVersion:
                  FileDescription:
                  Product:
                  ProductVersion:
                  Debug:            False
                  Patched:          False
                  PreRelease:       False
                  PrivateBuild:     False
                  SpecialBuild:     False
                  Language:

Select unique values with 'select' function in 'dplyr' library

The dplyr select function selects specific columns from a data frame. To return unique values in a particular column of data, you can use the group_by function. For example:

library(dplyr)

# Fake data
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE))

# Return the distinct values of x
dat %>%
  group_by(x) %>%
  summarise() 

    x
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10

If you want to change the column name you can add the following:

dat %>%
  group_by(x) %>%
  summarise() %>%
  select(unique.x=x)

This both selects column x from among all the columns in the data frame that dplyr returns (and of course there's only one column in this case) and changes its name to unique.x.

You can also get the unique values directly in base R with unique(dat$x).

If you have multiple variables and want all unique combinations that appear in the data, you can generalize the above code as follows:

set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE), 
                 y=sample(letters[1:5], 100, replace=TRUE))

dat %>% 
  group_by(x,y) %>%
  summarise() %>%
  select(unique.x=x, unique.y=y)

How do I find a particular value in an array and return its index?

Here is a very simple way to do it by hand. You could also use the <algorithm>, as Peter suggests.

#include <iostream>
int find(int arr[], int len, int seek)
{
    for (int i = 0; i < len; ++i)
    {
        if (arr[i] == seek) return i;
    }
    return -1;
}
int main()
{
    int arr[ 5 ] = { 4, 1, 3, 2, 6 };
    int x = find(arr,5,3);
    std::cout << x << std::endl;    
}

What is the difference between '/' and '//' when used for division?

Python 3.x Clarification

Just to complement some previous answers.

It is important to remark that:

a // b

  • Is floor division. As in:

    math.floor(a/b)

  • Is not int division. As in:

    int(a/b)

  • Is not round to 0 float division. As in:

    round(a/b,0)

As a consequence, the way of behaving is different when it comes to positives an negatives numbers as in the following example:

1 // 2 is 0, as in:

math.floor(1/2)

-1 // 2 is -1, as in:

math.floor(-1/2)

Custom checkbox image android

If you use androidx.appcompat:appcompat and want a custom drawable (of type selector with android:state_checked) to work on old platform versions in addition to new platform versions, you need to use

    <CheckBox
        app:buttonCompat="@drawable/..."

instead of

    <CheckBox
        android:button="@drawable/..."

Cannot delete directory with Directory.Delete(path, true)

I had the very same problem under Delphi. And the end result was that my own application was locking the directory I wanted to delete. Somehow the directory got locked when I was writing to it (some temporary files).

The catch 22 was, I made a simple change directory to it's parent before deleting it.

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

You've got no SMTPSecure setting to define the type of authentication being used, and you're running the Host setting with the unnecessary 'ssl://' (PS -- ssl is over port 465, if you need to run it over ssl instead, see the accepted answer here. Here's the lines to add/change:

+ $mail->SMTPSecure = 'tls';

- $mail->Host = "ssl://smtp.gmail.com";
+ $mail->Host = "smtp.gmail.com";

Create instance of generic type whose constructor requires a parameter?

It is still possible, with high performance, by doing the following:

    //
    public List<R> GetAllItems<R>() where R : IBaseRO, new() {
        var list = new List<R>();
        using ( var wl = new ReaderLock<T>( this ) ) {
            foreach ( var bo in this.items ) {
                T t = bo.Value.Data as T;
                R r = new R();
                r.Initialize( t );
                list.Add( r );
            }
        }
        return list;
    }

and

    //
///<summary>Base class for read-only objects</summary>
public partial interface IBaseRO  {
    void Initialize( IDTO dto );
    void Initialize( object value );
}

The relevant classes then have to derive from this interface and initialize accordingly. Please note, that in my case, this code is part of a surrounding class, which already has <T> as generic parameter. R, in my case, also is a read-only class. IMO, the public availability of Initialize() functions has no negative effect on the immutability. The user of this class could put another object in, but this would not modify the underlying collection.

Facebook login "given URL not allowed by application configuration"

Your settings must be incorrect.

Go to http://www.facebook.com/developers/ and edit the application you're working on.

On the "website" tab, look for "Site URL". This should be set to your website's URL "http://yoursite.com/"

Note that if you're using subdomains, you'll also need to update "Site Domain" to be "yoursite.com"

JavaScript load a page on button click

Simple code to redirect page

<!-- html button designing and calling the event in javascript -->
<input id="btntest" type="button" value="Check" 
       onclick="window.location.href = 'http://www.google.com'" />

jQuery rotate/transform

Why not just use, toggleClass on click?

js:

$(this).toggleClass("up");

css:

button.up {
    -webkit-transform: rotate(180deg);
       -moz-transform: rotate(180deg);
        -ms-transform: rotate(180deg);
         -o-transform: rotate(180deg);
            transform: rotate(180deg);
               /* IE6–IE9 */
               filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.9914448613738104, M12=-0.13052619222005157,M21=0.13052619222005157, M22=0.9914448613738104, sizingMethod='auto expand');
                 zoom: 1;
    }

you can also add this to the css:

button{
        -webkit-transition: all 500ms ease-in-out;
        -moz-transition: all 500ms ease-in-out;
        -o-transition: all 500ms ease-in-out;
        -ms-transition: all 500ms ease-in-out;
}

which will add the animation.

PS...

to answer your original question:

you said that it rotates but never stops. When using set timeout you need to make sure you have a condition that will not call settimeout or else it will run forever. So for your code:

<script type="text/javascript">
    $(function() {
     var $elie = $("#bkgimg");
     rotate(0);
     function rotate(degree) {

      // For webkit browsers: e.g. Chrome
    $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
      // For Mozilla browser: e.g. Firefox
    $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});


    /* add a condition here for the extremity */ 
    if(degree < 180){
      // Animate rotation with a recursive call
      setTimeout(function() { rotate(++degree); },65);
     }
    }
    });
    </script>

How to get instance variables in Python?

You will need to first, examine the class, next, examine the bytecode for functions, then, copy the bytecode, and finally, use the __code__.co_varnames. This is tricky because some classes create their methods using constructors like those in the types module. I will provide code for it on GitHub.

ng-change not working on a text input

I've got the same issue, my model is binding from another form, I've added ng-change and ng-model and it still doesn't work:

<input type="hidden" id="pdf-url" class="form-control" ng-model="pdfUrl"/>

<ng-dropzone
  dropzone="dropzone"
  dropzone-config="dropzoneButtonCfg"
  model="pdfUrl">
</ng-dropzone>

An input #pdf-url gets data from dropzone (two ways binding), however, ng-change doesn't work in this case. $scope.$watch is a solution for me:

$scope.$watch('pdfUrl', function updatePdfUrl(newPdfUrl, oldPdfUrl) {
  if (newPdfUrl !== oldPdfUrl) {
    // It's updated - Do something you want here.
  }
});

Hope this help.

mysql update column with value from another table

Second possibility is,

UPDATE TableB 
SET TableB.value = (
    SELECT TableA.value 
    FROM TableA
    WHERE TableA.name = TableB.name
);

How to append strings using sprintf?

Use strcat http://www.cplusplus.com/reference/cstring/strcat/

int main ()
    {
      char str[80];
      strcpy (str,"these ");
      strcat (str,"strings ");
      strcat (str,"are ");
      strcat (str,"concatenated.");
      puts (str);
      return 0;
    }




    Output:


    these strings are concatenated. 

Get user location by IP address

An Alternative to using an API is to use HTML 5 location Navigator to query the browser about the User location. I was looking for a similar approach as in the subject question but I found that HTML 5 Navigator works better and cheaper for my situation. Please consider that your scinario might be different. To get the User position using Html5 is very easy:

function getLocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
    else
    {
        console.log("Geolocation is not supported by this browser.");
     }
}

function showPosition(position)
{
      console.log("Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude); 
}

Try it yourself on W3Schools Geolocation Tutorial

Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX

Found it!

Change host: localhost in config/database.yml to host: 127.0.0.1 to make rails connect over TCP/IP instead of local socket.

development:
  adapter: mysql2
  host: 127.0.0.1
  username: root
  password: xxxx
  database: xxxx

In PHP, how do you change the key of an array element?

This basic function handles swapping array keys and keeping the array in the original order...

public function keySwap(array $resource, array $keys)
{
    $newResource = [];

    foreach($resource as $k => $r){
        if(array_key_exists($k,$keys)){
            $newResource[$keys[$k]] = $r;
        }else{
            $newResource[$k] = $r;
        }
    }

    return $newResource;
}

You could then loop through and swap all 'a' keys with 'z' for example...

$inputs = [
  0 => ['a'=>'1','b'=>'2'],
  1 => ['a'=>'3','b'=>'4']
]

$keySwap = ['a'=>'z'];

foreach($inputs as $k=>$i){
    $inputs[$k] = $this->keySwap($i,$keySwap);
}

Determine the number of rows in a range

That single last line worked perfectly @GSerg.

The other function was what I had been working on but I don't like having to resort to UDF's unless absolutely necessary.

I had been trying a combination of excel and vba and had got this to work - but its clunky compared with your answer.

strArea = Sheets("Oper St Report CC").Range("cc_rev").CurrentRegion.Address
cc_rev_rows = "=ROWS(" & strArea & ")"
Range("cc_rev_count").Formula = cc_rev_rows

Enforcing the type of the indexed members of a Typescript object?

Define interface

interface Settings {
  lang: 'en' | 'da';
  welcome: boolean;
}

Enforce key to be a specific key of Settings interface

private setSettings(key: keyof Settings, value: any) {
   // Update settings key
}

Intellij Cannot resolve symbol on import

in my case the solution was to add the project as maven project, besides the fact that i imported as maven project :P

go to pom.xml -> right click -> add as maven project

Persist javascript variables across pages?

You can use http://rhaboo.org as a wrapper around localStorage. It stores complex objects but doesn't merely stringify and parse the whole thing like most such libraries do. That's really inefficient if you want to store a lot of data and add to it or change it in small chunks. Also, JSON discards a lot of important stuff like non-numerical properties of arrays.

In rhaboo you can write things like this:

var store = Rhaboo.persistent('Some name');

store.write('count', store.count ? store.count+1 : 1);

var laststamp = store.stamp ? store.stamp.toString() : "never";
store.write('stamp', new Date());

store.write('somethingfancy', {
  one: ['man', 'went'],
  2: 'mow',
  went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
});

store.somethingfancy.went[1].mow.write(1, 'lawn');
console.log( store.somethingfancy.went[1].mow[1] ); //says lawn

BTW, I wrote rhaboo

Custom circle button

With the official Material Components library you can use the MaterialButton applying a Widget.MaterialComponents.Button.Icon style.

Something like:

   <com.google.android.material.button.MaterialButton
            android:layout_width="48dp"
            android:layout_height="48dp"
            style="@style/Widget.MaterialComponents.Button.Icon"
            app:icon="@drawable/ic_add"
            app:iconSize="24dp"
            app:iconPadding="0dp"
            android:insetLeft="0dp"
            android:insetTop="0dp"
            android:insetRight="0dp"
            android:insetBottom="0dp"
            app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MyApp.Button.Rounded"
            />

Currently the app:iconPadding="0dp",android:insetLeft,android:insetTop,android:insetRight,android:insetBottom attributes are needed to center the icon on the button avoiding extra padding space.

Use the app:shapeAppearanceOverlay attribute to get rounded corners. In this case you will have a circle.

  <style name="ShapeAppearanceOverlay.MyApp.Button.Rounded" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
  </style>

The final result:

enter image description here

How to Clone Objects

a and b are just two references to the same Person object. They both essentially hold the address of the Person.

There is a ICloneable interface, though relatively few classes support it. With this, you would write:

Person b = a.Clone();

Then, b would be an entirely separate Person.

You could also implement a copy constructor:

public Person(Person src)
{
  // ... 
}

There is no built-in way to copy all the fields. You can do it through reflection, but there would be a performance penalty.

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

I solved a similar problem by closing the project, then re-importing the project (not opening, but re-importing as an eclipse or other project)

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

If you're doing this at any sort of a frequency, heck even on a schedule, I would absolutely, unequivocally never use a DML statement. The cost of writing to the transaction log is just to high, and setting the entire database into SIMPLE recovery mode to truncate one table is ridiculous.

The best way, is unfortunately the hard or laborious way. That being:

  • Drop constraints
  • Truncate table
  • Re-create constraints

My process for doing this involves the following steps:

  1. In SSMS right-click on the table in question, and select View Dependencies
  2. Take note of the tables referenced (if any)
  3. Back in object explorer, expand the Keys node and take note of the foreign keys (if any)
  4. Start scripting (drop / truncate / re-create)

Scripts of this nature should be done within a begin tran and commit tran block.

How to make HTTP Post request with JSON body in Swift

SWIFT 5 People Here :

let json: [String: Any] = ["key": "value"]

        let jsonData = try? JSONSerialization.data(withJSONObject: json)

        // create post request
        let url = URL(string: "http://localhost:1337/postrequest/addData")! //PUT Your URL
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("\(String(describing: jsonData?.count))", forHTTPHeaderField: "Content-Length")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        // insert json data to the request
        request.httpBody = jsonData

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print(error?.localizedDescription ?? "No data")
                return
            }
            let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
            if let responseJSON = responseJSON as? [String: Any] {
                print(responseJSON) //Code after Successfull POST Request
            }
        }

        task.resume()

How to use sed to remove all double quotes within a file

Additional comment. Yes this works:

    sed 's/\"//g' infile.txt  > outfile.txt

(however with batch gnu sed, will just print to screen)

In batch scripting (GNU SED), this was needed:

    sed 's/\x22//g' infile.txt  > outfile.txt

Using jQuery to center a DIV on the screen

What I have here is a "center" method that ensures the element you are attempting to center is not only of "fixed" or "absolute" positioning, but it also ensures that the element you are centering is smaller than its parent, this centers and element relative to is parent, if the elements parent is smaller than the element itself, it will pillage up the DOM to the next parent, and center it relative to that.

$.fn.center = function () {
        /// <summary>Centers a Fixed or Absolute positioned element relative to its parent</summary>

        var element = $(this),
            elementPos = element.css('position'),
            elementParent = $(element.parent()),
            elementWidth = element.outerWidth(),
            parentWidth = elementParent.width();

        if (parentWidth <= elementWidth) {
            elementParent = $(elementParent.parent());
            parentWidth = elementParent.width();
        }

        if (elementPos === "absolute" || elementPos === "fixed") {
            element.css('right', (parentWidth / 2) - elementWidth / 2 + 'px');
        }
    };

Calculating text width

I could not get any of the solutions listed to work 100%, so came up with this hybrid, based on ideas from @chmurson (which was in turn based on @Okamera) and also from @philfreo:

(function ($)
{
    var calc;
    $.fn.textWidth = function ()
    {
        // Only create the dummy element once
        calc = calc || $('<span>').css('font', this.css('font')).css({'font-size': this.css('font-size'), display: 'none', 'white-space': 'nowrap' }).appendTo('body');
        var width = calc.html(this.html()).width();
        // Empty out the content until next time - not needed, but cleaner
        calc.empty();
        return width;
    };
})(jQuery);

Notes:

  • this inside a jQuery extension method is already a jQuery object, so no need for all the extra $(this) that many examples have.
  • It only adds the dummy element to the body once, and reuses it.
  • You should also specify white-space: nowrap, just to ensure that it measures it as a single line (and not line wrap based on other page styling).
  • I could not get this to work using font alone and had to explicitly copy font-size as well. Not sure why yet (still investigating).
  • This does not support input fields that way @philfreo does.

AngularJS: factory $http.get JSON file

Okay, here's a list of things to look into:

1) If you're not running a webserver of any kind and just testing with file://index.html, then you're probably running into same-origin policy issues. See:

https://code.google.com/archive/p/browsersec/wikis/Part2.wiki#Same-origin_policy

Many browsers don't allow locally hosted files to access other locally hosted files. Firefox does allow it, but only if the file you're loading is contained in the same folder as the html file (or a subfolder).

2) The success function returned from $http.get() already splits up the result object for you:

$http({method: 'GET', url: '/someUrl'}).success(function(data, status, headers, config) {

So it's redundant to call success with function(response) and return response.data.

3) The success function does not return the result of the function you pass it, so this does not do what you think it does:

var mainInfo = $http.get('content.json').success(function(response) {
        return response.data;
    });

This is closer to what you intended:

var mainInfo = null;
$http.get('content.json').success(function(data) {
    mainInfo = data;
});

4) But what you really want to do is return a reference to an object with a property that will be populated when the data loads, so something like this:

theApp.factory('mainInfo', function($http) { 

    var obj = {content:null};

    $http.get('content.json').success(function(data) {
        // you can do some processing here
        obj.content = data;
    });    

    return obj;    
});

mainInfo.content will start off null, and when the data loads, it will point at it.

Alternatively you can return the actual promise the $http.get returns and use that:

theApp.factory('mainInfo', function($http) { 
    return $http.get('content.json');
});

And then you can use the value asynchronously in calculations in a controller:

$scope.foo = "Hello World";
mainInfo.success(function(data) { 
    $scope.foo = "Hello "+data.contentItem[0].username;
});

Hive: Filtering Data between Specified Dates when Date is a String

Just like SQL, Hive supports BETWEEN operator for more concise statement:

SELECT *
  FROM your_table
  WHERE your_date_column BETWEEN '2010-09-01' AND '2013-08-31';

button image as form input submit button?

You can also use a second image to give the effect of a button being pressed. Just add the "pressed" button image in the HTML before the input image:

<img src="http://integritycontractingofva.com/images/go2.jpg" id="pressed"/>
<input id="unpressed" type="submit" value=" " style="background:url(http://integritycontractingofva.com/images/go1.jpg) no-repeat;border:none;"/>

And use CSS to change the opacity of the "unpressed" image on hover:

#pressed, #unpressed{position:absolute; left:0px;}
#unpressed{opacity: 1; cursor: pointer;}
#unpressed:hover{opacity: 0;}

I use it for the blue "GO" button on this page

Excel 2010 VBA Referencing Specific Cells in other worksheets

Sub Results2()

    Dim rCell As Range
    Dim shSource As Worksheet
    Dim shDest As Worksheet
    Dim lCnt As Long

    Set shSource = ThisWorkbook.Sheets("Sheet1")
    Set shDest = ThisWorkbook.Sheets("Sheet2")

    For Each rCell In shSource.Range("A1", shSource.Cells(shSource.Rows.Count, 1).End(xlUp)).Cells
        lCnt = lCnt + 1
        shDest.Range("A4").Offset(0, lCnt * 4).Formula = "=" & rCell.Address(False, False, , True) & "+" & rCell.Offset(0, 1).Address(False, False, , True)
    Next rCell

End Sub

This loops through column A of sheet1 and creates a formula in sheet2 for every cell. To find the last cell in Sheet1, I start at the bottom (shSource.Rows.Count) and .End(xlUp) to get the last cell in the column that's not blank.

To create the elements of the formula, I use the Address property of the cell on Sheet. I'm using three of the arguments to Address. The first two are RowAbsolute and ColumnAbsolute, both set to false. I don't care about the third argument, but I set the fourth argument (External) to True so that it includes the sheet name.

I prefer to go from Source to Destination rather than the other way. But that's just a personal preference. If you want to work from the destination,

Sub Results3()

    Dim i As Long, lCnt As Long
    Dim sh As Worksheet

    lCnt = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("Sheet1").Columns(1))
    Set sh = ThisWorkbook.Sheets("Sheet2")

    Const sSOURCE As String = "Sheet1!"

    For i = 1 To lCnt
        sh.Range("A1").Offset(0, 4 * (i - 1)).Formula = "=" & sSOURCE & "A" & i & " + " & sSOURCE & "B" & i
    Next i

End Sub

Get just the filename from a path in a Bash script

basename and dirname solutions are more convenient. Those are alternative commands:

FILE_PATH="/opt/datastores/sda2/test.old.img"
echo "$FILE_PATH" | sed "s/.*\///"

This returns test.old.img like basename.

This is salt filename without extension:

echo "$FILE_PATH" | sed -r "s/.+\/(.+)\..+/\1/"

It returns test.old.

And following statement gives the full path like dirname command.

echo "$FILE_PATH" | sed -r "s/(.+)\/.+/\1/"

It returns /opt/datastores/sda2

How can I initialize a MySQL database with schema in a Docker container?

Another way based on a merge of serveral responses here before :

docker-compose file :

version: "3"
services:
    db:
      container_name: db
      image: mysql
      ports:
       - "3306:3306"  
      environment:
         - MYSQL_ROOT_PASSWORD=mysql
         - MYSQL_DATABASE=db

      volumes:
         - /home/user/db/mysql/data:/var/lib/mysql
         - /home/user/db/mysql/init:/docker-entrypoint-initdb.d/:ro

where /home/user.. is a shared folder on the host

And in the /home/user/db/mysql/init folder .. just drop one sql file, with any name, for example init.sql containing :

CREATE DATABASE mydb;
GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'%' IDENTIFIED BY 'mysql';
GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'localhost' IDENTIFIED BY 'mysql';
USE mydb
CREATE TABLE CONTACTS (
    [ ... ]
);
INSERT INTO CONTACTS VALUES ...
[ ... ]

According to the official mysql documentation, you can put more than one sql file in the docker-entrypoint-initdb.d, they are executed in the alphabetical order

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

Probably the most elegant way of doing this is to do it in one step. See val().

$("#text").val(function(i, val) {
  return val.replace('.', ':');
});

compared to:

var val = $("#text").val();
$("#text").val(val.replace('.', ':'));

From the docs:

.val( function(index, value) )

function(index, value)A function returning the value to set.

This method is typically used to set the values of form fields. For <select multiple="multiple"> elements, multiple s can be selected by passing in an array.

The .val() method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:

$('input:text.items').val(function(index, value) {
  return value + ' ' + this.className;
});

This example appends the string " items" to the text inputs' values.

This requires jQuery 1.4+.

Find the most popular element in int[] array

below code can be put inside a main method

    // TODO Auto-generated method stub
    Integer[] a = { 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 1, 2, 2, 2, 2, 3, 4, 2 };
    List<Integer> list = new ArrayList<Integer>(Arrays.asList(a));
    Set<Integer> set = new HashSet<Integer>(list);
    int highestSeq = 0;
    int seq = 0;
    for (int i : set) {
        int tempCount = 0;
        for (int l : list) {
            if (i == l) {
                tempCount = tempCount + 1;
            }
            if (tempCount > highestSeq) {
                highestSeq = tempCount;
                seq = i;
            }
        }

    }

    System.out.println("highest sequence is " + seq + " repeated for " + highestSeq);

Turn off enclosing <p> tags in CKEditor 3.0

Found it!

ckeditor.js line #91 ... search for

B.config.enterMode==3?'div':'p'

change to

B.config.enterMode==3?'div':'' (NO P!)

Dump your cache and BAM!

Sort array of objects by single key with date value

The Array.sort() method sorts the elements of an array in place and returns the array. Be careful with Array.sort() as it's not Immutable. For immutable sort use immutable-sort.

This method is to sort the array using your current updated_at in ISO format. We use new Data(iso_string).getTime() to convert ISO time to Unix timestamp. A Unix timestamp is a number that we can do simple math on. We subtract the first and second timestamp the result is; if the first timestamp is bigger than the second the return number will be positive. If the second number is bigger than the first the return value will be negative. If the two are the same the return will be zero. This alines perfectly with the required return values for the inline function.

For ES6:

arr.sort((a,b) => new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime());

For ES5:

arr.sort(function(a,b){ 
 return new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime();
});

If you change your updated_at to be unix timestamps you can do this:

For ES6:

arr.sort((a,b) => a.updated_at - b.updated_at);

For ES5:

arr.sort(function(a,b){ 
 return a.updated_at - b.updated_at;
});

At the time of this post, modern browsers do not support ES6. To use ES6 in modern browsers use babel to transpile the code to ES5. Expect browser support for ES6 in the near future.

Array.sort() should receave a return value of one of 3 possible outcomes:

  • A positive number (first item > second item)
  • A negative number (first item < second item)
  • 0 if the two items are equal

Note that the return value on the inline function can be any positive or negative number. Array.Sort() does not care what the return number is. It only cares if the return value is positive, negative or zero.

For Immutable sort: (example in ES6)

const sort = require('immutable-sort');
const array = [1, 5, 2, 4, 3];
const sortedArray = sort(array);

You can also write it this way:

import sort from 'immutable-sort';
const array = [1, 5, 2, 4, 3];
const sortedArray = sort(array);

The import-from you see is a new way to include javascript in ES6 and makes your code look very clean. My personal favorite.

Immutable sort doesn't mutate the source array rather it returns a new array. Using const is recommended on immutable data.

Node.js/Express routing with get params

Your route isn't ok, it should be like this (with ':')

app.get('/documents/:format/:type', function (req, res) {
   var format = req.params.format,
       type = req.params.type;
});

Also you cannot interchange parameter order unfortunately. For more information on req.params (and req.query) check out the api reference here.

Getting DOM elements by classname

There is also another approach without the use of DomXPath or Zend_Dom_Query.

Based on dav's original function, I wrote the following function that returns all the children of the parent node whose tag and class match the parameters.

function getElementsByClass(&$parentNode, $tagName, $className) {
    $nodes=array();

    $childNodeList = $parentNode->getElementsByTagName($tagName);
    for ($i = 0; $i < $childNodeList->length; $i++) {
        $temp = $childNodeList->item($i);
        if (stripos($temp->getAttribute('class'), $className) !== false) {
            $nodes[]=$temp;
        }
    }

    return $nodes;
}

suppose you have a variable $html the following HTML:

<html>
 <body>
  <div id="content_node">
    <p class="a">I am in the content node.</p>
    <p class="a">I am in the content node.</p>
    <p class="a">I am in the content node.</p>    
  </div>
  <div id="footer_node">
    <p class="a">I am in the footer node.</p>
  </div>
 </body>
</html>

use of getElementsByClass is as simple as:

$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($html);
$content_node=$dom->getElementById("content_node");

$div_a_class_nodes=getElementsByClass($content_node, 'div', 'a');//will contain the three nodes under "content_node".

How can I restore the MySQL root user’s full privileges?

i also remove privileges of root and database not showing in mysql console when i was a root user, so changed user by mysql>mysql -u 'userName' -p; and password;

UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';

FLUSH PRIVILEGES;

after this command it all show database's in root .

Thanks

Java java.sql.SQLException: Invalid column index on preparing statement

In date '?', the '?' is a literal string with value ?, not a parameter placeholder, so your query does not have any parameters. The date is a shorthand cast from (literal) string to date. You need to replace date '?' with ? to actually have a parameter.

Also if you know it is a date, then use setDate(..) and not setString(..) to set the parameter.

What's the difference between a 302 and a 307 redirect?

Originally there was just 302

Response What browsers should do
302 Found Redo request with new url

The idea is that:

  • if you were doing a GET at some location, you would redo your GET to the new URL
  • if you were doing a POST at some location, you would redo your POST to the new URL
  • if you were doing a PUT at some location, you would redo your PUT to the new URL
  • if you were doing a DELETE at some location, you would redo your DELETE to the new URL
  • etc

Unfortunately every browser did it wrong. When getting a 302, they would always switch to GET at the new URL, rather than retrying the request with the same verb (e.g., POST):

  • Mosaic did it wrong
  • Netscape copied the bugs in Mosaic; so they got it wrong
  • Internet Explorer copied the bugs in Netscape; so they got it wrong

It became de-facto wrong.

All browsers got 302 wrong. So 303 and 307 were created.

Response What browsers should do What browsers actually do
302 Found Redo request with new url GET with new url
303 See Other GET with new url GET with new url
307 Temporary Redirect Redo request with new url Redo request with new url

In chart form

The 5 different kinds of redirects:

+------------------------------------------------------------+
¦           ¦                Switch to GET?                  ¦
¦           ¦------------------------------------------------¦
¦ Temporary ¦          No            ¦         Yes           ¦
¦-----------+------------------------+-----------------------¦
¦ No        ¦ 308 Permanent Redirect ¦ 301 Moved Permanently ¦
¦-----------+------------------------+-----------------------¦
¦ Yes       ¦ 307 Temporary Redirect ¦ 303 See Other         ¦
¦           ¦ 302 Found (intended)   ¦ 302 Found (actual)    ¦
+------------------------------------------------------------+

Alternatively:

Response Switch to get? Temporary?
301 Moved Permanently No No
302 Found (intended) No Yes
302 Found (actual) Yes Yes
303 See Other Yes Yes
307 Temporary Redirect No Yes
308 Permanent Redirect No No

Create HTTP post request and receive response using C# console application

HttpWebRequest request =(HttpWebRequest)WebRequest.Create("some url");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)";
request.Accept = "/";
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
doc.Save(request.GetRequestStream());
HttpWebResponse resp = request.GetResponse() as HttpWebResponse;

Hope it helps

Java: getMinutes and getHours

I would recommend looking ad joda time. http://www.joda.org/joda-time/

I was afraid of adding another library to my thick project, but it's just easy and fast and smart and awesome. Plus, it plays nice with existing code, to some extent.

No converter found capable of converting from type to type

If you look at the exception stack trace it says that, it failed to convert from ABDeadlineType to DeadlineType. Because your repository is going to return you the objects of ABDeadlineType. How the spring-data-jpa will convert into the other one(DeadlineType). You should return the same type from repository and then have some intermediate util class to convert it into your model class.

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<ABDeadlineType> findAllSummarizedBy();
}

What is process.env.PORT in Node.js?

  • if you run node index.js ,Node will use 3000

  • If you run PORT=4444 node index.js, Node will use process.env.PORT which equals to 4444 in this example. Run with sudo for ports below 1024.

regex to remove all text before a character

In Javascript I would use /.*_/, meaning: match everything until _ (including)

Example:

console.log( 'hello_world'.replace(/.*_/,'') ) // 'world'

Conda version pip install -r requirements.txt --target ./lib

To create an environment named py37 with python 3.7, using the channel conda-forge and a list of packages:

conda create -y --name py37 python=3.7
conda install --force-reinstall -y -q --name py37 -c conda-forge --file requirements.txt
conda activate py37
...
conda deactivate

Flags explained:

  • -y: Do not ask for confirmation.
  • --force-reinstall: Install the package even if it already exists.
  • -q: Do not display progress bar.
  • -c: Additional channel to search for packages. These are URLs searched in the order

The ansible-role dockpack.base_miniconda can manage conda environments and can be used to create a docker base image.

Alternatively you can create an environment.yml file instead of requirements.txt:

name: py37
channels:
  - conda-forge
dependencies:
  - python=3.7
  - numpy=1.9.*
  - pandas

Use this command to list the environments you have:

conda info --envs

Use this command to remove the environment:

conda env remove -n py37

How to detect iPhone 5 (widescreen devices)?

This way you can detect device family.

    #import <sys/utsname.h>
    NSString* deviceName()
    {
        struct utsname systemInformation;
        uname(&systemInformation);
        NSString *result = [NSString stringWithCString:systemInformation.machine
                                              encoding:NSUTF8StringEncoding];
        return result;
    }

    #define isIPhone5  [deviceName() rangeOfString:@"iPhone5,"].location != NSNotFound
    #define isIPhone5S [deviceName() rangeOfString:@"iPhone6,"].location != NSNotFound

Uncaught ReferenceError: function is not defined with onclick

Make sure you are using Javascript module or not?! if using js6 modules your html events attributes won't work. in that case you must bring your function from global scope to module scope. Just add this to your javascript file: window.functionName= functionName;

example:

<h1 onClick="functionName">some thing</h1>

How do I convert datetime to ISO 8601 in PHP

After PHP 5 you can use this: echo date("c"); form ISO 8601 formatted datetime.

http://ideone.com/nD7piL

Note for comments:

Regarding to this, both of these expressions are valid for timezone, for basic format: ±[hh]:[mm], ±[hh][mm], or ±[hh].

But note that, +0X:00 is correct, and +0X00 is incorrect for extended usage. So it's better to use date("c"). A similar discussion here.

Predicate in Java

Adding up to what Micheal has said:

You can use Predicate as follows in filtering collections in java:

public static <T> Collection<T> filter(final Collection<T> target,
   final Predicate<T> predicate) {
  final Collection<T> result = new ArrayList<T>();
  for (final T element : target) {
   if (predicate.apply(element)) {
    result.add(element);
   }
  }
  return result;
}

one possible predicate can be:

final Predicate<DisplayFieldDto> filterCriteria = 
                    new Predicate<DisplayFieldDto>() {
   public boolean apply(final DisplayFieldDto displayFieldDto) {
    return displayFieldDto.isDisplay();
   }
  };

Usage:

 final List<DisplayFieldDto> filteredList=
 (List<DisplayFieldDto>)filter(displayFieldsList, filterCriteria);

Java Currency Number format

If you want work on currencies, you have to use BigDecimal class. The problem is, there's no way to store some float numbers in memory (eg. you can store 5.3456, but not 5.3455), which can effects in bad calculations.

There's an nice article how to cooperate with BigDecimal and currencies:

http://www.javaworld.com/javaworld/jw-06-2001/jw-0601-cents.html

Adding a new entry to the PATH variable in ZSH

OPTION 1: Add this line to ~/.zshrc:

export "PATH=$HOME/pear/bin:$PATH"

After that you need to run source ~/.zshrc in order your changes to take affect OR close this window and open a new one

OPTION 2: execute it inside the terminal console to add this path only to the current terminal window session. When you close the window/session, it will be lost.

java: How can I do dynamic casting of a variable from one type to another?

Just thought I would post something that I found quite useful and could be possible for someone who experiences similar needs.

The following method was a method I wrote for my JavaFX application to avoid having to cast and also avoid writing if object x instance of object b statements every time the controller was returned.

public <U> Optional<U> getController(Class<U> castKlazz){
    try {
        return Optional.of(fxmlLoader.<U>getController());
    }catch (Exception e){
        e.printStackTrace();
    }
    return Optional.empty();
}

The method declaration for obtaining the controller was

public <T> T getController()

By using type U passed into my method via the class object, it could be forwarded to the method get controller to tell it what type of object to return. An optional object is returned in case the wrong class is supplied and an exception occurs in which case an empty optional will be returned which we can check for.

This is what the final call to the method looked like (if present of the optional object returned takes a Consumer

getController(LoadController.class).ifPresent(controller->controller.onNotifyComplete());

Writing a Python list of lists to a csv file

How about dumping the list of list into pickle and restoring it with pickle module? It's quite convenient.

>>> import pickle
>>> 
>>> mylist = [1, 'foo', 'bar', {1, 2, 3}, [ [1,4,2,6], [3,6,0,10]]]
>>> with open('mylist', 'wb') as f:
...     pickle.dump(mylist, f) 


>>> with open('mylist', 'rb') as f:
...      mylist = pickle.load(f)
>>> mylist
[1, 'foo', 'bar', {1, 2, 3}, [[1, 4, 2, 6], [3, 6, 0, 10]]]
>>> 

Unable to cast object of type 'System.DBNull' to type 'System.String`

A shorter form can be used:

return (accountNumber == DBNull.Value) ? string.Empty : accountNumber.ToString()

EDIT: Haven't paid attention to ExecuteScalar. It does really return null if the field is absent in the return result. So use instead:

return (accountNumber == null) ? string.Empty : accountNumber.ToString() 

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

I use a simple approach that handles stale lock files.

Note that some of the above solutions that store the pid, ignore the fact that the pid can wrap around. So - just checking if there is a valid process with the stored pid is not enough, especially for long running scripts.

I use noclobber to make sure only one script can open and write to the lock file at one time. Further, I store enough information to uniquely identify a process in the lockfile. I define the set of data to uniquely identify a process to be pid,ppid,lstart.

When a new script starts up, if it fails to create the lock file, it then verifies that the process that created the lock file is still around. If not, we assume the original process died an ungraceful death, and left a stale lock file. The new script then takes ownership of the lock file, and all is well the world, again.

Should work with multiple shells across multiple platforms. Fast, portable and simple.

#!/usr/bin/env sh
# Author: rouble

LOCKFILE=/var/tmp/lockfile #customize this line

trap release INT TERM EXIT

# Creates a lockfile. Sets global variable $ACQUIRED to true on success.
# 
# Returns 0 if it is successfully able to create lockfile.
acquire () {
    set -C #Shell noclobber option. If file exists, > will fail.
    UUID=`ps -eo pid,ppid,lstart $$ | tail -1`
    if (echo "$UUID" > "$LOCKFILE") 2>/dev/null; then
        ACQUIRED="TRUE"
        return 0
    else
        if [ -e $LOCKFILE ]; then 
            # We may be dealing with a stale lock file.
            # Bring out the magnifying glass. 
            CURRENT_UUID_FROM_LOCKFILE=`cat $LOCKFILE`
            CURRENT_PID_FROM_LOCKFILE=`cat $LOCKFILE | cut -f 1 -d " "`
            CURRENT_UUID_FROM_PS=`ps -eo pid,ppid,lstart $CURRENT_PID_FROM_LOCKFILE | tail -1`
            if [ "$CURRENT_UUID_FROM_LOCKFILE" == "$CURRENT_UUID_FROM_PS" ]; then 
                echo "Script already running with following identification: $CURRENT_UUID_FROM_LOCKFILE" >&2
                return 1
            else
                # The process that created this lock file died an ungraceful death. 
                # Take ownership of the lock file.
                echo "The process $CURRENT_UUID_FROM_LOCKFILE is no longer around. Taking ownership of $LOCKFILE"
                release "FORCE"
                if (echo "$UUID" > "$LOCKFILE") 2>/dev/null; then
                    ACQUIRED="TRUE"
                    return 0
                else
                    echo "Cannot write to $LOCKFILE. Error." >&2
                    return 1
                fi
            fi
        else
            echo "Do you have write permissons to $LOCKFILE ?" >&2
            return 1
        fi
    fi
}

# Removes the lock file only if this script created it ($ACQUIRED is set), 
# OR, if we are removing a stale lock file (first parameter is "FORCE") 
release () {
    #Destroy lock file. Take no prisoners.
    if [ "$ACQUIRED" ] || [ "$1" == "FORCE" ]; then
        rm -f $LOCKFILE
    fi
}

# Test code
# int main( int argc, const char* argv[] )
echo "Acquring lock."
acquire
if [ $? -eq 0 ]; then 
    echo "Acquired lock."
    read -p "Press [Enter] key to release lock..."
    release
    echo "Released lock."
else
    echo "Unable to acquire lock."
fi

Sorting string array in C#

If you have problems with numbers (say 1, 2, 10, 12 which will be sorted 1, 10, 12, 2) you can use LINQ:

var arr = arr.OrderBy(x=>x).ToArray();

Node / Express: EADDRINUSE, Address already in use - Kill server

You can also go the command line route:

ps aux | grep node

to get the process ids.

Then:

kill -9 PID

Doing the -9 on kill sends a SIGKILL (instead of a SIGTERM). SIGTERM has been ignored by node for me sometimes.

Reporting Services export to Excel with Multiple Worksheets

As @huttelihut pointed out, this is now possible as of SQL Server 2008 R2 - Read More Here

Prior to 2008 R2 it does't appear possible but MSDN Social has some suggested workarounds.

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

Watching this course https://app.pluralsight.com/library/courses/angular-2-getting-started-update/discussion

The author explains that new version of JavaScript has for of and for in, the for of is to enumerate objects and the for in is to enumerate the index of the array.

Object passed as parameter to another class, by value or reference?

I found the other examples unclear, so I did my own test which confirmed that a class instance is passed by reference and as such actions done to the class will affect the source instance.

In other words, my Increment method modifies its parameter myClass everytime its called.

class Program
{
    static void Main(string[] args)
    {
        MyClass myClass = new MyClass();
        Console.WriteLine(myClass.Value);  // Displays 1
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 2
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 3           
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 4
        Console.WriteLine("Hit Enter to exit.");
        Console.ReadLine();
    }

    public static void Increment(MyClass myClassRef)
    {
        myClassRef.Value++;
    }
}

public class MyClass
{
    public int Value {get;set;}
    public MyClass()
    {
        Value = 1;
    }
}

When do you use POST and when do you use GET?

In PHP, POST data limit is usually set by your php.ini. GET is limited by server/browser settings I believe - usually around 255 bytes.

PostgreSQL - max number of parameters in "IN" clause?

Just tried it. the answer is -> out-of-range integer as a 2-byte value: 32768

How to modify WooCommerce cart, checkout pages (main theme portion)

I used the page-checkout.php template to change the header for my cart page. I renamed it to page-cart.php in my /wp-content/themes/childtheme/woocommerce/. This gives you more control over the wrapping html, header and footer.

How to temporarily exit Vim and go back

To extend user Zen's answer, you could add the following line in your ~/.vimrc file to allow quick toggling between Bash and Vim:

noremap <C-d> :sh<cr>

Excel VBA Copy a Range into a New Workbook

Modify to suit your specifics, or make more generic as needed:

Private Sub CopyItOver()
  Set NewBook = Workbooks.Add
  Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
  NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
  NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

How do I configure Apache 2 to run Perl CGI scripts?

As of Ubuntu 12.04 (Precise Pangolin) (and perhaps a release or two before) simply installing apache2 and mod-perl via Synaptic and placing your CGI scripts in /usr/lib/cgi-bin is really all you need to do.

Incorrect syntax near ''

Panagiotis Kanavos is right, sometimes copy and paste T-SQL can make appear unwanted characters...

I finally found a simple and fast way (only Notepad++ needed) to detect which character is wrong, without having to manually rewrite the whole statement: there is no need to save any file to disk.

It's pretty quick, in Notepad++:

  • Click "New file"
  • Check under the menu "Encoding": the value should be "Encode in UTF-8"; set it if it's not
  • Paste your text enter image description here
  • From Encoding menu, now click "Encode in ANSI" and check again your text enter image description here

You should easily find the wrong character(s)

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Upgrade pip as follows:

curl https://bootstrap.pypa.io/get-pip.py | python

Note: You may need to use sudo python above if not in a virtual environment.

What's happening:

Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.

(Note that upgrading pip via pip install --upgrade pip will also not upgrade it correctly. It is a chicken-and-egg issue)

This thread explains it (thanks to this Twitter post):

Mac users who use pip and PyPI:

If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:

curl https://bootstrap.pypa.io/get-pip.py | python

and we recommend you do that by April 8th.

Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/

Also, the Python status page:

Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC

Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC

Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:

pip install --upgrade setuptools

How to convert string to date to string in Swift iOS?

//String to Date Convert

var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)


//CONVERT FROM NSDate to String  

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" 
var dateString = dateFormatter.stringFromDate(date)
println(dateString)  

Is there a way to select sibling nodes?

The following function will return an array containing all the siblings of the given element.

function getSiblings(elem) {
    return [...elem.parentNode.children].filter(item => item !== elem);
}

Just pass the selected element into the getSiblings() function as it's only parameter.

How to remove all line breaks from a string

If you want to remove all control characters, including CR and LF, you can use this:

myString.replace(/[^\x20-\x7E]/gmi, "")

It will remove all non-printable characters. This are all characters NOT within the ASCII HEX space 0x20-0x7E. Feel free to modify the HEX range as needed.

CSS Disabled scrolling

I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype

Beautiful way to remove GET-variables with PHP?

Couldn't you use the server variables to do this?

Or would this work?:

unset($_GET['page']);
$url = $_SERVER['SCRIPT_NAME'] ."?".http_build_query($_GET);

Just a thought.

Can you pass parameters to an AngularJS controller on creation?

You can do it when setting up the routes for e.g.

 .when('/newitem/:itemType', {
            templateUrl: 'scripts/components/items/newEditItem.html',
            controller: 'NewEditItemController as vm',
            resolve: {
              isEditMode: function () {
                return true;
              }
            },
        })

And later use it as

(function () {
  'use strict';

  angular
    .module('myApp')
    .controller('NewEditItemController', NewEditItemController);

  NewEditItemController.$inject = ['$http','isEditMode',$routeParams,];

  function NewEditItemController($http, isEditMode, $routeParams) {
    /* jshint validthis:true */

    var vm = this;
    vm.isEditMode = isEditMode;
    vm.itemType = $routeParams.itemType;
  }
})();

So here when we set up the route we sent :itemType and retrive it later from $routeParams.

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

The device is temporarily restricted error appears in MIUI 8.5. To resolve the error you need to make WIFI off and make mobile data on and then enable the option “Install via USB” under "Developer Options" in "Settings". it will work for you.

Check if table exists in SQL Server

We always use the OBJECT_ID style for as long as I remember

IF OBJECT_ID('*objectName*', 'U') IS NOT NULL 

Meaning of "[: too many arguments" error from if [] (square brackets)

Some times If you touch the keyboard accidentally and removed a space.

if [ "$myvar" = "something"]; then
    do something
fi

Will trigger this error message. Note the space before ']' is required.