Programs & Examples On #Mozilla prism

Mozilla prism is an opensource system to bring web applications to the desktop

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

You can use an Extention:

public static void CopyOnlyEqualProperties<T>(this T objDest, object objSource) where T : class
    {
        foreach (PropertyInfo propInfo in typeof(T).GetProperties())
            if (objSource.GetType().GetProperties().Any(z => z.Name == propInfo.Name && z.GetType() == propInfo.GetType()))
                propInfo.SetValue(objDest, objSource.GetType().GetProperties().First(z => z.Name == propInfo.Name && z.GetType() == propInfo.GetType()).GetValue(objSource));
    }

In Code:

public class BaseClass
{
  public string test{ get; set;}
}
public Derived : BaseClass
{
//Some properies
}

public void CopyProps()
{
   BaseClass baseCl =new BaseClass();
   baseCl.test="Hello";
   Derived drv=new Derived();
   drv.CopyOnlyEqualProperties(baseCl);
   //Should return Hello to the console now in derived class.
   Console.WriteLine(drv.test);

}

Git ignore file for Xcode projects

Best of all,

gitignore.io

Go and choose your language, and then it'll give you the file.

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

I can confirm this works. I exported the reg file after I had made the adjustments and then put it in a logon script like this:

REM ------ IE Auto Detect Settings FIX ------------------
REG IMPORT \\mydomain.local\netlogon\IE-Autofix.reg 2>NUL

How to add text inside the doughnut chart using Chart.js?

Alesana's solution works very nicely for me in general, but like others, I wanted to be able to specify where line breaks occur. I made some simple modifications to wrap lines at '\n' characters, as long as the text is already being wrapped. A more complete solution would force wrapping if there are any '\n' characters in the text, but I don't have time at the moment to make that work with font sizing. The change also centers a little better horizontally when wrapping (avoids trailing spaces). The code's below (I can't post comments yet).

It would be cool if someone put this plug-in on GitHub...

Chart.pluginService.register({
  beforeDraw: function(chart) {
    if (chart.config.options.elements.center) {
      // Get ctx from string
      var ctx = chart.chart.ctx;

      // Get options from the center object in options
      var centerConfig = chart.config.options.elements.center;
      var fontStyle = centerConfig.fontStyle || 'Arial';
      var txt = centerConfig.text;
      var color = centerConfig.color || '#000';
      var maxFontSize = centerConfig.maxFontSize || 75;
      var sidePadding = centerConfig.sidePadding || 20;
      var sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2)
      // Start with a base font of 30px
      ctx.font = "30px " + fontStyle;

      // Get the width of the string and also the width of the element minus 10 to give it 5px side padding
      var stringWidth = ctx.measureText(txt).width;
      var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;

      // Find out how much the font can grow in width.
      var widthRatio = elementWidth / stringWidth;
      var newFontSize = Math.floor(30 * widthRatio);
      var elementHeight = (chart.innerRadius * 2);

      // Pick a new font size so it will not be larger than the height of label.
      var fontSizeToUse = Math.min(newFontSize, elementHeight, maxFontSize);
      var minFontSize = centerConfig.minFontSize;
      var lineHeight = centerConfig.lineHeight || 25;
      var wrapText = false;

      if (minFontSize === undefined) {
        minFontSize = 20;
      }

      if (minFontSize && fontSizeToUse < minFontSize) {
        fontSizeToUse = minFontSize;
        wrapText = true;
      }

      // Set font settings to draw it correctly.
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
      var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);
      ctx.font = fontSizeToUse + "px " + fontStyle;
      ctx.fillStyle = color;

      if (!wrapText) {
        ctx.fillText(txt, centerX, centerY);
        return;
      }

      var lines = [];
      var chunks = txt.split('\n');
      for (var m = 0; m < chunks.length; m++) {
        var words = chunks[m].split(' ');
        var line;

        // Break words up into multiple lines if necessary
        for (var n = 0; n < words.length; n++) {
          var testLine = (n == 0) ? words[n] : line + ' ' + words[n];
          var metrics = ctx.measureText(testLine);
          var testWidth = metrics.width;
          if (testWidth > elementWidth && n > 0) {
            lines.push(line);
            line = words[n];
          } else {
            line = testLine;
          }
        }
        lines.push(line);
      }

      // Move the center up depending on line height and number of lines
      centerY -= ((lines.length-1) / 2) * lineHeight;

      // All but last line
      for (var n = 0; n < lines.length; n++) {
        ctx.fillText(lines[n], centerX, centerY);
        centerY += lineHeight;
      }
    }
  }
});

Cannot import keras after installation

I had pip referring by default to pip3, which made me download the libs for python3. On the contrary I launched the shell as python (which opened python 2) and the library wasn't installed there obviously.

Once I matched the names pip3 -> python3, pip -> python (2) all worked.

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

Here is another option which did the trick for me: https://dba.stackexchange.com/a/44340

There I used Option B. This is not my idea so all credit goes to the original author. I am just putting it in here also as I know that sometimes links don't function and it is recommended to have the full story handy.

Just one tip from me: First resolve the schema incompatibilities if any. Then pouring in the data should be a breeze.


Option A: Script out database in compatibility mode using Generate script option:

Note: If you script out database with schema and data, depending on your data size, the script will be massive and wont be handled by SSMS, sqlcmd or osql (might be in GB as well).

enter image description here

Option B:

First script out tables first with all Indexes, FK's, etc and create blank tables in the destination database - option with SCHEMA ONLY (No data).

Use BCP to insert data

I. BCP out the data using below script. Set SSMS in Text Mode and copy the output generated by below script in a bat file.

-- save below output in a bat file by executing below in SSMS in TEXT mode

-- clean up: create a bat file with this command --> del D:\BCP\*.dat 

select '"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\bcp.exe" ' /* path to BCP.exe */
    +  QUOTENAME(DB_NAME())+ '.' /* Current Database */
    +  QUOTENAME(SCHEMA_NAME(SCHEMA_ID))+'.'            
    +  QUOTENAME(name)  
    +  ' out D:\BCP\'  /* Path where BCP out files will be stored */
    +  REPLACE(SCHEMA_NAME(schema_id),' ','') + '_' 
    +  REPLACE(name,' ','') 
    + '.dat -T -E -SServerName\Instance -n' /* ServerName, -E will take care of Identity, -n is for Native Format */
from sys.tables
where is_ms_shipped = 0 and name <> 'sysdiagrams'                       /* sysdiagrams is classified my MS as UserTable and we dont want it */
/*and schema_name(schema_id) <> 'unwantedschema'    */                             /* Optional to exclude any schema  */
order by schema_name(schema_id)

II. Run the bat file that will generate the .dat files in the folder that you have specified.

III. Run below script on the destination server with SSMS in text mode again.

--- Execute this on the destination server.database from SSMS.

--- Make sure the change the @Destdbname and the bcp out path as per your environment.

declare @Destdbname sysname
set @Destdbname = 'destinationDB' /* Destination Database Name where you want to Bulk Insert in */
select 'BULK INSERT '
/*Remember Tables must be present on destination database */ 
+ QUOTENAME(@Destdbname) + '.' 
+ QUOTENAME(SCHEMA_NAME(SCHEMA_ID)) 
+ '.' + QUOTENAME(name) 
+ ' from ''D:\BCP\' /* Change here for bcp out path */ 
+ REPLACE(SCHEMA_NAME(schema_id), ' ', '') + '_' + REPLACE(name, ' ', '') 
+ '.dat'' with ( KEEPIDENTITY, DATAFILETYPE = ''native'', TABLOCK )' 
+ char(10) 
+ 'print ''Bulk insert for ' + REPLACE(SCHEMA_NAME(schema_id), ' ', '') + '_' + REPLACE(name, ' ', '') + ' is done... ''' 
+ char(10) + 'go'
from sys.tables
where is_ms_shipped = 0
and name <> 'sysdiagrams' /* sysdiagrams is classified my MS as UserTable and we dont want it */
--and schema_name(schema_id) <> 'unwantedschema' /* Optional to exclude any schema */
    order by schema_name(schema_id)

IV. Run the output using SSMS to insert data back in the tables.

This is very fast BCP method as it uses Native mode.

How can I avoid running ActiveRecord callbacks?

https://gist.github.com/576546

just dump this monkey-patch into config/initializers/skip_callbacks.rb

then

Project.skip_callbacks { @project.save }

or the like.

all credit to the author

How does #include <bits/stdc++.h> work in C++?

#include <bits/stdc++.h> is an implementation file for a precompiled header.

From, software engineering perspective, it is a good idea to minimize the include. If you use it actually includes a lot of files, which your program may not need, thus increase both compile-time and program size unnecessarily. [edit: as pointed out by @Swordfish in the comments that the output program size remains unaffected. But still, it's good practice to include only the libraries you actually need, unless it's some competitive competition]

But in contests, using this file is a good idea, when you want to reduce the time wasted in doing chores; especially when your rank is time-sensitive.

It works in most online judges, programming contest environments, including ACM-ICPC (Sub-Regionals, Regionals, and World Finals) and many online judges.

The disadvantages of it are that it:

  • increases the compilation time.
  • uses an internal non-standard header file of the GNU C++ library, and so will not compile in MSVC, XCode, and many other compilers

Does JavaScript have a built in stringbuilder class?

When I find myself doing a lot of string concatenation in JavaScript, I start looking for templating. Handlebars.js works quite well keeping the HTML and JavaScript more readable. http://handlebarsjs.com

What’s the difference between Response.Write() andResponse.Output.Write()?

Here Response.Write():to display only string and you can not display any other data type values like int,date,etc.Conversion(from one data type to another) is not allowed. whereas Response .Output .Write(): you can display any type of data like int, date ,string etc.,by giving index values.

Here is example:

protected void Button1_Click(object sender, EventArgs e)
    {
       Response.Write ("hi good morning!"+"is it right?");//only strings are allowed        
       Response.Write("Scott is {0} at {1:d}", "cool", DateTime.Now);//this will give error(conversion is not allowed)
       Response.Output.Write("\nhi goood morning!");//works fine
       Response.Output.Write("Jai is {0} on {1:d}", "cool", DateTime.Now);//here the current date will be converted into string and displayed
    }

NuGet Package Restore Not Working

Did you enable package restore mode in the project that has the missing packages/binaries ? There's a known issue that requires the packages to be correctly installed when enabling the restore mode :

http://nuget.codeplex.com/workitem/1879


Original link is dead; this might be a replacement: https://github.com/NuGet/Home/issues/1968

Best TCP port number range for internal applications

I can't see why you would care. Other than the "don't use ports below 1024" privilege rule, you should be able to use any port because your clients should be configurable to talk to any IP address and port!

If they're not, then they haven't been done very well. Go back and do them properly :-)

In other words, run the server at IP address X and port Y then configure clients with that information. Then, if you find you must run a different server on X that conflicts with your Y, just re-configure your server and clients to use a new port. This is true whether your clients are code, or people typing URLs into a browser.

I, like you, wouldn't try to get numbers assigned by IANA since that's supposed to be for services so common that many, many environments will use them (think SSH or FTP or TELNET).

Your network is your network and, if you want your servers on port 1234 (or even the TELNET or FTP ports for that matter), that's your business. Case in point, in our mainframe development area, port 23 is used for the 3270 terminal server which is a vastly different beast to telnet. If you want to telnet to the UNIX side of the mainframe, you use port 1023. That's sometimes annoying if you use telnet clients without specifying port 1023 since it hooks you up to a server that knows nothing of the telnet protocol - we have to break out of the telnet client and do it properly:

telnet big_honking_mainframe_box.com 1023

If you really can't make the client side configurable, pick one in the second range, like 48042, and just use it, declaring that any other software on those boxes (including any added in the future) has to keep out of your way.

How to change font size in a textbox in html

To actually do it in HTML with inline CSS (not with an external CSS style sheet)

<input type="text" style="font-size: 44pt">

A lot of people would consider putting the style right into the html like this to be poor form. However, I frequently make extreeemly simple web pages for my own use that don't even have a <html> or <body> tag, and such is appropriate there.

Pandas dataframe groupby plot

Similar to Julien's answer above, I had success with the following:

fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
    ax.plot(grp['Date'], grp['adj_close'], label=key)

ax.legend()
plt.show()

This solution might be more relevant if you want more control in matlab.

Solution inspired by: https://stackoverflow.com/a/52526454/10521959

Activity restart on rotation Android

You may use ViewModel object in your activity.

ViewModel objects are automatically retained during configuration changes so that data they hold is immediately available to the next activity or fragment instance. Read more:

https://developer.android.com/topic/libraries/architecture/viewmodel

Javascript Click on Element by Class

class of my button is "input-addon btn btn-default fileinput-exists"

below code helped me

document.querySelector('.input-addon.btn.btn-default.fileinput-exists').click();

but I want to click second button, I have two buttons in my screen so I used querySelectorAll

var elem = document.querySelectorAll('.input-addon.btn.btn-default.fileinput-exists');
                elem[1].click();

here elem[1] is the second button object that I want to click.

Detecting arrow key presses in JavaScript

Arrow Keys are triggered on keyup

$(document).on("keyup", "body", function(e) {
 if (e.keyCode == 38) {
    // up arrow
    console.log("up arrow")
  }
  if (e.keyCode == 40) {
      // down arrow
      console.log("down arrow")
  }
  if (e.keyCode == 37) {
    // left arrow
    console.log("lefy arrow")
  }
  if (e.keyCode == 39) {
    // right arrow
    console.log("right arrow")
  }
})

onkeydown allows ctrl, alt, shits

onkeyup allows tab, up arrows, down arrows, left arrows, down arrows

Location of the mongodb database on mac

If mongodb is installed via Homebrew the default location is:

/usr/local/var/mongodb

See the answer from @simonbogarde for the location of other interesting files that are different when using Homebrew.

How to transform numpy.matrix or array to scipy sparse matrix

There are several sparse matrix classes in scipy.

bsr_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrix
coo_matrix(arg1[, shape, dtype, copy]) A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Row matrix
dia_matrix(arg1[, shape, dtype, copy]) Sparse matrix with DIAgonal storage
dok_matrix(arg1[, shape, dtype, copy]) Dictionary Of Keys based sparse matrix.
lil_matrix(arg1[, shape, dtype, copy]) Row-based linked list sparse matrix

Any of them can do the conversion.

import numpy as np
from scipy import sparse
a=np.array([[1,0,1],[0,0,1]])
b=sparse.csr_matrix(a)
print(b)

(0, 0)  1
(0, 2)  1
(1, 2)  1

See http://docs.scipy.org/doc/scipy/reference/sparse.html#usage-information .

Convert Mongoose docs to json

Try this options:

  UserModel.find({}, function (err, users) {
    //i got into errors using so i changed to res.send()
    return res.send( JSON.parse(JSON.stringify(users)) );
    //Or
    //return JSON.parse(JSON.stringify(users));
  }

What does "app.run(host='0.0.0.0') " mean in Flask

To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100 in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application. If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.

Android WebView not loading an HTTPS URL

Copy and paste your code line bro , it will work trust me :) i am thinking ,you get a ssl error. If you use override onReceivedSslError method and remove super it's super method. Just write handler.proceed() ,error will solve.

    webView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {

            activity.setTitle("Loading...");
            activity.setProgress(progress * 100);

            if (progress == 100)
                activity.setTitle(getResources().getString(R.string.app_name));
        }
    });

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.d("Failure Url :" , failingUrl);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            Log.d("Ssl Error:",handler.toString() + "error:" +  error);
            handler.proceed();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.loadUrl(Constant.VIRTUALPOS_URL + "token=" + Preference.getInstance(getContext()).getToken() + "&dealer=" + Preference.getInstance(getContext()).getDealerCode());

Using async/await for multiple tasks

Parallel.ForEach requires a list of user-defined workers and a non-async Action to perform with each worker.

Task.WaitAll and Task.WhenAll require a List<Task>, which are by definition asynchronous.

I found RiaanDP's response very useful to understand the difference, but it needs a correction for Parallel.ForEach. Not enough reputation to respond to his comment, thus my own response.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncTest
{
    class Program
    {
        class Worker
        {
            public int Id;
            public int SleepTimeout;

            public void DoWork(DateTime testStart)
            {
                var workerStart = DateTime.Now;
                Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
                    Id, Thread.CurrentThread.ManagedThreadId, (workerStart - testStart).TotalSeconds.ToString("F2"));
                Thread.Sleep(SleepTimeout);
                var workerEnd = DateTime.Now;
                Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
                   Id, (workerEnd - workerStart).TotalSeconds.ToString("F2"), (workerEnd - testStart).TotalSeconds.ToString("F2"));
            }

            public async Task DoWorkAsync(DateTime testStart)
            {
                var workerStart = DateTime.Now;
                Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
                    Id, Thread.CurrentThread.ManagedThreadId, (workerStart - testStart).TotalSeconds.ToString("F2"));
                await Task.Run(() => Thread.Sleep(SleepTimeout));
                var workerEnd = DateTime.Now;
                Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
                   Id, (workerEnd - workerStart).TotalSeconds.ToString("F2"), (workerEnd - testStart).TotalSeconds.ToString("F2"));
            }
        }

        static void Main(string[] args)
        {
            var workers = new List<Worker>
            {
                new Worker { Id = 1, SleepTimeout = 1000 },
                new Worker { Id = 2, SleepTimeout = 2000 },
                new Worker { Id = 3, SleepTimeout = 3000 },
                new Worker { Id = 4, SleepTimeout = 4000 },
                new Worker { Id = 5, SleepTimeout = 5000 },
            };

            var startTime = DateTime.Now;
            Console.WriteLine("Starting test: Parallel.ForEach...");
            PerformTest_ParallelForEach(workers, startTime);
            var endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            startTime = DateTime.Now;
            Console.WriteLine("Starting test: Task.WaitAll...");
            PerformTest_TaskWaitAll(workers, startTime);
            endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            startTime = DateTime.Now;
            Console.WriteLine("Starting test: Task.WhenAll...");
            var task = PerformTest_TaskWhenAll(workers, startTime);
            task.Wait();
            endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            Console.ReadKey();
        }

        static void PerformTest_ParallelForEach(List<Worker> workers, DateTime testStart)
        {
            Parallel.ForEach(workers, worker => worker.DoWork(testStart));
        }

        static void PerformTest_TaskWaitAll(List<Worker> workers, DateTime testStart)
        {
            Task.WaitAll(workers.Select(worker => worker.DoWorkAsync(testStart)).ToArray());
        }

        static Task PerformTest_TaskWhenAll(List<Worker> workers, DateTime testStart)
        {
            return Task.WhenAll(workers.Select(worker => worker.DoWorkAsync(testStart)));
        }
    }
}

The resulting output is below. Execution times are comparable. I ran this test while my computer was doing the weekly anti virus scan. Changing the order of the tests did change the execution times on them.

Starting test: Parallel.ForEach...
Worker 1 started on thread 9, beginning 0.02 seconds after test start.
Worker 2 started on thread 10, beginning 0.02 seconds after test start.
Worker 3 started on thread 11, beginning 0.02 seconds after test start.
Worker 4 started on thread 13, beginning 0.03 seconds after test start.
Worker 5 started on thread 14, beginning 0.03 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.02 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.02 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.03 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.03 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.03 seconds after the test start.
Test finished after 5.03 seconds.

Starting test: Task.WaitAll...
Worker 1 started on thread 9, beginning 0.00 seconds after test start.
Worker 2 started on thread 9, beginning 0.00 seconds after test start.
Worker 3 started on thread 9, beginning 0.00 seconds after test start.
Worker 4 started on thread 9, beginning 0.00 seconds after test start.
Worker 5 started on thread 9, beginning 0.01 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.01 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.01 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.01 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.01 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.

Starting test: Task.WhenAll...
Worker 1 started on thread 9, beginning 0.00 seconds after test start.
Worker 2 started on thread 9, beginning 0.00 seconds after test start.
Worker 3 started on thread 9, beginning 0.00 seconds after test start.
Worker 4 started on thread 9, beginning 0.00 seconds after test start.
Worker 5 started on thread 9, beginning 0.00 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.00 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.00 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.00 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.00 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.

Xcode doesn't see my iOS device but iTunes does

After 20 minutes of debugging, I realized I had to hover over the up button () at the top of the Devices picker in the top left hand corner, to the right of the run app button

Ping all addresses in network, windows

All you are wanting to do is to see if computers are connected to the network and to gather their IP addresses. You can utilize angryIP scanner: http://angryip.org/ to see what IP addresses are in use on a particular subnet or groups of subnets.

I have found this tool very helpful when trying to see what IPs are being used that are not located inside of my DHCP.

How to put two divs on the same line with CSS in simple_form in rails?

You can't float or set the width of an inline element. Remove display: inline; from both classes and your markup should present fine.

EDIT: You can set the width, but it will cause the element to be rendered as a block.

How to change a <select> value from JavaScript

I think I know what the problem is here - if you are trying to have it select an option that doesn't exist, it won't work. You need to ADD the option first. Like so:

var option=document.createElement("option");
option.text=document.getElementById('other_referee').value
document.getElementById('referee_new').add(option,null);
document.getElementById('referee_new').value = document.getElementById('other_referee').value;

Not elegant, but you get the idea.

How to call a View Controller programmatically?

        UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone_iOS7" bundle:nil];
            AccountViewController * controller = [storyboard instantiateViewControllerWithIdentifier:@"accountView"];
            //            [self presentViewController:controller animated:YES completion:nil];

        UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        while (topRootViewController.presentedViewController)
        {
            topRootViewController = topRootViewController.presentedViewController;
        }

        [topRootViewController presentViewController:controller animated:YES completion:nil];

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

Try this one

var getValue = cmd.ExecuteScalar();    
conn.Close();
return (getValue == null) ? string.Empty : getValue.ToString();

SCCM 2012 application install "Failed" in client Software Center

I'm assuming you figured this out already but:

Technical Reference for Log Files in Configuration Manager

That's a list of client-side logs and what they do. They are located in Windows\CCM\Logs

AppEnforce.log will show you the actual command-line executed and the resulting exit code for each Deployment Type (only for the new style ConfigMgr Applications)

This is my go-to for troubleshooting apps. Haven't really found any other logs that are exceedingly useful.

HTML -- two tables side by side

Depending on your content and space, you can use floats or inline display:

<table style="display: inline-block;">

<table style="float: left;">

Check it out here: http://jsfiddle.net/SM769/

Documentation

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

In my case I had created a SB app from the SB Initializer and had included a fair number of deps in it to other things. I went in and commented out the refs to them in the build.gradle file and so was left with:

implementation 'org.springframework.boot:spring-boot-starter-hateoas'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.hsqldb:hsqldb'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'

as deps. Then my bare-bones SB app was able to build and get running successfully. As I go to try to do things that may need those commented-out libs I will add them back and see what breaks.

Onclick javascript to make browser go back to previous page?

the only one that worked for me:

function goBackAndRefresh() {
  window.history.go(-1);
  setTimeout(() => {
    location.reload();
  }, 0);
}

How do I count columns of a table

I think you want to know the total entries count in a table! For that use this code..

SELECT count( * ) as Total_Entries FROM tbl_ifo;

Can I execute a function after setState is finished updating?

setState(updater[, callback]) is an async function:

https://facebook.github.io/react/docs/react-component.html#setstate

You can execute a function after setState is finishing using the second param callback like:

this.setState({
    someState: obj
}, () => {
    this.afterSetStateFinished();
});

The same can be done with hooks in React functional component:

https://github.com/the-road-to-learn-react/use-state-with-callback#usage

Look at useStateWithCallbackLazy:

import { useStateWithCallbackLazy } from 'use-state-with-callback';

const [count, setCount] = useStateWithCallbackLazy(0);

setCount(count + 1, () => {
   afterSetCountFinished();
});

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

Good to also check the other combinators in the family and to get back to what is this specific one.

  • ul li
  • ul > li
  • ul + ul
  • ul ~ ul

Example checklist:

  • ul li - Looking inside - Selects all the li elements placed (anywhere) inside the ul; Descendant selector
  • ul > li - Looking inside - Selects only the direct li elements of ul; i.e. it will only select direct children li of ul; Child Selector or Child combinator selector
  • ul + ul - Looking outside - Selects the ul immediately following the ul; It is not looking inside, but looking outside for the immediately following element; Adjacent Sibling Selector
  • ul ~ ul - Looking outside - Selects all the ul which follows the ul doesn't matter where it is, but both ul should be having the same parent; General Sibling Selector

The one we are looking at here is General Sibling Selector

comparing elements of the same array in java

Try this or purpose will solve with lesser no of steps

for (int i = 0; i < a.length; i++) 
{
    for (int k = i+1; k < a.length; k++) 
    {
        if (a[i] != a[k]) 
         {
            System.out.println(a[i]+"not the same with"+a[k]+"\n");
        }
    }
}

How to count digits, letters, spaces for a string in Python?

sample = ("Python 3.2 is very easy") #sample string  
letters = 0  # initiating the count of letters to 0
numeric = 0  # initiating the count of numbers to 0

        for i in sample:  
            if i.isdigit():      
                numeric +=1      
            elif i.isalpha():    
                letters +=1    
            else:    
               pass  
letters  
numeric  

How to export collection to CSV in MongoDB?

@karoly-horvath has it right. Fields are required for csv.

According to this bug in the MongoDB issue tracker https://jira.mongodb.org/browse/SERVER-4224 you MUST provide the fields when exporting to a csv. The docs are not clear on it. That is the reason for the error.

Try this:

mongoexport --host localhost --db dbname --collection name --csv --out text.csv --fields firstName,middleName,lastName

UPDATE:

This commit: https://github.com/mongodb/mongo-tools/commit/586c00ef09c32c77907bd20d722049ed23065398 fixes the docs for 3.0.0-rc10 and later. It changes

Fields string `long:"fields" short:"f" description:"comma separated list of field names, e.g. -f name,age"`

to

Fields string `long:"fields" short:"f" description:"comma separated list of field names (required for exporting CSV) e.g. -f \"name,age\" "`

VERSION 3.0 AND ABOVE:

You should use --type=csv instead of --csv since it has been deprecated.

More details: https://docs.mongodb.com/manual/reference/program/mongoexport/#export-in-csv-format

Full command:

mongoexport --host localhost --db dbname --collection name --type=csv --out text.csv --fields firstName,middleName,lastName

How do I use a custom deleter with a std::unique_ptr member?

Assuming that create and destroy are free functions (which seems to be the case from the OP's code snippet) with the following signatures:

Bar* create();
void destroy(Bar*);

You can write your class Foo like this

class Foo {

    std::unique_ptr<Bar, void(*)(Bar*)> ptr_;

    // ...

public:

    Foo() : ptr_(create(), destroy) { /* ... */ }

    // ...
};

Notice that you don't need to write any lambda or custom deleter here because destroy is already a deleter.

How to put sshpass command inside a bash script?

I didn't understand how the accepted answer answers the actual question of how to run any commands on the server after sshpass is given from within the bash script file. For that reason, I'm providing an answer.


After your provided script commands, execute additional commands like below:

sshpass -p 'password' ssh user@host "ls; whois google.com;" #or whichever commands you would like to use, for multiple commands provide a semicolon ; after the command

In your script:

#! /bin/bash

sshpass -p 'password' ssh user@host "ls; whois google.com;"

How can I run NUnit tests in Visual Studio 2017?

You need to install NUnitTestAdapter. The latest version of NUnit is 3.x.y (3.6.1) and you should install NUnit3TestAdapter along with NUnit 3.x.y

To install NUnit3TestAdapter in Visual Studio 2017, follow the steps below:

  1. Right click on menu Project ? click "Manage NuGet Packages..." from the context menu
  2. Go to the Browse tab and search for NUnit
  3. Select NUnit3TestAdapter ? click Install at the right side ? click OK from the Preview pop up

Enter image description here

How to find out what the date was 5 days ago?

simple way to find the same is

$date = date("Y-m-d", strtotime('-5 days', strtotime('input_date')));

Vim and Ctags tips and tricks

One line that always goes in my .vimrc:

set tags=./tags;/

This will look in the current directory for "tags", and work up the tree towards root until one is found. IOW, you can be anywhere in your source tree instead of just the root of it.

PHP String to Float

you can follow this link to know more about How to convert a string/number into number/float/decimal in PHP. HERE IS WHAT THIS LINK SAYS...

Method 1: Using number_format() Function. The number_format() function is used to convert a string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure.

$num = "1000.314"; 

//Convert string in number using  
//number_format(), function 
echo number_format($num), "\n"; 

//Convert string in number using  
//number_format(), function 
echo number_format($num, 2); 

Method 2: Using type casting: Typecasting can directly convert a string into a float, double, or integer primitive type. This is the best way to convert a string into a number without any function.

// Number in string format 
$num = "1000.314"; 

// Type cast using int 
echo (int)$num, "\n"; 

// Type cast using float 
echo (float)$num, "\n"; 

// Type cast using double 
echo (double)$num; 

Method 3: Using intval() and floatval() Function. The intval() and floatval() functions can also be used to convert the string into its corresponding integer and float values respectively.

// Number in string format 
$num = "1000.314"; 

// intval() function to convert  
// string into integer 
echo intval($num), "\n"; 

// floatval() function to convert 
// string to float 
echo floatval($num); 

Method 4: By adding 0 or by performing mathematical operations. The string number can also be converted into an integer or float by adding 0 with the string. In PHP, performing mathematical operations, the string is converted to an integer or float implicitly.

// Number into string format 
$num = "1000.314"; 

// Performing mathematical operation  
// to implicitly type conversion 
echo $num + 0, "\n"; 

// Performing mathematical operation  
// to implicitly type conversion 
echo $num + 0.0, "\n"; 

// Performing mathematical operation  
// to implicitly type conversion 
echo $num + 0.1;

How do I get specific properties with Get-AdUser

This worked for me as well:

Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"

How do I find an array item with TypeScript? (a modern, easier way)

For some projects it's easier to set your target to es6 in your tsconfig.json.

{
  "compilerOptions": {
    "target": "es6",
    ...

Can Google Chrome open local links?

It's not really an anwser but a workaround to open a local link in chrome using python.

Copy the local link you want to run then run the code bellow (using a shortcut), it will open your link.

import win32clipboard
import os

win32clipboard.OpenClipboard()
clipboard_data= win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()

os.system("start "+clipboard_data)

How to paste into a terminal?

On windows 7:

Ctrl + Shift + Ins

works for me!

Angular routerLink does not navigate to the corresponding component

don't forget this to add this below in your template:

<router-outlet></router-outlet>

set value of input field by php variable's value

inside the Form, You can use this code. Replace your variable name (i use $variable)

<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">

How to add an event after close the modal window?

Few answers that may be useful, especially if you have dynamic content.

$('#dialogueForm').live("dialogclose", function(){
   //your code to run on dialog close
});

Or, when opening the modal, have a callback.

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

Remote JMX connection

In my testing with Tomcat and Java 8, the JVM was opening an ephemeral port in addition to the one specified for JMX. The following code fixed me up; give it a try if you are having issues where your JMX client (e.g. VisualVM is not connecting.

-Dcom.sun.management.jmxremote.port=8989
-Dcom.sun.management.jmxremote.rmi.port=8989

Also see Why Java opens 3 ports when JMX is configured?

Return positions of a regex match() in Javascript?

This member fn returns an array of 0-based positions, if any, of the input word inside the String object

String.prototype.matching_positions = function( _word, _case_sensitive, _whole_words, _multiline )
{
   /*besides '_word' param, others are flags (0|1)*/
   var _match_pattern = "g"+(_case_sensitive?"i":"")+(_multiline?"m":"") ;
   var _bound = _whole_words ? "\\b" : "" ;
   var _re = new RegExp( _bound+_word+_bound, _match_pattern );
   var _pos = [], _chunk, _index = 0 ;

   while( true )
   {
      _chunk = _re.exec( this ) ;
      if ( _chunk == null ) break ;
      _pos.push( _chunk['index'] ) ;
      _re.lastIndex = _chunk['index']+1 ;
   }

   return _pos ;
}

Now try

var _sentence = "What do doers want ? What do doers need ?" ;
var _word = "do" ;
console.log( _sentence.matching_positions( _word, 1, 0, 0 ) );
console.log( _sentence.matching_positions( _word, 1, 1, 0 ) );

You can also input regular expressions:

var _second = "z^2+2z-1" ;
console.log( _second.matching_positions( "[0-9]\z+", 0, 0, 0 ) );

Here one gets the position index of linear term.

Android Starting Service at Boot Time , How to restart service class after device Reboot?

First register a receiver in your manifest.xml file:

    <receiver android:name="com.mileagelog.service.Broadcast_PowerUp" >
        <intent-filter>
            <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
            <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
        </intent-filter>
    </receiver>

and then write a broadcast for this receiver like:

public class Broadcast_PowerUp extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
        Toast.makeText(context, "Service_PowerUp Started",
                Toast.LENGTH_LONG).show();


    } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {



        Toast.makeText(context, "Service_PowerUp Stoped", Toast.LENGTH_LONG)
        .show();
    }
  }
}

mysql: see all open connections to a given database?

SQL: show full processlist;

This is what the MySQL Workbench does.

Create dynamic URLs in Flask with url_for()

url_for in Flask is used for creating a URL to prevent the overhead of having to change URLs throughout an application (including in templates). Without url_for, if there is a change in the root URL of your app then you have to change it in every page where the link is present.

Syntax: url_for('name of the function of the route','parameters (if required)')

It can be used as:

@app.route('/index')
@app.route('/')
def index():
    return 'you are in the index page'

Now if you have a link the index page:you can use this:

<a href={{ url_for('index') }}>Index</a>

You can do a lot o stuff with it, for example:

@app.route('/questions/<int:question_id>'):    #int has been used as a filter that only integer will be passed in the url otherwise it will give a 404 error
def find_question(question_id):  
    return ('you asked for question{0}'.format(question_id))

For the above we can use:

<a href = {{ url_for('find_question' ,question_id=1) }}>Question 1</a>

Like this you can simply pass the parameters!

Get user profile picture by Id

You can use the following endpoint to get the image.jfif instead of jpg:

https://graph.facebook.com/v3.2/{user-id}/picture

Note that you won't be able to see the image, only download it.

Invoking a PHP script from a MySQL trigger

Run away from store procedures as much as possible. They are pretty hard to maintain and are VERY OLD STUFF ;)

Adding headers when using httpClient.GetAsync

You can add whatever headers you need to the HttpClient.

Here is a nice tutorial about it.

This doesn't just reference to POST-requests, you can also use it for GET-requests.

Failed Apache2 start, no error log

in the apache virtualhost you have to define the path to the error log file. when apache2 start for the first time it will create it automatically.

for example ErrorLog "/var/www/www.localhost.com/log-apache2/error.log" in the apache virtualhost..

How to set background color of view transparent in React Native

Surprisingly no one told about this, which provides some !clarity:

style={{
backgroundColor: 'white',
opacity: 0.7
}}

How do I concatenate strings?

I think that concat method and + should be mentioned here as well:

assert_eq!(
  ("My".to_owned() + " " + "string"),
  ["My", " ", "string"].concat()
);

and there is also concat! macro but only for literals:

let s = concat!("test", 10, 'b', true);
assert_eq!(s, "test10btrue");

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

RookieRick is right, using DataGridTemplateColumn instead of DataGridComboBoxColumn gives a much simpler XAML.

Moreover, putting the CompanyItem list directly accessible from the GridItem allows you to get rid of the RelativeSource.

IMHO, this give you a very clean solution.

XAML:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding GridItems}" >
    <DataGrid.Resources>
        <DataTemplate x:Key="CompanyDisplayTemplate" DataType="vm:GridItem">
            <TextBlock Text="{Binding Company}" />
        </DataTemplate>
        <DataTemplate x:Key="CompanyEditingTemplate" DataType="vm:GridItem">
            <ComboBox SelectedItem="{Binding Company}" ItemsSource="{Binding CompanyList}" />
        </DataTemplate>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}" />
        <DataGridTemplateColumn CellTemplate="{StaticResource CompanyDisplayTemplate}"
                                CellEditingTemplate="{StaticResource CompanyEditingTemplate}" />
    </DataGrid.Columns>
</DataGrid>

View model:

public class GridItem
{
    public string Name { get; set; }
    public CompanyItem Company { get; set; }
    public IEnumerable<CompanyItem> CompanyList { get; set; }
}

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

    public override string ToString() { return Name; }
}

public class ViewModel
{
    readonly ObservableCollection<CompanyItem> companies;

    public ViewModel()
    {
        companies = new ObservableCollection<CompanyItem>{
            new CompanyItem { ID = 1, Name = "Company 1" },
            new CompanyItem { ID = 2, Name = "Company 2" }
        };

        GridItems = new ObservableCollection<GridItem> {
            new GridItem { Name = "Jim", Company = companies[0], CompanyList = companies}
        };
    }

    public ObservableCollection<GridItem> GridItems { get; set; }
}

How to receive JSON as an MVC 5 action method parameter

You are sending a array of string

var usersRoles = [];
jQuery("#dualSelectRoles2 option").each(function () {
    usersRoles.push(jQuery(this).val());
});   

So change model type accordingly

 public ActionResult AddUser(List<string> model)
 {
 }

Convert Pandas Series to DateTime in a DataFrame

Some handy script:

hour = df['assess_time'].dt.hour.values[0]

Is it a good practice to use try-except-else in Python?

What is the reason for the try-except-else to exist?

A try block allows you to handle an expected error. The except block should only catch exceptions you are prepared to handle. If you handle an unexpected error, your code may do the wrong thing and hide bugs.

An else clause will execute if there were no errors, and by not executing that code in the try block, you avoid catching an unexpected error. Again, catching an unexpected error can hide bugs.

Example

For example:

try:
    try_this(whatever)
except SomeException as the_exception:
    handle(the_exception)
else:
    return something

The "try, except" suite has two optional clauses, else and finally. So it's actually try-except-else-finally.

else will evaluate only if there is no exception from the try block. It allows us to simplify the more complicated code below:

no_error = None
try:
    try_this(whatever)
    no_error = True
except SomeException as the_exception:
    handle(the_exception)
if no_error:
    return something

so if we compare an else to the alternative (which might create bugs) we see that it reduces the lines of code and we can have a more readable, maintainable, and less buggy code-base.

finally

finally will execute no matter what, even if another line is being evaluated with a return statement.

Broken down with pseudo-code

It might help to break this down, in the smallest possible form that demonstrates all features, with comments. Assume this syntactically correct (but not runnable unless the names are defined) pseudo-code is in a function.

For example:

try:
    try_this(whatever)
except SomeException as the_exception:
    handle_SomeException(the_exception)
    # Handle a instance of SomeException or a subclass of it.
except Exception as the_exception:
    generic_handle(the_exception)
    # Handle any other exception that inherits from Exception
    # - doesn't include GeneratorExit, KeyboardInterrupt, SystemExit
    # Avoid bare `except:`
else: # there was no exception whatsoever
    return something()
    # if no exception, the "something()" gets evaluated,
    # but the return will not be executed due to the return in the
    # finally block below.
finally:
    # this block will execute no matter what, even if no exception,
    # after "something" is eval'd but before that value is returned
    # but even if there is an exception.
    # a return here will hijack the return functionality. e.g.:
    return True # hijacks the return in the else clause above

It is true that we could include the code in the else block in the try block instead, where it would run if there were no exceptions, but what if that code itself raises an exception of the kind we're catching? Leaving it in the try block would hide that bug.

We want to minimize lines of code in the try block to avoid catching exceptions we did not expect, under the principle that if our code fails, we want it to fail loudly. This is a best practice.

It is my understanding that exceptions are not errors

In Python, most exceptions are errors.

We can view the exception hierarchy by using pydoc. For example, in Python 2:

$ python -m pydoc exceptions

or Python 3:

$ python -m pydoc builtins

Will give us the hierarchy. We can see that most kinds of Exception are errors, although Python uses some of them for things like ending for loops (StopIteration). This is Python 3's hierarchy:

BaseException
    Exception
        ArithmeticError
            FloatingPointError
            OverflowError
            ZeroDivisionError
        AssertionError
        AttributeError
        BufferError
        EOFError
        ImportError
            ModuleNotFoundError
        LookupError
            IndexError
            KeyError
        MemoryError
        NameError
            UnboundLocalError
        OSError
            BlockingIOError
            ChildProcessError
            ConnectionError
                BrokenPipeError
                ConnectionAbortedError
                ConnectionRefusedError
                ConnectionResetError
            FileExistsError
            FileNotFoundError
            InterruptedError
            IsADirectoryError
            NotADirectoryError
            PermissionError
            ProcessLookupError
            TimeoutError
        ReferenceError
        RuntimeError
            NotImplementedError
            RecursionError
        StopAsyncIteration
        StopIteration
        SyntaxError
            IndentationError
                TabError
        SystemError
        TypeError
        ValueError
            UnicodeError
                UnicodeDecodeError
                UnicodeEncodeError
                UnicodeTranslateError
        Warning
            BytesWarning
            DeprecationWarning
            FutureWarning
            ImportWarning
            PendingDeprecationWarning
            ResourceWarning
            RuntimeWarning
            SyntaxWarning
            UnicodeWarning
            UserWarning
    GeneratorExit
    KeyboardInterrupt
    SystemExit

A commenter asked:

Say you have a method which pings an external API and you want to handle the exception at a class outside the API wrapper, do you simply return e from the method under the except clause where e is the exception object?

No, you don't return the exception, just reraise it with a bare raise to preserve the stacktrace.

try:
    try_this(whatever)
except SomeException as the_exception:
    handle(the_exception)
    raise

Or, in Python 3, you can raise a new exception and preserve the backtrace with exception chaining:

try:
    try_this(whatever)
except SomeException as the_exception:
    handle(the_exception)
    raise DifferentException from the_exception

I elaborate in my answer here.

Write to rails console

puts or p is a good start to do that.

p "asd"       # => "asd"
puts "asd"    # => asd

here is more information about that: http://www.ruby-doc.org/core-1.9.3/ARGF.html

How can I use regex to get all the characters after a specific character, e.g. comma (",")

Short answer

Either:

  • ,[\s\S]*$ or ,.*$ to match everything after the first comma (see explanation for which one to use); or

  • [^,]*$ to match everything after the last comma (which is probably what you want).

You can use, for example, /[^,]*/.exec(s)[0] in JavaScript, where s is the original string. If you wanted to use multiline mode and find all matches that way, you could use s.match(/[^,]*/mg) to get an array (if you have more than one of your posted example lines in the variable on separate lines).

Explanation

  • [\s\S] is a character class that matches both whitespace and non-whitespace characters (i.e. all of them). This is different from . in that it matches newlines.
  • [^,] is a negated character class that matches everything except for commas.
  • * means that the previous item can repeat 0 or more times.
  • $ is the anchor that requires that the end of the match be at the end of the string (or end of line if using the /m multiline flag).

For the first match, the first regex finds the first comma , and then matches all characters afterward until the end of line [\s\S]*$, including commas.

The second regex matches as many non-comma characters as possible before the end of line. Thus, the entire match will be after the last comma.

How to get the HTML for a DOM element in javascript

var el = document.getElementById('foo');
el.parentNode.innerHTML;

How do I run a simple bit of code in a new thread?

If you are going to use the raw Thread object then you need to set IsBackground to true at a minimum and you should also set the Threading Apartment model (probably STA).

public static void DoWork()
{
    // do some work
}

public static void StartWorker()
{
    Thread worker = new Thread(DoWork);
    worker.IsBackground = true;
    worker.SetApartmentState(System.Threading.ApartmentState.STA);
    worker.Start()
}

I would recommend the BackgroundWorker class if you need UI interaction.

How do you get the contextPath from JavaScript, the right way?

Reviewer the solution by this Checking the solution of this page, make the following solution I hope it works: Example:

Javascript:

var context = window.location.pathname.substring(0, window.location.pathname.indexOf("/",2)); 
var url =window.location.protocol+"//"+ window.location.host +context+"/bla/bla";

How to include "zero" / "0" results in COUNT aggregate?

To change even less on your original query, you can turn your join into a RIGHT join

SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM appointment
RIGHT JOIN person ON person.person_id = appointment.person_id
GROUP BY person.person_id;

This just builds on the selected answer, but as the outer join is in the RIGHT direction, only one word needs to be added and less changes. - Just remember that it's there and can sometimes make queries more readable and require less rebuilding.

Test method is inconclusive: Test wasn't run. Error?

In my case my test method was private I changed it to public and it worked.

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below

git ls-files -z | xargs -0 rm
git checkout -- .

or one line

git ls-files -z | xargs -0 rm ; git checkout -- .

I use it all the time and haven't found any down sides yet!

For some further explanation, the -z appends a null character onto the end of each entry output by ls-files, and the -0 tells xargs to delimit the output it was receiving by those null characters.

Stratified Train/Test-split in scikit-learn

#train_size is 1 - tst_size - vld_size
tst_size=0.15
vld_size=0.15

X_train_test, X_valid, y_train_test, y_valid = train_test_split(df.drop(y, axis=1), df.y, test_size = vld_size, random_state=13903) 

X_train_test_V=pd.DataFrame(X_train_test)
X_valid=pd.DataFrame(X_valid)

X_train, X_test, y_train, y_test = train_test_split(X_train_test, y_train_test, test_size=tst_size, random_state=13903)

How do I name the "row names" column in r

The tibble package now has a dedicated function that converts row names to an explicit variable.

library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head

Gives:

           das_Auto  mpg cyl disp  hp drat    wt  qsec vs am gear carb
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

How can I present a file for download from an MVC controller?

Although standard action results FileContentResult or FileStreamResult may be used for downloading files, for reusability, creating a custom action result might be the best solution.

As an example let's create a custom action result for exporting data to Excel files on the fly for download.

ExcelResult class inherits abstract ActionResult class and overrides the ExecuteResult method.

We are using FastMember package for creating DataTable from IEnumerable object and ClosedXML package for creating Excel file from the DataTable.

public class ExcelResult<T> : ActionResult
{
    private DataTable dataTable;
    private string fileName;

    public ExcelResult(IEnumerable<T> data, string filename, string[] columns)
    {
        this.dataTable = new DataTable();
        using (var reader = ObjectReader.Create(data, columns))
        {
            dataTable.Load(reader);
        }
        this.fileName = filename;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context != null)
        {
            var response = context.HttpContext.Response;
            response.Clear();
            response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            response.AddHeader("content-disposition", string.Format(@"attachment;filename=""{0}""", fileName));
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dataTable, "Sheet1");
                using (MemoryStream stream = new MemoryStream())
                {
                    wb.SaveAs(stream);
                    response.BinaryWrite(stream.ToArray());
                }
            }
        }
    }
}

In the Controller use the custom ExcelResult action result as follows

[HttpGet]
public async Task<ExcelResult<MyViewModel>> ExportToExcel()
{
    var model = new Models.MyDataModel();
    var items = await model.GetItems();
    string[] columns = new string[] { "Column1", "Column2", "Column3" };
    string filename = "mydata.xlsx";
    return new ExcelResult<MyViewModel>(items, filename, columns);
}

Since we are downloading the file using HttpGet, create an empty View without model and empty layout.

Blog post about custom action result for downloading files that are created on the fly:

https://acanozturk.blogspot.com/2019/03/custom-actionresult-for-files-in-aspnet.html

How to check string length with JavaScript

 var myString = 'sample String';   var length = myString.length ;

first you need to defined a keypressed handler or some kind of a event trigger to listen , btw , getting the length is really simple like mentioned above

Testing Private method using mockito

Here is a small example how to do it with powermock

public class Hello {
    private Hello obj;
    private Integer method1(Long id) {
        return id + 10;
    }
} 

To test method1 use code:

Hello testObj = new Hello();
Integer result = Whitebox.invokeMethod(testObj, "method1", new Long(10L));

To set private object obj use this:

Hello testObj = new Hello();
Hello newObject = new Hello();
Whitebox.setInternalState(testObj, "obj", newObject);

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

How can I stop the browser back button using JavaScript?

Just set location.hash="Something". On pressing the back button, the hash will get removed from the URL, but the page won't go back.

This method is good for preventing going back accidentally, but for security purposes you should design your backend for preventing reanswering.

Export MySQL data to Excel in PHP

If you just want your query data dumped into excel I have to do this frequently and using an html table is a very simple method. I use mysqli for db queries and the following code for exports to excel:

header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=filename.xls");  
header("Pragma: no-cache"); 
header("Expires: 0");


echo '<table border="1">';
//make the column headers what you want in whatever order you want
echo '<tr><th>Field Name 1</th><th>Field Name 2</th><th>Field Name 3</th></tr>';
//loop the query data to the table in same order as the headers
while ($row = mysqli_fetch_assoc($result)){
    echo "<tr><td>".$row['field1']."</td><td>".$row['field2']."</td><td>".$row['field3']."</td></tr>";
}
echo '</table>';

Search and replace in bash using regular expressions

This example in the input hello ugly world it searches for the regex bad|ugly and replaces it with nice

#!/bin/bash

# THIS FUNCTION NEEDS THREE PARAMETERS
# arg1 = input              Example:  hello ugly world
# arg2 = search regex       Example:  bad|ugly
# arg3 = replace            Example:  nice
function regex_replace()
{
  # $1 = hello ugly world
  # $2 = bad|ugly
  # $3 = nice

  # REGEX
  re="(.*?)($2)(.*)"

  if [[ $1 =~ $re ]]; then
    # if there is a match
    
    # ${BASH_REMATCH[0]} = hello ugly world
    # ${BASH_REMATCH[1]} = hello 
    # ${BASH_REMATCH[2]} = ugly
    # ${BASH_REMATCH[3]} = world    

    # hello + nice + world
    echo ${BASH_REMATCH[1]}$3${BASH_REMATCH[3]}
  else    
    # if no match return original input  hello ugly world
    echo "$1"
  fi    
}

# prints 'hello nice world'
regex_replace 'hello ugly world' 'bad|ugly' 'nice'

# to save output to a variable
x=$(regex_replace 'hello ugly world' 'bad|ugly' 'nice')
echo "output of replacement is: $x"
exit

Get the row(s) which have the max value in groups using groupby

Realizing that "applying" "nlargest" to groupby object works just as fine:

Additional advantage - also can fetch top n values if required:

In [85]: import pandas as pd

In [86]: df = pd.DataFrame({
    ...: 'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
    ...: 'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
    ...: 'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
    ...: 'count' : [3,2,5,8,10,1,2,2,7]
    ...: })

## Apply nlargest(1) to find the max val df, and nlargest(n) gives top n values for df:
In [87]: df.groupby(["sp", "mt"]).apply(lambda x: x.nlargest(1, "count")).reset_index(drop=True)
Out[87]:
   count  mt   sp  val
0      3  S1  MM1    a
1      5  S3  MM1   cb
2      8  S3  MM2   mk
3     10  S4  MM2   bg
4      7  S2  MM4  uyi

How can I add some small utility functions to my AngularJS application?

You can also use the constant service as such. Defining the function outside of the constant call allows it to be recursive as well.

function doSomething( a, b ) {
    return a + b;
};

angular.module('moduleName',[])
    // Define
    .constant('$doSomething', doSomething)
    // Usage
    .controller( 'SomeController', function( $doSomething ) {
        $scope.added = $doSomething( 100, 200 );
    })
;

Using Jquery Ajax to retrieve data from Mysql

This answer was for @
Neha Gandhi but I modified it for  people who use pdo and mysqli sing mysql functions are not supported. Here is the new answer 

    <html>
<!--Save this as index.php-->
      <script src="//code.jquery.com/jquery-1.9.1.js"></script>
        <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
    
     <script type="text/javascript">
    
     $(document).ready(function() {
    
        $("#display").click(function() {                
    
          $.ajax({    //create an ajax request to display.php
            type: "GET",
            url: "display.php",             
            dataType: "html",   //expect html to be returned                
            success: function(response){                    
                $("#responsecontainer").html(response); 
                //alert(response);
            }
    
        });
    });
    });
    
    </script>
    
    <body>
    <h3 align="center">Manage Student Details</h3>
    <table border="1" align="center">
       <tr>
           <td> <input type="button" id="display" value="Display All Data" /> </td>
       </tr>
    </table>
    <div id="responsecontainer" align="center">
    
    </div>
    </body>
    </html>

<?php
// save this as display.php


    // show errors 
error_reporting(E_ALL);
ini_set('display_errors', 1);
    //errors ends here 
// call the page for connecting to the db
require_once('dbconnector.php');
?>
<?php
$get_member =" SELECT 
empid, lastName, firstName, email, usercode, companyid, userid, jobTitle, cell, employeetype, address ,initials   FROM employees";
$user_coder1 = $con->prepare($get_member);
$user_coder1 ->execute();

echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";

while($row =$user_coder1->fetch(PDO::FETCH_ASSOC)){
$firstName = $row['firstName'];
$empid = $row['empid'];
$lastName =    $row['lastName'];
$cell =    $row['cell'];

    echo "<tr>";
    echo "<td align=center>$firstName</td>";
    echo "<td align=center>$empid</td>";
    echo "<td align=center>$lastName </td>";
    echo "<td align=center>$cell</td>";
    echo "<td align=center>$cell</td>";
    echo "</tr>";
}
echo "</table>";
?>

<?php
// save this as dbconnector.php
function connected_Db(){

    $dsn  = 'mysql:host=localhost;dbname=mydb;charset=utf8';
    $opt  = array(
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    );
    #echo "Yes we are connected";
    return new PDO($dsn,'username','password', $opt);
    
}
$con = connected_Db();
if($con){
//echo "me  is connected ";
}
else {
//echo "Connection faid ";
exit();
}
?>

How to set child process' environment variable in Makefile

As MadScientist pointed out, you can export individual variables with:

export MY_VAR = foo  # Available for all targets

Or export variables for a specific target (target-specific variables):

my-target: export MY_VAR_1 = foo
my-target: export MY_VAR_2 = bar
my-target: export MY_VAR_3 = baz

my-target: dependency_1 dependency_2
  echo do something

You can also specify the .EXPORT_ALL_VARIABLES target to—you guessed it!—EXPORT ALL THE THINGS!!!:

.EXPORT_ALL_VARIABLES:

MY_VAR_1 = foo
MY_VAR_2 = bar
MY_VAR_3 = baz

test:
  @echo $$MY_VAR_1 $$MY_VAR_2 $$MY_VAR_3

see .EXPORT_ALL_VARIABLES

Common Header / Footer with static HTML

The only way to include another file with just static HTML is an iframe. I wouldn't consider it a very good solution for headers and footers. If your server doesn't support PHP or SSI for some bizarre reason, you could use PHP and preprocess it locally before upload. I would consider that a better solution than iframes.

How to add buttons at top of map fragment API v2 layout

Button Above The Map

If this is what you want ...simply add button inside the Fragment.

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.LocationChooser">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right|top"
        android:text="Demo Button" 
        android:padding="10dp"
        android:layout_marginTop="20dp"
        android:paddingRight="10dp"/>

</fragment>

Java regular expression OR operator

You can just use the pipe on its own:

"string1|string2"

for example:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));

Output:

blah, blah, string3

The main reason to use parentheses is to limit the scope of the alternatives:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));

has the same output. but if you just do this:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));

you get:

blah, stringblah, string3

because you've said "string1" or "2".

If you don't want to capture that part of the expression use ?::

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));

Angularjs checkbox checked by default on load and disables Select list when checked

Do it in the controller ( controller as syntax below)

controller:

vm.question= {};
vm.question.active = true;

form

<input ng-model="vm.question.active" type="checkbox" id="active" name="active">

How can I select the row with the highest ID in MySQL?

SELECT *
FROM permlog
WHERE id = ( SELECT MAX(id) FROM permlog ) ;

This would return all rows with highest id, in case id column is not constrained to be unique.

Error In PHP5 ..Unable to load dynamic library

sudo apt-get install php5-mcrypt
sudo apt-get install php5-mysql

...etc resolved it for me :)

hope it helps

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

This question wasn't asking explicitly about Docker, but I received the same error when I had a pom.xml file that was targeting 1.9...

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.9</maven.compiler.source>
  <maven.compiler.target>1.9</maven.compiler.target>
</properties>

... but then tried to run tests against a Docker container by specifying "maven" by itself.

docker run -t --rm -v m2_repository:/root/.m2/repository -v $(pwd):/work -w /work maven mvn -e test

For me, the fix was to target the exact version I needed.

docker run -t --rm -v m2_repository:/root/.m2/repository -v $(pwd):/work -w /work maven:3.5.2-jdk-9 mvn test

(You can learn more here.)

Fill background color left to right CSS

A single css code on hover can do the trick: box-shadow: inset 100px 0 0 0 #e0e0e0;

A complete demo can be found in my fiddle:

https://jsfiddle.net/shuvamallick/3o0h5oka/

How to use fetch in typescript

If you take a look at @types/node-fetch you will see the body definition

export class Body {
    bodyUsed: boolean;
    body: NodeJS.ReadableStream;
    json(): Promise<any>;
    json<T>(): Promise<T>;
    text(): Promise<string>;
    buffer(): Promise<Buffer>;
}

That means that you could use generics in order to achieve what you want. I didn't test this code, but it would looks something like this:

import { Actor } from './models/actor';

fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json<Actor>())
      .then(res => {
          let b:Actor = res;
      });

Location of Django logs and errors

Logs are set in your settings.py file. A new, default project, looks like this:

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

By default, these don't create log files. If you want those, you need to add a filename parameter to your handlers

    'applogfile': {
        'level':'DEBUG',
        'class':'logging.handlers.RotatingFileHandler',
        'filename': os.path.join(DJANGO_ROOT, 'APPNAME.log'),
        'maxBytes': 1024*1024*15, # 15MB
        'backupCount': 10,
    },

This will set up a rotating log that can get 15 MB in size and keep 10 historical versions.

In the loggers section from above, you need to add applogfile to the handlers for your application

'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'APPNAME': {
            'handlers': ['applogfile',],
            'level': 'DEBUG',
        },
    }

This example will put your logs in your Django root in a file named APPNAME.log

Get the filePath from Filename using Java

You may use:

FileSystems.getDefault().getPath(new String()).toAbsolutePath();

or

FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()

This will give you the root folder path without using the name of the file. You can then drill down to where you want to go.

Example: /src/main/java...

What is the purpose of the : (colon) GNU Bash builtin?

You could use it in conjunction with backticks (``) to execute a command without displaying its output, like this:

: `some_command`

Of course you could just do some_command > /dev/null, but the :-version is somewhat shorter.

That being said I wouldn't recommend actually doing that as it would just confuse people. It just came to mind as a possible use-case.

jQuery table sort

I came across this, and thought I'd throw in my 2 cents. Click on the column headers to sort ascending, and again to sort descending.

  • Works in Chrome, Firefox, Opera AND IE(8)
  • Only uses JQuery
  • Does alpha and numeric sorting - ascending and descending

_x000D_
_x000D_
$('th').click(function(){_x000D_
    var table = $(this).parents('table').eq(0)_x000D_
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))_x000D_
    this.asc = !this.asc_x000D_
    if (!this.asc){rows = rows.reverse()}_x000D_
    for (var i = 0; i < rows.length; i++){table.append(rows[i])}_x000D_
})_x000D_
function comparer(index) {_x000D_
    return function(a, b) {_x000D_
        var valA = getCellValue(a, index), valB = getCellValue(b, index)_x000D_
        return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)_x000D_
    }_x000D_
}_x000D_
function getCellValue(row, index){ return $(row).children('td').eq(index).text() }
_x000D_
table, th, td {_x000D_
    border: 1px solid black;_x000D_
}_x000D_
th {_x000D_
    cursor: pointer;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
    <tr><th>Country</th><th>Date</th><th>Size</th></tr>_x000D_
    <tr><td>France</td><td>2001-01-01</td><td>25</td></tr>_x000D_
    <tr><td><a href=#>spain</a></td><td>2005-05-05</td><td></td></tr>_x000D_
    <tr><td>Lebanon</td><td>2002-02-02</td><td>-17</td></tr>_x000D_
    <tr><td>Argentina</td><td>2005-04-04</td><td>100</td></tr>_x000D_
    <tr><td>USA</td><td></td><td>-6</td></tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

** Update: 2018

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

how to install python distutils

If the system Python is borked (i.e. the OS packages split distutils in a python-devel package) and you can’t ask a sysadmin to install the missing piece, then you’ll have to install your own Python. It requires some header files and a compiler toolchain. If you can’t have those, try compiling a Python on an identical computer and just copying it.

Disable browser's back button

<script>
    $(document).ready(function() {
        function disableBack() { window.history.forward() }

        window.onload = disableBack();
        window.onpageshow = function(evt) { if (evt.persisted) disableBack() }
    });
</script>

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

How do I use installed packages in PyCharm?

On Project Explorer, you can right click on the folder where the module is contained and set as 'Source'.

It will be parsed in the Index for code completion as well as other items.

How to escape regular expression special characters using javascript?

Use the \ character to escape a character that has special meaning inside a regular expression.

To automate it, you could use this:

function escapeRegExp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape

Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.

How do I convert a javascript object array to a string array of the object attribute I want?

You can do this to only monitor own properties of the object:

var arr = [];

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        arr.push(p[key]);
    }
}

How to reload a page using JavaScript

You can perform this task using window.location.reload();. As there are many ways to do this but I think it is the appropriate way to reload the same document with JavaScript. Here is the explanation

JavaScript window.location object can be used

  • to get current page address (URL)
  • to redirect the browser to another page
  • to reload the same page

window: in JavaScript represents an open window in a browser.

location: in JavaScript holds information about current URL.

The location object is like a fragment of the window object and is called up through the window.location property.

location object has three methods:

  1. assign(): used to load a new document
  2. reload(): used to reload current document
  3. replace(): used to replace current document with a new one

So here we need to use reload(), because it can help us in reloading the same document.

So use it like window.location.reload();.

Online demo on jsfiddle

To ask your browser to retrieve the page directly from the server not from the cache, you can pass a true parameter to location.reload(). This method is compatible with all major browsers, including IE, Chrome, Firefox, Safari, Opera.

Is there a W3C valid way to disable autocomplete in a HTML form?

I MADE THIS WORK IN 2020!

I basically create a css class that applies -webkit-text-security to my inputs.

Here's the link to a more recent discussion: https://stackoverflow.com/a/64471795/8754782

How to add new line into txt file

You could do it easily using

File.AppendAllText("date.txt", DateTime.Now.ToString());

If you need newline

File.AppendAllText("date.txt", 
                   DateTime.Now.ToString() + Environment.NewLine);

Anyway if you need your code do this:

TextWriter tw = new StreamWriter("date.txt", true);

with second parameter telling to append to file.
Check here StreamWriter syntax.

Counting the Number of keywords in a dictionary in python

If the question is about counting the number of keywords then would recommend something like

def countoccurrences(store, value):
    try:
        store[value] = store[value] + 1
    except KeyError as e:
        store[value] = 1
    return

in the main function have something that loops through the data and pass the values to countoccurrences function

if __name__ == "__main__":
    store = {}
    list = ('a', 'a', 'b', 'c', 'c')
    for data in list:
        countoccurrences(store, data)
    for k, v in store.iteritems():
        print "Key " + k + " has occurred "  + str(v) + " times"

The code outputs

Key a has occurred 2 times
Key c has occurred 2 times
Key b has occurred 1 times

Are there constants in JavaScript?

Okay, this is ugly, but it gives me a constant in Firefox and Chromium, an inconstant constant (WTF?) in Safari and Opera, and a variable in IE.

Of course eval() is evil, but without it, IE throws an error, preventing scripts from running.

Safari and Opera support the const keyword, but you can change the const's value.

In this example, server-side code is writing JavaScript to the page, replacing {0} with a value.

try{
    // i can haz const?
    eval("const FOO='{0}';");
    // for reals?
    var original=FOO;
    try{
        FOO='?NO!';
    }catch(err1){
        // no err from Firefox/Chrome - fails silently
        alert('err1 '+err1);
    }
    alert('const '+FOO);
    if(FOO=='?NO!'){
        // changed in Sf/Op - set back to original value
        FOO=original;
    }
}catch(err2){
    // IE fail
    alert('err2 '+err2);
    // set var (no var keyword - Chrome/Firefox complain about redefining const)
    FOO='{0}';
    alert('var '+FOO);
}
alert('FOO '+FOO);

What is this good for? Not much, since it's not cross-browser. At best, maybe a little peace of mind that at least some browsers won't let bookmarklets or third-party script modify the value.

Tested with Firefox 2, 3, 3.6, 4, Iron 8, Chrome 10, 12, Opera 11, Safari 5, IE 6, 9.

Javascript - sort array based on another array

var sortedArray = [];
for(var i=0; i < sortingArr.length; i++) {
    var found = false;
    for(var j=0; j < itemsArray.length && !found; j++) {
        if(itemsArray[j][1] == sortingArr[i]) {
            sortedArray.push(itemsArray[j]);
            itemsArray.splice(j,1);
            found = true;
        }
    }
}

http://jsfiddle.net/s7b2P/

Resulting order: Bob,Jason,Henry,Thomas,Anne,Andrew

How to get the month name in C#?

    private string MonthName(int m)
    {
        string res;
        switch (m)
        {
            case 1:
                res="Ene";
                break;
            case 2:
                res = "Feb";
                break;
            case 3:
                res = "Mar";
                break;
            case 4:
                res = "Abr";
                break;
            case 5:
                res = "May";
                break;
            case 6:
                res = "Jun";
                break;
            case 7:
                res = "Jul";
                break;
            case 8:
                res = "Ago";
                break;
            case 9:
                res = "Sep";
                break;
            case 10:
                res = "Oct";
                break;
            case 11:
                res = "Nov";
                break;
            case 12:
                res = "Dic";
                break;
            default:
                res = "Nulo";
                break;
        }
        return res;
    }

Jenkins - passing variables between jobs?

I faced the same issue when I had to pass a pom version to a downstream Rundeck job.

What I did, was using parameters injection via a properties file as such:

1) Creating properties in properties file via shell :

Build actions:

  • Execute a shell script
  • Inject environment variables

E.g : properties definition

2) Passing defined properties to the downstream job : Post Build Actions :

  • Trigger parameterized build on other project
  • Add parameters : Current build parameters
  • Add parameters : predefined parameters

E.g : properties sending

3) It was then possible to use $POM_VERSION as such in the downstream Rundeck job.

/!\ Jenkins Version : 1.636

/!\ For some reason when creating the triggered build, it was necessary to add the option 'Current build parameters' to pass the properties.

How to access parameters in a Parameterized Build?

The following snippet gives you access to all Job params

    def myparams = currentBuild.rawBuild.getAction(ParametersAction)
    for( p in myparams ) {
        pMap[p.name.toString()] = p.value.toString()
    }

Concatenate multiple node values in xpath

Try this expression...

string-join(//element3/(concat(element4/text(), '.', element5/text())), "&#10;")

How do I check form validity with angularjs?

When you put <form> tag inside you ngApp, AngularJS automatically adds form controller (actually there is a directive, called form that add nessesary behaviour). The value of the name attribute will be bound in your scope; so something like <form name="yourformname">...</form> will satisfy:

A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute.

So to check form validity, you can check value of $scope.yourformname.$valid property of scope.

More information you can get at Developer's Guide section about forms.

How to restart ADB manually from Android Studio

open command prompt -> cd to your sdk\platform-tools type below command:

adb kill-server && adb start-server

Regex replace uppercase with lowercase letters

In BBEdit works this (ex.: changing the ID values to lowercase):

Search any value: <a id="(?P<x>.*?)"></a> Replace with the same in lowercase: <a id="\L\P<x>\E"></a>

Was: <a id="VALUE"></a> Became: <a id="value"></a>

jQuery check/uncheck radio button onclick

Having tested some of the above solutions which did not work for me 100%, I decided to create my own. It creates new click listeners after a radio button is clicked:

/**
 * Radio select toggler
 * enables radio buttons to be toggled when clicked
 * Created by Michal on 09/05/2016.
 */

var radios = $('input[type=radio]');

/**
 * Adds click listeners to all checkboxes to unselect checkbox if it was checked already
 */
function updateCheckboxes() {
    radios.unbind('click');
    radios.filter(':checked').click(function () {
        $(this).prop('checked', false);
    });
    radios.click(function () {
        updateCheckboxes();
    });
}

updateCheckboxes();

How do I find the date a video (.AVI .MP4) was actually recorded?

The best way I found of getting the "dateTaken" date for either video or pictures is to use:

 Imports Microsoft.WindowsAPICodePack.Shell
 Imports Microsoft.WindowsAPICodePack.Shell.PropertySystem
 Imports System.IO
 Dim picture As ShellObject = ShellObject.FromParsingName(path)
 Dim picture As ShellObject = ShellObject.FromParsingName(path)
 Dim ItemDate=picture.Properties.System.ItemDate

The above code requires the shell api, which is internal to Microsoft, and does not depend on any other external dll.

Convert Json Array to normal Java list

We can simply convert the JSON into readable string, and split it using "split" method of String class.

String jsonAsString = yourJsonArray.toString();
//we need to remove the leading and the ending quotes and square brackets
jsonAsString = jsonAsString.substring(2, jsonAsString.length() -2);
//split wherever the String contains ","
String[] jsonAsStringArray = jsonAsString.split("\",\"");

HttpServletRequest - Get query string parameters, no form data

Java 8

return Collections.list(httpServletRequest.getParameterNames())
                  .stream()
                  .collect(Collectors.toMap(parameterName -> parameterName, httpServletRequest::getParameterValues));

Show Hide div if, if statement is true

This does not need jquery, you could set a variable inside the if and use it in html or pass it thru your template system if any

<?php
$showDivFlag=false
$query3 = mysql_query($query3);
$numrows = mysql_num_rows($query3);
if ($numrows > 0){
    $fvisit = mysql_fetch_array($result3);
    $showDivFlag=true;
 }else {

 }

?>

later in html

  <div id="results" <?php if ($showDivFlag===false){?>style="display:none"<?php } ?>>

Determine the line of code that causes a segmentation fault?

Lucas's answer about core dumps is good. In my .cshrc I have:

alias core 'ls -lt core; echo where | gdb -core=core -silent; echo "\n"'

to display the backtrace by entering 'core'. And the date stamp, to ensure I am looking at the right file :(.

Added: If there is a stack corruption bug, then the backtrace applied to the core dump is often garbage. In this case, running the program within gdb can give better results, as per the accepted answer (assuming the fault is easily reproducible). And also beware of multiple processes dumping core simultaneously; some OS's add the PID to the name of the core file.

com.jcraft.jsch.JSchException: UnknownHostKey

JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession("user", "hostname", 22); // default
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
session.setPassword("password".getBytes());
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
System.out.println("Connected");
} catch (JSchException e) {
e.printStackTrace(System.out);
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
session.disconnect();
System.out.println("Disconnected");
}
}

Can I convert a boolean to Yes/No in a ASP.NET GridView

Add a method to your page class like this:

public string YesNo(bool active) 
{
  return active ? "Yes" : "No";
}

And then in your TemplateField you Bind using this method:

<%# YesNo(Active) %>

How to terminate a window in tmux?

<Prefix> & for killing a window

<Prefix> x for killing a pane

If there is only one pane (i.e. the window is not split into multiple panes, <Prefix> x would kill the window)

As always iterated, <Prefix> is generally CTRL+b. (I think for beginner questions, we can just say CTRL+b all the time, and not talk about prefix at all, but anyway :) )

How to remove \n from a list element?

If you want to remove \n from the last element only, use this:

t[-1] = t[-1].strip()

If you want to remove \n from all the elements, use this:

t = map(lambda s: s.strip(), t)

You might also consider removing \n before splitting the line:

line = line.strip()
# split line...

Selecting Folder Destination in Java?

Oracles Java Tutorial for File Choosers: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

Note getSelectedFile() returns the selected folder, despite the name. getCurrentDirectory() returns the directory of the selected folder.

import javax.swing.*;

public class Example
{
    public static void main(String[] args)
    {
        JFileChooser f = new JFileChooser();
        f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
        f.showSaveDialog(null);

        System.out.println(f.getCurrentDirectory());
        System.out.println(f.getSelectedFile());
    }      
}

Passing an array as parameter in JavaScript

JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP is an array and contains elements with a value property.

Selecting element by data attribute with jQuery

It's sometimes desirable to filter elements based on whether they have data-items attached to them programmatically (aka not via dom-attributes):

$el.filter(function(i, x) { return $(x).data('foo-bar'); }).doSomething();

The above works but is not very readable. A better approach is to use a pseudo-selector for testing this sort of thing:

$.expr[":"].hasData = $.expr.createPseudo(function (arg) {
    return function (domEl) {
        var $el = $(domEl);
        return $el.is("[" + ((arg.startsWith("data-") ? "" : "data-") + arg) + "]") || typeof ($el.data(arg)) !== "undefined";
    };
});

Now we can refactor the original statement to something more fluent and readable:

$el.filter(":hasData('foo-bar')").doSomething();

Can you style html form buttons with css?

You might want to add:

-webkit-appearance: none; 

if you need it looking consistent on Mobile Safari...

How can I make a link from a <td> table cell

Yes, that's possible, albeit not literally the <td>, but what's in it. The simple trick is, to make sure that the content extends to the borders of the cell (it won't include the borders itself though).

As already explained, this isn't semantically correct. An a element is an inline element and should not be used as block-level element. However, here's an example (but JavaScript plus a td:hover CSS style will be much neater) that works in most browsers:

<td>
  <a href="http://example.com">
    <div style="height:100%;width:100%">
      hello world
    </div>
  </a>
</td>

PS: it's actually neater to change a in a block-level element using CSS as explained in another solution in this thread. it won't work well in IE6 though, but that's no news ;)

Alternative (non-advised) solution

If your world is only Internet Explorer (rare, nowadays), you can violate the HTML standard and write this, it will work as expected, but will be highly frowned upon and be considered ill-advised (you haven't heard this from me). Any other browser than IE will not render the link, but will show the table correctly.

<table>
    <tr>
        <a href="http://example.com"><td  width="200">hello world</td></a>
    </tr>
</table>

"Actual or formal argument lists differs in length"

Say you have defined your class like this:

    @Data
    @AllArgsConstructor(staticName = "of")
    private class Pair<P,Q> {

        public P first;
        public Q second;
    }

So when you will need to create a new instance, it will need to take the parameters and you will provide it like this as defined in the annotation.

Pair<Integer, String> pair = Pair.of(menuItemId, category);

If you define it like this, you will get the error asked for.

Pair<Integer, String> pair = new Pair(menuItemId, category);

What does the error "arguments imply differing number of rows: x, y" mean?

I had the same error message so I went googling a bit I managed to fix it with the following code.

df<-data.frame(words = unlist(words))

words is a character list.

This just in case somebody else needs the output to be a data frame.

Change link color of the current page with CSS

Best and easiest solution:

For each page you want your respective link to change color to until switched, put an internal style in EACH PAGE for the VISITED attribute and make each an individual class in order to differentiate between links so you don't apply the feature to all accidentally. We'll use white as an example:

<style type="text/css">
.link1 a:visited {color:#FFFFFF;text-decoration:none;} 
</style>

For all other attributes such as LINK, ACTIVE and HOVER, you can keep those in your style.css. You'll want to include a VISITED there as well for the color you want the link to turn back to when you click a different link.

How do I find which process is leaking memory?

I suggest the use of htop, as a better alternative to top.

How to copy a file from one directory to another using PHP?

<?php  
  
// Copy the file from /user/desktop/geek.txt  
// to user/Downloads/geeksforgeeks.txt' 
// directory 
  
// Store the path of source file 
$source = '/user/Desktop/geek.txt';  
  
// Store the path of destination file 
$destination = 'user/Downloads/geeksforgeeks.txt';  
  
// Copy the file from /user/desktop/geek.txt  
// to user/Downloads/geeksforgeeks.txt' 
// directory 
if( !copy($source, $destination) ) {  
    echo "File can't be copied! \n";  
}  
else {  
    echo "File has been copied! \n";  
}  
  
?>  

Hive Alter table change Column Name

Command works only if "use" -command has been first used to define the database where working in. Table column renaming syntax using DATABASE.TABLE throws error and does not work. Version: HIVE 0.12.

EXAMPLE:

hive> ALTER TABLE databasename.tablename CHANGE old_column_name new_column_name;

  MismatchedTokenException(49!=90)
        at org.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(BaseRecognizer.java:617)
        at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:115)
        at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatementSuffixExchangePartition(HiveParser.java:11492)
        ...

hive> use databasename;

hive> ALTER TABLE tablename CHANGE old_column_name new_column_name;

OK

How do I concatenate two strings in C?

You cannot add string literals like that in C. You have to create a buffer of size of string literal one + string literal two + a byte for null termination character and copy the corresponding literals to that buffer and also make sure that it is null terminated. Or you can use library functions like strcat.

How to interpolate variables in strings in JavaScript, without concatenation?

If you like to write CoffeeScript you could do:

hello = "foo"
my_string = "I pity the #{hello}"

CoffeeScript actually IS javascript, but with a much better syntax.

For an overview of CoffeeScript check this beginner's guide.

AWK to print field $2 first, then field $1

Use a dot or a pipe as the field separator:

awk -v FS='[.|]' '{
    printf "%s%s %s.%s\n", toupper(substr($4,1,1)), substr($4,2), $1, $2
}' << END
[email protected]|com.emailclient.account
[email protected]|com.socialsite.auth.account
END

gives:

Emailclient [email protected]
Socialsite [email protected]

How can I install a local gem?

Also, you can use gem install --local path_to_gem/filename.gem

This will skip the usual gem repository scan that happens when you leave off --local.

You can find other magic with gem install --help.

javascript onclick increment number

Yes! You can definitely use onclick or you can also use addEventListener to listen a click event. In this code sample the onclick event is in action(use).

HTML code:

<div class="container">
<p><output id="output">0</output></p>
<p><button type="button" id="btn">Increment</button></p>
</div>

Javascript code:

(function() {
 var button = document.getElementById("btn")
 var output = document.getElementById("output")
 var number
 var counter
 

 function init() {
 // Convert string to primitve number using parseInt()
  number = parseInt(output.innerText)
  
 /**
 * Start counter by adding any number to start counting.
 * In this case the output starts from 0 so to immediately
 * invoke the button to increment the counter add 1 to start 
 * counting in natural number (counting numbers).
 */  counter = number + 1
  
  function increment() {
    // Increment counter
    value = counter++
    output.innerText = value
   }
  
   // Output the increment value for every click
    button.onclick = increment
 }

 window.onload = init
})()

Demo

Getting the HTTP Referrer in ASP.NET

Request.Headers["Referer"]

Explanation

The Request.UrlReferer property will throw a System.UriFormatException if the referer HTTP header is malformed (which can happen since it is not usually under your control).

Therefore, the Request.UrlReferer property is not 100% reliable - it may contain data that cannot be parsed into a Uri class. To ensure the value is always readable, use Request.Headers["Referrer"] instead.

As for using Request.ServerVariables as others here have suggested, per MSDN:

Request.ServerVariables Collection

The ServerVariables collection retrieves the values of predetermined environment variables and request header information.

Request.Headers Property

Gets a collection of HTTP headers.

Request.Headers is a better choice than Request.ServerVariables, since Request.ServerVariables contains all of the environment variables as well as the headers, where Request.Headers is a much shorter list that only contains the headers.

So the most reliable solution is to use the Request.Headers collection to read the value directly. Do heed Microsoft's warnings about HTML encoding the value if you are going to display it on a form, though.

Using python PIL to turn a RGB image into a pure black and white image

A PIL only solution for creating a bi-level (black and white) image with a custom threshold:

from PIL import Image
img = Image.open('mB96s.png')
thresh = 200
fn = lambda x : 255 if x > thresh else 0
r = img.convert('L').point(fn, mode='1')
r.save('foo.png')

With just

r = img.convert('1')
r.save('foo.png')

you get a dithered image.

From left to right the input image, the black and white conversion result and the dithered result:

Input Image Black and White Result Dithered Result

You can click on the images to view the unscaled versions.

CSS styling in Django forms

You could use this library: https://pypi.python.org/pypi/django-widget-tweaks

It allows you to do the following:

{% load widget_tweaks %}
<!-- add 2 extra css classes to field element -->
{{ form.title|add_class:"css_class_1 css_class_2" }}

How do I measure a time interval in C?

Using the time.h library, try something like this:

long start_time, end_time, elapsed;

start_time = clock();
// Do something
end_time = clock();

elapsed = (end_time - start_time) / CLOCKS_PER_SEC * 1000;

How do I view the Explain Plan in Oracle Sql developer?

We use Oracle PL/SQL Developer(Version 12.0.7). And we use F5 button to view the explain plan.

Cannot find control with name: formControlName in angular reactive form

you're missing group nested controls with formGroupName directive

<div class="panel-body" formGroupName="address">
  <div class="form-group">
    <label for="address" class="col-sm-3 control-label">Business Address</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="street" placeholder="Business Address">
    </div>
  </div>
  <div class="form-group">
    <label for="website" class="col-sm-3 control-label">Website</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="website" placeholder="website">
    </div>
  </div>
  <div class="form-group">
    <label for="telephone" class="col-sm-3 control-label">Telephone</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="mobile" placeholder="telephone">
    </div>
  </div>
  <div class="form-group">
    <label for="email" class="col-sm-3 control-label">Email</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="email" placeholder="email">
    </div>
  </div>
  <div class="form-group">
    <label for="page id" class="col-sm-3 control-label">Facebook Page ID</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">
    </div>
  </div>
  <div class="form-group">
    <label for="about" class="col-sm-3  control-label"></label>
    <div class="col-sm-3">
      <!--span class="btn btn-success form-control" (click)="openGeneralPanel()">Back</span-->
    </div>
    <label for="about" class="col-sm-2  control-label"></label>
    <div class="col-sm-3">
      <button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>
    </div>
  </div>
</div>

What version of JBoss I am running?

Realize this is an old thread but here are a couple other ways (works with EAP 6.4):

  1. Use JBoss CLI (/opt/jboss/bin)

# jboss-cli.sh -c --controller=127.0.0.1:9999 'version' JBoss Admin Command-line Interface JBOSS_HOME: /opt/AAS/latest/jboss JBoss AS release: 7.5.14.Final-redhat-2 "Janus" JBoss AS product: EAP 6.4.14.GA

  1. Inspect the identity.conf file

# more /opt/jboss/.installation/identity.conf patches= cumulative-patch-id=jboss-eap-6.4.14.CP installed-patches=jboss-eap-6.4.1.CP,jboss-eap-6.4.2.CP,jboss-eap-6.4.3.CP,jboss-eap-6.4.4.CP,jboss-eap-6.4.5.CP,jboss-eap-6.4.6.CP,jboss-eap-6.4.7.CP,jboss-eap-6.4.8.CP,jboss-eap-6.4.9.CP, jboss-eap-6.4.10.CP,jboss-eap-6.4.11.CP,jboss-eap-6.4.12.CP,jboss-eap-6.4.13.CP,jboss-eap-6.4.14.CP

How to pass arguments to addEventListener listener function?

Sending arguments to an eventListener's callback function requires creating an isolated function and passing arguments to that isolated function.

Here's a nice little helper function you can use. Based on "hello world's" example above.)

One thing that is also needed is to maintain a reference to the function so we can remove the listener cleanly.

// Lambda closure chaos.
//
// Send an anonymous function to the listener, but execute it immediately.
// This will cause the arguments are captured, which is useful when running 
// within loops.
//
// The anonymous function returns a closure, that will be executed when 
// the event triggers. And since the arguments were captured, any vars 
// that were sent in will be unique to the function.

function addListenerWithArgs(elem, evt, func, vars){
    var f = function(ff, vv){
            return (function (){
                ff(vv);
            });
    }(func, vars);

    elem.addEventListener(evt, f);

    return f;
}

// Usage:

function doSomething(withThis){
    console.log("withThis", withThis);
}

// Capture the function so we can remove it later.
var storeFunc = addListenerWithArgs(someElem, "click", doSomething, "foo");

// To remove the listener, use the normal routine:
someElem.removeEventListener("click", storeFunc);

$lookup on ObjectId's in an array

Starting with MongoDB v3.4 (released in 2016), the $lookup aggregation pipeline stage can also work directly with an array. There is no need for $unwind any more.

This was tracked in SERVER-22881.

How can I use "." as the delimiter with String.split() in java

You might be interested in the StringTokenizer class. However, the java docs advise that you use the .split method as StringTokenizer is a legacy class.

Angularjs simple file download causes router to redirect

We also had to develop a solution which would even work with APIs requiring authentication (see this article)

Using AngularJS in a nutshell here is how we did it:

Step 1: Create a dedicated directive

// jQuery needed, uses Bootstrap classes, adjust the path of templateUrl
app.directive('pdfDownload', function() {
return {
    restrict: 'E',
    templateUrl: '/path/to/pdfDownload.tpl.html',
    scope: true,
    link: function(scope, element, attr) {
        var anchor = element.children()[0];

        // When the download starts, disable the link
        scope.$on('download-start', function() {
            $(anchor).attr('disabled', 'disabled');
        });

        // When the download finishes, attach the data to the link. Enable the link and change its appearance.
        scope.$on('downloaded', function(event, data) {
            $(anchor).attr({
                href: 'data:application/pdf;base64,' + data,
                download: attr.filename
            })
                .removeAttr('disabled')
                .text('Save')
                .removeClass('btn-primary')
                .addClass('btn-success');

            // Also overwrite the download pdf function to do nothing.
            scope.downloadPdf = function() {
            };
        });
    },
    controller: ['$scope', '$attrs', '$http', function($scope, $attrs, $http) {
        $scope.downloadPdf = function() {
            $scope.$emit('download-start');
            $http.get($attrs.url).then(function(response) {
                $scope.$emit('downloaded', response.data);
            });
        };
    }] 
});

Step 2: Create a template

<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>

Step 3: Use it

<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>

This will render a blue button. When clicked, a PDF will be downloaded (Caution: the backend has to deliver the PDF in Base64 encoding!) and put into the href. The button turns green and switches the text to Save. The user can click again and will be presented with a standard download file dialog for the file my-awesome.pdf.

Our example uses PDF files, but apparently you could provide any binary format given it's properly encoded.

How to change border color of textarea on :focus

.input:focus {
    outline: none !important;
    border:1px solid red;
    box-shadow: 0 0 10px #719ECE;
}

Count elements with jQuery

$('.class').length

This one does not work for me. I'd rather use this:

$('.class').children().length

I don't really know the reason why, but the second one works only for me. Somewhy, either size doesn't work.

convert a char* to std::string

Pass it in through the constructor:

const char* dat = "my string!";
std::string my_string( dat );

You can use the function string.c_str() to go the other way:

std::string my_string("testing!");
const char* dat = my_string.c_str();

Replace only some groups with Regex

A good idea could be to encapsulate everything inside groups, no matter if need to identify them or not. That way you can use them in your replacement string. For example:

var pattern = @"(-)(\d+)(-)";
var replaced = Regex.Replace(text, pattern, "$1AA$3"); 

or using a MatchEvaluator:

var replaced = Regex.Replace(text, pattern, m => m.Groups[1].Value + "AA" + m.Groups[3].Value);

Another way, slightly messy, could be using a lookbehind/lookahead:

(?<=-)(\d+)(?=-)

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

I think you should upgrade lastest node version

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

live output from subprocess command

If you're able to use third-party libraries, You might be able to use something like sarge (disclosure: I'm its maintainer). This library allows non-blocking access to output streams from subprocesses - it's layered over the subprocess module.

How to test code dependent on environment variables using JUnit?

You can use Powermock for mocking the call. Like:

PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getenv("MyEnvVariable")).thenReturn("DesiredValue");

You can also mock all the calls with:

PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getenv(Mockito.anyString())).thenReturn(envVariable);

How to fill the whole canvas with specific color?

If you want to do the background explicitly, you must be certain that you draw behind the current elements on the canvas.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Add behind elements.
ctx.globalCompositeOperation = 'destination-over'
// Now draw!
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);

Compare dates with javascript

The best way is,

var first = '2012-11-21';
var second = '2012-11-03';

if (new Date(first) > new Date(second) {
    .....
}

How to execute a Python script from the Django shell?

If you want to execute startup script (e.g. import some django models to work with them interactively) and remain in django shell:

PYTHONSTARTUP=my_script.py python manage.py shell

Compile to stand alone exe for C# app in Visual Studio 2010

You can use the files from debug folder,however if you look at app debug informations with some inspection software,you can clearly see "Symbols File Name" which can reveals not wanted informations in path to the original exe file.

WPF: Create a dialog / prompt

You don't need ANY of these other fancy answers. Below is a simplistic example that doesn't have all the Margin, Height, Width properties set in the XAML, but should be enough to show how to get this done at a basic level.

XAML
Build a Window page like you would normally and add your fields to it, say a Label and TextBox control inside a StackPanel:

<StackPanel Orientation="Horizontal">
    <Label Name="lblUser" Content="User Name:" />
    <TextBox Name="txtUser" />
</StackPanel>

Then create a standard Button for Submission ("OK" or "Submit") and a "Cancel" button if you like:

<StackPanel Orientation="Horizontal">
    <Button Name="btnSubmit" Click="btnSubmit_Click" Content="Submit" />
    <Button Name="btnCancel" Click="btnCancel_Click" Content="Cancel" />
</StackPanel>

Code-Behind
You'll add the Click event handler functions in the code-behind, but when you go there, first, declare a public variable where you will store your textbox value:

public static string strUserName = String.Empty;

Then, for the event handler functions (right-click the Click function on the button XAML, select "Go To Definition", it will create it for you), you need a check to see if your box is empty. You store it in your variable if it is not, and close your window:

private void btnSubmit_Click(object sender, RoutedEventArgs e)
{        
    if (!String.IsNullOrEmpty(txtUser.Text))
    {
        strUserName = txtUser.Text;
        this.Close();
    }
    else
        MessageBox.Show("Must provide a user name in the textbox.");
}

Calling It From Another Page
You're thinking, if I close my window with that this.Close() up there, my value is gone, right? NO!! I found this out from another site: http://www.dreamincode.net/forums/topic/359208-wpf-how-to-make-simple-popup-window-for-input/

They had a similar example to this (I cleaned it up a bit) of how to open your Window from another and retrieve the values:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
    {
        MyPopupWindow popup = new MyPopupWindow();  // this is the class of your other page

        //ShowDialog means you can't focus the parent window, only the popup
        popup.ShowDialog(); //execution will block here in this method until the popup closes

        string result = popup.strUserName;
        UserNameTextBlock.Text = result;  // should show what was input on the other page
    }
}

Cancel Button
You're thinking, well what about that Cancel button, though? So we just add another public variable back in our pop-up window code-behind:

public static bool cancelled = false;

And let's include our btnCancel_Click event handler, and make one change to btnSubmit_Click:

private void btnCancel_Click(object sender, RoutedEventArgs e)
{        
    cancelled = true;
    strUserName = String.Empty;
    this.Close();
}

private void btnSubmit_Click(object sender, RoutedEventArgs e)
{        
    if (!String.IsNullOrEmpty(txtUser.Text))
    {
        strUserName = txtUser.Text;
        cancelled = false;  // <-- I add this in here, just in case
        this.Close();
    }
    else
        MessageBox.Show("Must provide a user name in the textbox.");
}

And then we just read that variable in our MainWindow btnOpenPopup_Click event:

private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
{
    MyPopupWindow popup = new MyPopupWindow();  // this is the class of your other page
    //ShowDialog means you can't focus the parent window, only the popup
    popup.ShowDialog(); //execution will block here in this method until the popup closes

    // **Here we find out if we cancelled or not**
    if (popup.cancelled == true)
        return;
    else
    {
        string result = popup.strUserName;
        UserNameTextBlock.Text = result;  // should show what was input on the other page
    }
}

Long response, but I wanted to show how easy this is using public static variables. No DialogResult, no returning values, nothing. Just open the window, store your values with the button events in the pop-up window, then retrieve them afterwards in the main window function.

Searching for file in directories recursively

You will want to move the loop for the files outside of the loop for the folders. In addition you will need to pass the data structure holding the collection of files to each call of the method. That way all files go into a single list.

public static List<string> DirSearch(string sDir, List<string> files)
{
  foreach (string f in Directory.GetFiles(sDir, "*.xml"))
  {
    string extension = Path.GetExtension(f);
    if (extension != null && (extension.Equals(".xml")))
    {
      files.Add(f);
    }
  }
  foreach (string d in Directory.GetDirectories(sDir))
  {
    DirSearch(d, files);
  }
  return files;
}

Then call it like this.

List<string> files = DirSearch("c:\foo", new List<string>());

Update:

Well unbeknownst to me, until I read the other answer anyway, there is already a builtin mechanism for doing this. I will leave my answer in case you are interested in seeing how your code needs to be modified to make it work.

Decoding and verifying JWT token using System.IdentityModel.Tokens.Jwt

I am just wondering why to use some libraries for JWT token decoding and verification at all.

Encoded JWT token can be created using following pseudocode

var headers = base64URLencode(myHeaders);
var claims = base64URLencode(myClaims);
var payload = header + "." + claims;

var signature = base64URLencode(HMACSHA256(payload, secret));

var encodedJWT = payload + "." + signature;

It is very easy to do without any specific library. Using following code:

using System;
using System.Text;
using System.Security.Cryptography;

public class Program
{   
    // More info: https://stormpath.com/blog/jwt-the-right-way/
    public static void Main()
    {           
        var header = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}";
        var claims = "{\"sub\":\"1047986\",\"email\":\"[email protected]\",\"given_name\":\"John\",\"family_name\":\"Doe\",\"primarysid\":\"b521a2af99bfdc65e04010ac1d046ff5\",\"iss\":\"http://example.com\",\"aud\":\"myapp\",\"exp\":1460555281,\"nbf\":1457963281}";

        var b64header = Convert.ToBase64String(Encoding.UTF8.GetBytes(header))
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");
        var b64claims = Convert.ToBase64String(Encoding.UTF8.GetBytes(claims))
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");

        var payload = b64header + "." + b64claims;
        Console.WriteLine("JWT without sig:    " + payload);

        byte[] key = Convert.FromBase64String("mPorwQB8kMDNQeeYO35KOrMMFn6rFVmbIohBphJPnp4=");
        byte[] message = Encoding.UTF8.GetBytes(payload);

        string sig = Convert.ToBase64String(HashHMAC(key, message))
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");

        Console.WriteLine("JWT with signature: " + payload + "." + sig);        
    }

    private static byte[] HashHMAC(byte[] key, byte[] message)
    {
        var hash = new HMACSHA256(key);
        return hash.ComputeHash(message);
    }
}

The token decoding is reversed version of the code above.To verify the signature you will need to the same and compare signature part with calculated signature.

UPDATE: For those how are struggling how to do base64 urlsafe encoding/decoding please see another SO question, and also wiki and RFCs

How to import an existing directory into Eclipse?

These days, there's a better solution for importing an existing PHP project. The PDT plugin now has an option on the New PHP Project dialog just for this. So:

From File->New->PHP Project:

New PHP Project Dialog with "Create project at existing location" options badly circled

How can I delete a newline if it is the last character in a file?

Yet another perl WTDI:

perl -i -p0777we's/\n\z//' filename

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

Its given the error because of security. for this please use "https" not "http" in the website url.

For example :

   "https://code.jquery.com/ui/1.8.10/themes/smoothness/jquery-ui.css"
   "https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.min.js"

subtract two times in python

You have two datetime.time objects so for that you just create two timedelta using datetime.timedetla and then substract as you do right now using "-" operand. Following is the example way to substract two times without using datetime.

enter = datetime.time(hour=1)  # Example enter time
exit = datetime.time(hour=2)  # Example start time
enter_delta = datetime.timedelta(hours=enter.hour, minutes=enter.minute, seconds=enter.second)
exit_delta = datetime.timedelta(hours=exit.hour, minutes=exit.minute, seconds=exit.second)
difference_delta = exit_delta - enter_delta

difference_delta is your difference which you can use for your reasons.

Switch case on type c#

Yes, you can switch on the name...

switch (obj.GetType().Name)
{
    case "TextBox":...
}

CR LF notepad++ removal

The best and quick solution to the problem is first do this: View-> Show Symbol-> uncheck Show End of Line

This will solve problem for 90% of you and as in my case CR LF and its combinations still persist in the code. To fix this simply create a new tab using ctrl+n and copy whole file and paste in this new file. All CRLF gone, copy whole file again and go to original file delete whole code and paste the copied save and you rock!!!

Hope this helps.

(How) can I count the items in an enum?

I like to use enums as arguments to my functions. It's an easy means to provide a fixed list of "options". The trouble with the top voted answer here is that using that, a client can specify an "invalid option". As a spin off, I recommend doing essentially the same thing, but use a constant int outside of the enum to define the count of them.

enum foobar { foo, bar, baz, quz };
const int FOOBAR_NR_ITEMS=4;

It's not pleasant, but it's a clean solution if you don't change the enum without updating the constant.

Oracle SQL update based on subquery between two tables

There are two ways to do what you are trying

One is a Multi-column Correlated Update

UPDATE PRODUCTION a
SET (name, count) = (
  SELECT name, count
  FROM STAGING b
  WHERE a.ID = b.ID);

DEMO

You can use merge

MERGE INTO PRODUCTION a
USING ( select id, name, count 
          from STAGING ) b
ON ( a.id = b.id )
WHEN MATCHED THEN 
UPDATE SET  a.name = b.name,
            a.count = b.count

DEMO

Build tree array from flat array in javascript

This is a proposal for unordered items. This function works with a single loop and with a hash table and collects all items with their id. If a root node is found, then the object is added to the result array.

_x000D_
_x000D_
function getTree(data, root) {_x000D_
    var o = {};_x000D_
    data.forEach(function (a) {_x000D_
        if (o[a.id] && o[a.id].children) {_x000D_
            a.children = o[a.id].children;_x000D_
        }_x000D_
        o[a.id] = a;_x000D_
        o[a.parentId] = o[a.parentId] || {};_x000D_
        o[a.parentId].children = o[a.parentId].children || [];_x000D_
        o[a.parentId].children.push(a);_x000D_
    });_x000D_
    return o[root].children;_x000D_
}_x000D_
_x000D_
var data = { People: [{ id: "12", parentId: "0", text: "Man", level: "1", children: null }, { id: "6", parentId: "12", text: "Boy", level: "2", children: null }, { id: "7", parentId: "12", text: "Other", level: "2", children: null }, { id: "9", parentId: "0", text: "Woman", level: "1", children: null }, { id: "11", parentId: "9", text: "Girl", level: "2", children: null }], Animals: [{ id: "5", parentId: "0", text: "Dog", level: "1", children: null }, { id: "8", parentId: "5", text: "Puppy", level: "2", children: null }, { id: "10", parentId: "13", text: "Cat", level: "1", children: null }, { id: "14", parentId: "13", text: "Kitten", level: "2", children: null }] },_x000D_
    tree = Object.keys(data).reduce(function (r, k) {_x000D_
        r[k] = getTree(data[k], '0');_x000D_
        return r;_x000D_
    }, {});_x000D_
_x000D_
console.log(tree);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
_x000D_
_x000D_

How to create a checkbox with a clickable label?

Use this

<input type="checkbox" name="checkbox" id="checkbox_id" value="value">
<label for="checkbox_id" id="checkbox_lbl">Text</label>


$("#checkbox_lbl").click(function(){ 
    if($("#checkbox_id").is(':checked'))
        $("#checkbox_id").removAttr('checked');
    else
       $("#checkbox_id").attr('checked');
    });
});

How to write loop in a Makefile?

Maybe you can use:

xxx:
    for i in `seq 1 4`; do ./a.out $$i; done;

How do I convert a Django QuerySet into list of dicts?

You need DjangoJSONEncoder and list to make your Queryset to json, ref: Python JSON serialize a Decimal object

import json
from django.core.serializers.json import DjangoJSONEncoder


blog = Blog.objects.all().values()
json.dumps(list(blog), cls=DjangoJSONEncoder)

How to add data via $.ajax ( serialize() + extra data ) like this

What kind of data?

data: $('#myForm').serialize() + "&moredata=" + morevalue

The "data" parameter is just a URL encoded string. You can append to it however you like. See the API here.

Salt and hash a password in Python

Here's my proposition:

for i in range(len(rserver.keys())):
    salt = uuid.uuid4().hex
    print(salt)
    mdp_hash = rserver.get(rserver.keys()[i])
    rserver.set(rserver.keys()[i], hashlib.sha256(salt.encode() + mdp_hash.encode()).hexdigest() + salt)
    rsalt.set(rserver.keys()[i], salt)

display Java.util.Date in a specific format

This will help you. DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); print (df.format(new Date());

Where is the WPF Numeric UpDown control?

Let's enjoy some hacky things:
Here is a Style of Slider as a NumericUpDown, simple and easy to use, without any hidden code or third party library.

<Style TargetType="{x:Type Slider}">
    <Style.Resources>
        <Style x:Key="RepeatButtonStyle" TargetType="{x:Type RepeatButton}">
            <Setter Property="Focusable" Value="false" />
            <Setter Property="IsTabStop" Value="false" />
            <Setter Property="Padding" Value="0" />
            <Setter Property="Width" Value="20" />
        </Style>
    </Style.Resources>
    <Setter Property="Stylus.IsPressAndHoldEnabled" Value="false" />
    <Setter Property="SmallChange" Value="1" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Slider}">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <TextBox Grid.RowSpan="2"
                             Height="Auto"
                             Margin="0" Padding="0" VerticalAlignment="Stretch" VerticalContentAlignment="Center"
                             Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Value}" />
                    <RepeatButton Grid.Row="0" Grid.Column="1" Command="{x:Static Slider.IncreaseLarge}" Style="{StaticResource RepeatButtonStyle}">
                        <Path Data="M4,0 L0,4 8,4 Z" Fill="Black" />
                    </RepeatButton>
                    <RepeatButton Grid.Row="1" Grid.Column="1" Command="{x:Static Slider.DecreaseLarge}" Style="{StaticResource RepeatButtonStyle}">
                        <Path Data="M0,0 L4,4 8,0 Z" Fill="Black" />
                    </RepeatButton>
                    <Border x:Name="TrackBackground" Visibility="Collapsed">
                        <Rectangle x:Name="PART_SelectionRange" Visibility="Collapsed" />
                    </Border>
                    <Thumb x:Name="Thumb" Visibility="Collapsed" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

How to allow Cross domain request in apache2

I had a lot of trouble getting this to work. Dummy me, don't forget that old page - even for sub-requests - gets cached in your browser. Maybe obvious, but clear your browsers cache. After that, one can also use Header set Cache-Control "no-store" This was helpful to me while testing.

Send json post using php

use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.

React Hooks useState() with Object

I leave you a utility function to inmutably update objects

/**
 * Inmutable update object
 * @param  {Object} oldObject     Object to update
 * @param  {Object} updatedValues Object with new values
 * @return {Object}               New Object with updated values
 */
export const updateObject = (oldObject, updatedValues) => {
  return {
    ...oldObject,
    ...updatedValues
  };
};

So you can use it like this

const MyComponent = props => {

  const [orderForm, setOrderForm] = useState({
    specialities: {
      elementType: "select",
      elementConfig: {
        options: [],
        label: "Specialities"
      },
      touched: false
    }
  });


// I want to update the options list, to fill a select element

  // ---------- Update with fetched elements ---------- //

  const updateSpecialitiesData = data => {
    // Inmutably update elementConfig object. i.e label field is not modified
    const updatedOptions = updateObject(
      orderForm[formElementKey]["elementConfig"],
      {
        options: data
      }
    );
    // Inmutably update the relevant element.
    const updatedFormElement = updateObject(orderForm[formElementKey], {
      touched: true,
      elementConfig: updatedOptions
    });
    // Inmutably update the relevant element in the state.
    const orderFormUpdated = updateObject(orderForm, {
      [formElementKey]: updatedFormElement
    });
    setOrderForm(orderFormUpdated);
  };

  useEffect(() => {
      // some code to fetch data
      updateSpecialitiesData.current("specialities",fetchedData);
  }, [updateSpecialitiesData]);

// More component code
}

If not you have more utilities here : https://es.reactjs.org/docs/update.html

Getting the last n elements of a vector. Is there a better way than using the length() function?

How about rev(x)[1:5]?

x<-1:10
system.time(replicate(10e6,tail(x,5)))
 user  system elapsed 
 138.85    0.26  139.28 

system.time(replicate(10e6,rev(x)[1:5]))
 user  system elapsed 
 61.97    0.25   62.23

Adding input elements dynamically to form

Try this JQuery code to dynamically include form, field, and delete/remove behavior:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var max_fields = 10;_x000D_
    var wrapper = $(".container1");_x000D_
    var add_button = $(".add_form_field");_x000D_
_x000D_
    var x = 1;_x000D_
    $(add_button).click(function(e) {_x000D_
        e.preventDefault();_x000D_
        if (x < max_fields) {_x000D_
            x++;_x000D_
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
        } else {_x000D_
            alert('You Reached the limits')_x000D_
        }_x000D_
    });_x000D_
_x000D_
    $(wrapper).on("click", ".delete", function(e) {_x000D_
        e.preventDefault();_x000D_
        $(this).parent('div').remove();_x000D_
        x--;_x000D_
    })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
    <button class="add_form_field">Add New Field &nbsp; _x000D_
      <span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
    </button>_x000D_
    <div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Refer Demo Here