Programs & Examples On #Reliability

Unable to connect to any of the specified mysql hosts. C# MySQL

Try this:

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "127.0.0.1";
conn_string.Port = 3306;
conn_string.UserID = "root";
conn_string.Password = "myPassword";
conn_string.Database = "myDB";



MySqlConnection MyCon = new MySqlConnection(conn_string.ToString());

try
{
    MyCon.Open();
    MessageBox.Show("Open");
    MyCon.Close();
    MessageBox.Show("Close");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

Technically what is the main difference between Oracle JDK and OpenJDK?

OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.

OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.

OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.

So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.

I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK

Why can't I use the 'await' operator within the body of a lock statement?

Hmm, looks ugly, seems to work.

static class Async
{
    public static Task<IDisposable> Lock(object obj)
    {
        return TaskEx.Run(() =>
            {
                var resetEvent = ResetEventFor(obj);

                resetEvent.WaitOne();
                resetEvent.Reset();

                return new ExitDisposable(obj) as IDisposable;
            });
    }

    private static readonly IDictionary<object, WeakReference> ResetEventMap =
        new Dictionary<object, WeakReference>();

    private static ManualResetEvent ResetEventFor(object @lock)
    {
        if (!ResetEventMap.ContainsKey(@lock) ||
            !ResetEventMap[@lock].IsAlive)
        {
            ResetEventMap[@lock] =
                new WeakReference(new ManualResetEvent(true));
        }

        return ResetEventMap[@lock].Target as ManualResetEvent;
    }

    private static void CleanUp()
    {
        ResetEventMap.Where(kv => !kv.Value.IsAlive)
                     .ToList()
                     .ForEach(kv => ResetEventMap.Remove(kv));
    }

    private class ExitDisposable : IDisposable
    {
        private readonly object _lock;

        public ExitDisposable(object @lock)
        {
            _lock = @lock;
        }

        public void Dispose()
        {
            ResetEventFor(_lock).Set();
        }

        ~ExitDisposable()
        {
            CleanUp();
        }
    }
}

Better way of getting time in milliseconds in javascript?

As far that I know you only can get time with Date.

Date.now is the solution but is not available everywhere : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now.

var currentTime = +new Date();

This gives you the current time in milliseconds.

For your jumps. If you compute interpolations correctly according to the delta frame time and you don't have some rounding number error, I bet for the garbage collector (GC).

If there is a lot of created temporary object in your loop, garbage collection has to lock the thread to make some cleanup and memory re-organization.

With Chrome you can see how much time the GC is spending in the Timeline panel.

EDIT: Since my answer, Date.now() should be considered as the best option as it is supported everywhere and on IE >= 9.

How to programmatically clear application data

From API version 19 it is possible to call ActivityManager.clearApplicationUserData().

((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).clearApplicationUserData();

Fastest JSON reader/writer for C++

rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.

There is a performance comparison with YAJL and JsonCPP.


Update:

I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.

Clang vs GCC - which produces faster binaries?

Here are some up-to-date albeit narrow findings of mine with GCC 4.7.2 and Clang 3.2 for C++.

UPDATE: GCC 4.8.1 v clang 3.3 comparison appended below.

UPDATE: GCC 4.8.2 v clang 3.4 comparison is appended to that.

I maintain an OSS tool that is built for Linux with both GCC and Clang, and with Microsoft's compiler for Windows. The tool, coan, is a preprocessor and analyser of C/C++ source files and codelines of such: its computational profile majors on recursive-descent parsing and file-handling. The development branch (to which these results pertain) comprises at present around 11K LOC in about 90 files. It is coded, now, in C++ that is rich in polymorphism and templates and but is still mired in many patches by its not-so-distant past in hacked-together C. Move semantics are not expressly exploited. It is single-threaded. I have devoted no serious effort to optimizing it, while the "architecture" remains so largely ToDo.

I employed Clang prior to 3.2 only as an experimental compiler because, despite its superior compilation speed and diagnostics, its C++11 standard support lagged the contemporary GCC version in the respects exercised by coan. With 3.2, this gap has been closed.

My Linux test harness for current coan development processes roughly 70K sources files in a mixture of one-file parser test-cases, stress tests consuming 1000s of files and scenario tests consuming < 1K files. As well as reporting the test results, the harness accumulates and displays the totals of files consumed and the run time consumed in coan (it just passes each coan command line to the Linux time command and captures and adds up the reported numbers). The timings are flattered by the fact that any number of tests which take 0 measurable time will all add up to 0, but the contribution of such tests is negligible. The timing stats are displayed at the end of make check like this:

coan_test_timer: info: coan processed 70844 input_files.
coan_test_timer: info: run time in coan: 16.4 secs.
coan_test_timer: info: Average processing time per input file: 0.000231 secs.

I compared the test harness performance as between GCC 4.7.2 and Clang 3.2, all things being equal except the compilers. As of Clang 3.2, I no longer require any preprocessor differentiation between code tracts that GCC will compile and Clang alternatives. I built to the same C++ library (GCC's) in each case and ran all the comparisons consecutively in the same terminal session.

The default optimization level for my release build is -O2. I also successfully tested builds at -O3. I tested each configuration 3 times back-to-back and averaged the 3 outcomes, with the following results. The number in a data-cell is the average number of microseconds consumed by the coan executable to process each of the ~70K input files (read, parse and write output and diagnostics).

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.7.2 | 231 | 237 |0.97 |
----------|-----|-----|-----|
Clang-3.2 | 234 | 186 |1.25 |
----------|-----|-----|------
GCC/Clang |0.99 | 1.27|

Any particular application is very likely to have traits that play unfairly to a compiler's strengths or weaknesses. Rigorous benchmarking employs diverse applications. With that well in mind, the noteworthy features of these data are:

  1. -O3 optimization was marginally detrimental to GCC
  2. -O3 optimization was importantly beneficial to Clang
  3. At -O2 optimization, GCC was faster than Clang by just a whisker
  4. At -O3 optimization, Clang was importantly faster than GCC.

A further interesting comparison of the two compilers emerged by accident shortly after those findings. Coan liberally employs smart pointers and one such is heavily exercised in the file handling. This particular smart-pointer type had been typedef'd in prior releases for the sake of compiler-differentiation, to be an std::unique_ptr<X> if the configured compiler had sufficiently mature support for its usage as that, and otherwise an std::shared_ptr<X>. The bias to std::unique_ptr was foolish, since these pointers were in fact transferred around, but std::unique_ptr looked like the fitter option for replacing std::auto_ptr at a point when the C++11 variants were novel to me.

In the course of experimental builds to gauge Clang 3.2's continued need for this and similar differentiation, I inadvertently built std::shared_ptr<X> when I had intended to build std::unique_ptr<X>, and was surprised to observe that the resulting executable, with default -O2 optimization, was the fastest I had seen, sometimes achieving 184 msecs. per input file. With this one change to the source code, the corresponding results were these;

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.7.2 | 234 | 234 |1.00 |
----------|-----|-----|-----|
Clang-3.2 | 188 | 187 |1.00 |
----------|-----|-----|------
GCC/Clang |1.24 |1.25 |

The points of note here are:

  1. Neither compiler now benefits at all from -O3 optimization.
  2. Clang beats GCC just as importantly at each level of optimization.
  3. GCC's performance is only marginally affected by the smart-pointer type change.
  4. Clang's -O2 performance is importantly affected by the smart-pointer type change.

Before and after the smart-pointer type change, Clang is able to build a substantially faster coan executable at -O3 optimisation, and it can build an equally faster executable at -O2 and -O3 when that pointer-type is the best one - std::shared_ptr<X> - for the job.

An obvious question that I am not competent to comment upon is why Clang should be able to find a 25% -O2 speed-up in my application when a heavily used smart-pointer-type is changed from unique to shared, while GCC is indifferent to the same change. Nor do I know whether I should cheer or boo the discovery that Clang's -O2 optimization harbours such huge sensitivity to the wisdom of my smart-pointer choices.

UPDATE: GCC 4.8.1 v clang 3.3

The corresponding results now are:

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.1 | 442 | 443 |1.00 |
----------|-----|-----|-----|
Clang-3.3 | 374 | 370 |1.01 |
----------|-----|-----|------
GCC/Clang |1.18 |1.20 |

The fact that all four executables now take a much greater average time than previously to process 1 file does not reflect on the latest compilers' performance. It is due to the fact that the later development branch of the test application has taken on lot of parsing sophistication in the meantime and pays for it in speed. Only the ratios are significant.

The points of note now are not arrestingly novel:

  • GCC is indifferent to -O3 optimization
  • clang benefits very marginally from -O3 optimization
  • clang beats GCC by a similarly important margin at each level of optimization.

Comparing these results with those for GCC 4.7.2 and clang 3.2, it stands out that GCC has clawed back about a quarter of clang's lead at each optimization level. But since the test application has been heavily developed in the meantime one cannot confidently attribute this to a catch-up in GCC's code-generation. (This time, I have noted the application snapshot from which the timings were obtained and can use it again.)

UPDATE: GCC 4.8.2 v clang 3.4

I finished the update for GCC 4.8.1 v Clang 3.3 saying that I would stick to the same coan snaphot for further updates. But I decided instead to test on that snapshot (rev. 301) and on the latest development snapshot I have that passes its test suite (rev. 619). This gives the results a bit of longitude, and I had another motive:

My original posting noted that I had devoted no effort to optimizing coan for speed. This was still the case as of rev. 301. However, after I had built the timing apparatus into the coan test harness, every time I ran the test suite the performance impact of the latest changes stared me in the face. I saw that it was often surprisingly big and that the trend was more steeply negative than I felt to be merited by gains in functionality.

By rev. 308 the average processing time per input file in the test suite had well more than doubled since the first posting here. At that point I made a U-turn on my 10 year policy of not bothering about performance. In the intensive spate of revisions up to 619 performance was always a consideration and a large number of them went purely to rewriting key load-bearers on fundamentally faster lines (though without using any non-standard compiler features to do so). It would be interesting to see each compiler's reaction to this U-turn,

Here is the now familiar timings matrix for the latest two compilers' builds of rev.301:

coan - rev.301 results

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.2 | 428 | 428 |1.00 |
----------|-----|-----|-----|
Clang-3.4 | 390 | 365 |1.07 |
----------|-----|-----|------
GCC/Clang | 1.1 | 1.17|

The story here is only marginally changed from GCC-4.8.1 and Clang-3.3. GCC's showing is a trifle better. Clang's is a trifle worse. Noise could well account for this. Clang still comes out ahead by -O2 and -O3 margins that wouldn't matter in most applications but would matter to quite a few.

And here is the matrix for rev. 619.

coan - rev.619 results

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.2 | 210 | 208 |1.01 |
----------|-----|-----|-----|
Clang-3.4 | 252 | 250 |1.01 |
----------|-----|-----|------
GCC/Clang |0.83 | 0.83|

Taking the 301 and the 619 figures side by side, several points speak out.

  • I was aiming to write faster code, and both compilers emphatically vindicate my efforts. But:

  • GCC repays those efforts far more generously than Clang. At -O2 optimization Clang's 619 build is 46% faster than its 301 build: at -O3 Clang's improvement is 31%. Good, but at each optimization level GCC's 619 build is more than twice as fast as its 301.

  • GCC more than reverses Clang's former superiority. And at each optimization level GCC now beats Clang by 17%.

  • Clang's ability in the 301 build to get more leverage than GCC from -O3 optimization is gone in the 619 build. Neither compiler gains meaningfully from -O3.

I was sufficiently surprised by this reversal of fortunes that I suspected I might have accidentally made a sluggish build of clang 3.4 itself (since I built it from source). So I re-ran the 619 test with my distro's stock Clang 3.3. The results were practically the same as for 3.4.

So as regards reaction to the U-turn: On the numbers here, Clang has done much better than GCC at at wringing speed out of my C++ code when I was giving it no help. When I put my mind to helping, GCC did a much better job than Clang.

I don't elevate that observation into a principle, but I take the lesson that "Which compiler produces the better binaries?" is a question that, even if you specify the test suite to which the answer shall be relative, still is not a clear-cut matter of just timing the binaries.

Is your better binary the fastest binary, or is it the one that best compensates for cheaply crafted code? Or best compensates for expensively crafted code that prioritizes maintainability and reuse over speed? It depends on the nature and relative weights of your motives for producing the binary, and of the constraints under which you do so.

And in any case, if you deeply care about building "the best" binaries then you had better keep checking how successive iterations of compilers deliver on your idea of "the best" over successive iterations of your code.

Disabling browser print options (headers, footers, margins) from page?

I solved my problem using some css into the web page.

<style media="print">
   @page {
      size: auto;
      margin: 0;
  }
</style>

Comparing HTTP and FTP for transferring files

I just benchmarked a file transfer over both FTP and HTTP :

  • over two very good server connections
  • using the same 1GB .zip file
  • under the same network conditions (tested one after the other)

The result:

  • using FTP: 6 minutes
  • using HTTP: 4 minutes
  • using a concurrent http downloader software (fdm): 1 minute

So, basically under a "real life" situation:

1) HTTP is faster than FTP when downloading one big file.

2) HTTP can use parallel chunk download which makes it 6x times faster than FTP depending on the network conditions.

How do I programmatically determine operating system in Java?

Oct. 2008:

I would recommend to cache it in a static variable:

public static final class OsUtils
{
   private static String OS = null;
   public static String getOsName()
   {
      if(OS == null) { OS = System.getProperty("os.name"); }
      return OS;
   }
   public static boolean isWindows()
   {
      return getOsName().startsWith("Windows");
   }

   public static boolean isUnix() // and so on
}

That way, every time you ask for the Os, you do not fetch the property more than once in the lifetime of your application.


February 2016: 7+ years later:

There is a bug with Windows 10 (which did not exist at the time of the original answer).
See "Java's “os.name” for Windows 10?"

Determining Referer in PHP

The REFERER is sent by the client's browser as part of the HTTP protocol, and is therefore unreliable indeed. It might not be there, it might be forged, you just can't trust it if it's for security reasons.

If you want to verify if a request is coming from your site, well you can't, but you can verify the user has been to your site and/or is authenticated. Cookies are sent in AJAX requests so you can rely on that.

How to get Android GPS location

Excerpt:-

try 
        {
          cnt++;scnt++;now=System.currentTimeMillis();r=rand.nextInt(6);r++;
            loc=lm.getLastKnownLocation(best);
            if(loc!=null){lat=loc.getLatitude();lng=loc.getLongitude();}

            Thread.sleep(100);
            handler.sendMessage(handler.obtainMessage());
         } 
        catch (InterruptedException e) 
        {
            Toast.makeText(this, "Error="+e.toString(), Toast.LENGTH_LONG).show();
        }

As you can see above, a thread is running alongside main thread of user-interface activity which continuously displays GPS lat,long alongwith current time and a random dice throw.

IF you are curious then just check the full code: GPS Location with a randomized dice throw & current time in separate thread

How can I return pivot table output in MySQL?

Correct answer is:

select table_record_id,
group_concat(if(value_name='note', value_text, NULL)) as note
,group_concat(if(value_name='hire_date', value_text, NULL)) as hire_date
,group_concat(if(value_name='termination_date', value_text, NULL)) as termination_date
,group_concat(if(value_name='department', value_text, NULL)) as department
,group_concat(if(value_name='reporting_to', value_text, NULL)) as reporting_to
,group_concat(if(value_name='shift_start_time', value_text, NULL)) as shift_start_time
,group_concat(if(value_name='shift_end_time', value_text, NULL)) as shift_end_time
from other_value
where table_name = 'employee'
and is_active = 'y'
and is_deleted = 'n'
GROUP BY table_record_id

Retrofit and GET using parameters

I also wanted to clarify that if you have complex url parameters to build, you will need to build them manually. ie if your query is example.com/?latlng=-37,147, instead of providing the lat and lng values individually, you will need to build the latlng string externally, then provide it as a parameter, ie:

public interface LocationService {    
    @GET("/example/")
    void getLocation(@Query(value="latlng", encoded=true) String latlng);
}

Note the encoded=true is necessary, otherwise retrofit will encode the comma in the string parameter. Usage:

String latlng = location.getLatitude() + "," + location.getLongitude();
service.getLocation(latlng);

"This SqlTransaction has completed; it is no longer usable."... configuration error?

In my case , I've some codes which needs to execute after committing the transaction at the same try catch block.One of the code threw an error then try block handed over the error to it's catch block which contains the transaction rollback. It will show the similar error. For example look at the code structure below :

SqlTransaction trans = null;

try{
 trans = Con.BeginTransaction();
// your codes

  trans.Commit();
//your codes having errors

}
catch(Exception ex)
{
     trans.Rollback(); //transaction roll back
    // error message
}

finally
{ 
    // connection close
}

Hope it will someone :)

Trim a string based on the string length

// this is how you shorten the length of the string with .. // add following method to your class

private String abbreviate(String s){
  if(s.length() <= 10) return s;
  return s.substring(0, 8) + ".." ;
}

Get battery level and state in Android

try this function no need permisson or any reciver

void getBattery_percentage()
{
      IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
      Intent batteryStatus = getApplicationContext().registerReceiver(null, ifilter);
      int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
      int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
      float batteryPct = level / (float)scale;
      float p = batteryPct * 100;

      Log.d("Battery percentage",String.valueOf(Math.round(p)));
  }

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

Both Activity and View have method dispatchTouchEvent() and onTouchEvent.The ViewGroup have this methods too, but have another method called onInterceptTouchEvent. The return type of those methods are boolean, you can control the dispatch route through the return value.

The event dispatch in Android starts from Activity->ViewGroup->View.

How to achieve pagination/table layout with Angular.js?

The best simple plug and play solution for pagination.

https://ciphertrick.com/2015/06/01/search-sort-and-pagination-ngrepeat-angularjs/#comment-1002

you would jus need to replace ng-repeat with custom directive.

<tr dir-paginate="user in userList|filter:search |itemsPerPage:7">
<td>{{user.name}}</td></tr>

Within the page u just need to add

<div align="center">
       <dir-pagination-controls
            max-size="100"
            direction-links="true"
            boundary-links="true" >
       </dir-pagination-controls>
</div>

In your index.html load

<script src="./js/dirPagination.js"></script>

In your module just add dependencies

angular.module('userApp',['angularUtils.directives.dirPagination']);

and thats all needed for pagination.

Might be helpful for someone.

How to add more than one machine to the trusted hosts list using winrm

The suggested answer by Loïc MICHEL blindly writes a new value to the TrustedHosts entry.
I believe, a better way would be to first query TrustedHosts.
As Jeffery Hicks posted in 2010, first query the TrustedHosts entry:

PS C:\> $current=(get-item WSMan:\localhost\Client\TrustedHosts).value
PS C:\> $current+=",testdsk23,alpha123"
PS C:\> set-item WSMan:\localhost\Client\TrustedHosts –value $current

Use string value from a cell to access worksheet of same name

You can use the formula INDIRECT().

This basically takes a string and treats it as a reference. In your case, you would use:

=INDIRECT("'"&A5&"'!G7")

The double quotes are to show that what's inside are strings, and only A5 here is a reference.

What is the difference between "expose" and "publish" in Docker?

You expose ports using the EXPOSE keyword in the Dockerfile or the --expose flag to docker run. Exposing ports is a way of documenting which ports are used, but does not actually map or open any ports. Exposing ports is optional.

Source: github commit

Combine or merge JSON on node.js without jQuery

A better approach from the correct solution here in order to not alter target:

function extend(){
  let sources = [].slice.call(arguments, 0), result = {};
  sources.forEach(function (source) {
    for (let prop in source) {
      result[prop] = source[prop];
    }
  });
  return result;
}

HTML not loading CSS file

_x000D_
_x000D_
<link href="style.css" rel="stylesheet" type="text/css"/>
_x000D_
_x000D_
_x000D_

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

check for jar(mysql-connector-java-bin) in your classpath download from here

Possible heap pollution via varargs parameter

The reason is because varargs give the option of being called with a non-parametrized object array. So if your type was List < A > ... , it can also be called with List[] non-varargs type.

Here is an example:

public static void testCode(){
    List[] b = new List[1];
    test(b);
}

@SafeVarargs
public static void test(List<A>... a){
}

As you can see List[] b can contain any type of consumer, and yet this code compiles. If you use varargs, then you are fine, but if you use the method definition after type-erasure - void test(List[]) - then the compiler will not check the template parameter types. @SafeVarargs will suppress this warning.

Calling class staticmethod within the class body?

This is the way I prefer:

class Klass(object):

    @staticmethod
    def stat_func():
        return 42

    _ANS = stat_func.__func__()

    def method(self):
        return self.__class__.stat_func() + self.__class__._ANS

I prefer this solution to Klass.stat_func, because of the DRY principle. Reminds me of the reason why there is a new super() in Python 3 :)

But I agree with the others, usually the best choice is to define a module level function.

For instance with @staticmethod function, the recursion might not look very good (You would need to break DRY principle by calling Klass.stat_func inside Klass.stat_func). That's because you don't have reference to self inside static method. With module level function, everything will look OK.

How to get MAC address of client using PHP?

echo GetMAC();

function GetMAC(){
    ob_start();
    system('getmac');
    $Content = ob_get_contents();
    ob_clean();
    return substr($Content, strpos($Content,'\\')-20, 17);
}

Above will basically execute the getmac program and parse its console-output, resulting to MAC-address of the server (and/or where ever PHP is installed and running on).

Is it possible to clone html element objects in JavaScript / JQuery?

It's actually very easy in jQuery:

$("#ddl_1").clone().attr("id",newId).appendTo("body");

Change .appendTo() of course...

Javascript code for showing yesterday's date and todays date

Yesterday's date is simply today's date less one, so:

var d = new Date();
d.setDate(d.getDate() - 1);

If today is 1 April, then it is set to 0 April which is converted to 31 March.

Since you also wanted to do some other stuff, here are some functions to do it:

// Check if d is a valid date
// Must be format year-month name-date
// e.g. 2011-MAR-12 or 2011-March-6
// Capitalisation is not important
function validDate(d) {
  var bits = d.split('-');
  var t = stringToDate(d);
  return t.getFullYear() == bits[0] && 
         t.getDate() == bits[2];
}

// Convert string in format above to a date object
function stringToDate(s) {
  var bits = s.split('-');
  var monthNum = monthNameToNumber(bits[1]);
  return new Date(bits[0], monthNum, bits[2]);
}

// Convert month names like mar or march to 
// number, capitalisation not important
// Month number is calendar month - 1.
var monthNameToNumber = (function() {
  var monthNames = (
     'jan feb mar apr may jun jul aug sep oct nov dec ' +
     'january february march april may june july august ' +
     'september october november december'
     ).split(' ');

  return function(month) {
    var i = monthNames.length;
    month = month.toLowerCase(); 

    while (i--) {
      if (monthNames[i] == month) {
        return i % 12;
      }
    }
  }
}());

// Given a date in above format, return
// previous day as a date object
function getYesterday(d) {
  d = stringToDate(d);
  d.setDate(d.getDate() - 1)
  return d;
}

// Given a date object, format
// per format above
var formatDate = (function() {
  var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
  function addZ(n) {
    return n<10? '0'+n : ''+n;
  }
  return function(d) {
    return d.getFullYear() + '-' + 
           months[d.getMonth()] + '-' + 
           addZ(d.getDate());
  }
}());

function doStuff(d) {

  // Is it format year-month-date?
  if (!validDate(d)) {
    alert(d + ' is not a valid date');
    return;
  } else {
    alert(d + ' is a valid date');
  }
  alert(
    'Date in was: ' + d +
    '\nDay before: ' + formatDate(getYesterday(d))
  );
}


doStuff('2011-feb-08');
// Shows 2011-feb-08 is a valid date
//       Date in was: 2011-feb-08
//       Day before: 2011-feb-07

How can I insert new line/carriage returns into an element.textContent?

You could use regular expressions to replace the '\n' or '\n\r' characters with '<br />'.

you have this:

var h1 = document.createElement("h1");

h1.textContent = "This is a very long string and I would like to insert a carriage return HERE...
moreover, I would like to insert another carriage return HERE... 
so this text will display in a new line";

you can replace your characters like this:

h1.innerHTML = h1.innerHTML.replace(/\n\r?/g, '<br />');

check the javascript reference for the String and Regex objects:

http://www.w3schools.com/jsref/jsref_replace.asp

http://www.w3schools.com/jsref/jsref_obj_regexp.asp

MongoDB Aggregation: How to get total records count?

This could be work for multiple match conditions

            const query = [
                {
                    $facet: {
                    cancelled: [
                        { $match: { orderStatus: 'Cancelled' } },
                        { $count: 'cancelled' }
                    ],
                    pending: [
                        { $match: { orderStatus: 'Pending' } },
                        { $count: 'pending' }
                    ],
                    total: [
                        { $match: { isActive: true } },
                        { $count: 'total' }
                    ]
                    }
                },
                {
                    $project: {
                    cancelled: { $arrayElemAt: ['$cancelled.cancelled', 0] },
                    pending: { $arrayElemAt: ['$pending.pending', 0] },
                    total: { $arrayElemAt: ['$total.total', 0] }
                    }
                }
                ]
                Order.aggregate(query, (error, findRes) => {})

Best way to "push" into C# array

As per comment "That is not pushing to an array. It is merely assigning to it"

If you looking for the best practice to assign value to array then its only way that you can assign value.

Array[index]= value;

there is only way to assign value when you do not want to use List.

How to automatically insert a blank row after a group of data

This does exactly what you are asking, checks the rows, and inserts a blank empty row at each change in column A:

sub AddBlankRows()
'
dim iRow as integer, iCol as integer
dim oRng as range

set oRng=range("a1")

irow=oRng.row
icol=oRng.column

do 
'
if cells(irow+1, iCol)<>cells(irow,iCol) then
    cells(irow+1,iCol).entirerow.insert shift:=xldown
    irow=irow+2
else
    irow=irow+1
end if
'
loop while not cells (irow,iCol).text=""
'
end sub

I hope that gets you started, let us know!

Philip

How do I see all foreign keys to a table or column?

Constraints in SQL are the rules defined for the data in a table. Constraints also limit the types of data that go into the table. If new data does not abide by these rules the action is aborted.

select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'FOREIGN KEY';

You can view all constraints by using select * from information_schema.table_constraints;

(This will produce a lot of table data).

You can also use this for MySQL:

show create table tableName;

Rename computer and join to domain in one step with PowerShell

Also add local account + rename computer at prompt + join to domain at promt

#Set A local admin account
$computername = $env:computername   # place computername here for remote access
$username = 'localadmin'
$password = 'P@ssw0rd1'
$desc = 'Local admin account'
$computer = [ADSI]"WinNT://$computername,computer"
$user = $computer.Create("user", $username)
$user.SetPassword($password)
$user.Setinfo()
$user.description = $desc
$user.setinfo()
$user.UserFlags = 65536
$user.SetInfo()
$group = [ADSI]("WinNT://$computername/administrators,group")
$group.add("WinNT://$username,user")

# Set computer name 
$computerName = Get-WmiObject Win32_ComputerSystem 
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null 
$name = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Desired Computer Name ")
$computername.rename("$name")

#Now Join to Domain
Add-Computer -DomainName [domainname] -Credential [user\domain]  -Verbose
Restart-Computer

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

If you are using the new Navigation Component, is simple as

findNavController().popBackStack()

It will do all the FragmentTransaction in behind for you.

Java : Accessing a class within a package, which is the better way?

As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang package is automatically imported, as is everything in the current package.

The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.

By the way, if you are using lots of static methods (from Math, for example), you could also write

import static java.lang.Math.*;

and then use

sqrt(x)

directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player);     // I get the error here.

void showInventory(player& obj) {   // By Johnny :D

this means that player is an datatype and showInventory expect an referance to an variable of type player.

so the correct code will be

  void showInventory(player& obj) {   // By Johnny :D
    for(int i = 0; i < 20; i++) {
        std::cout << "\nINVENTORY:\n" + obj.getItem(i);
        i++;
        std::cout << "\t\t\t" + obj.getItem(i) + "\n";
        i++;
    }
    }

players myPlayers[10];

    std::string toDo() //BY KEATON
    {
    std::string commands[5] =   // This is the valid list of commands.
        {"help", "inv"};

    std::string ans;
    std::cout << "\nWhat do you wish to do?\n>> ";
    std::cin >> ans;

    if(ans == commands[0]) {
        helpMenu();
        return NULL;
    }
    else if(ans == commands[1]) {
        showInventory(myPlayers[0]);     // or any other index,also is not necessary to have an array
        return NULL;
    }

}

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

I got the same error when upgraded angular from 6 to 8.

Simple update angular cli to latest version & node version to 10+.

1) Visit this link to get the latest node version. Angular 8 requires 10+.
2) Execute npm i @angular/cli@latest to update cli.


This is what I have currently

enter image description here

Change div width live with jQuery

You can use, which will be triggered when the window resizes.

$( window ).bind("resize", function(){
    // Change the width of the div
    $("#yourdiv").width( 600 );
});

If you want a DIV width as percentage of the screen, just use CSS width : 80%;.

How can I exclude a directory from Visual Studio Code "Explore" tab?

In newer versions of VS Code, you navigate to settings (Ctrl+,), and make sure to select Workspace Settings at the top right.

enter image description here

Then add a files.exclude option to specify patterns to exclude.

You can also add search.exclude if you only want to exclude a file from search results, and not from the folder explorer.

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

Try

(n+10).toString(36)

_x000D_
_x000D_
chr = n=>(n+10).toString(36);_x000D_
_x000D_
for(i=0; i<26; i++) console.log(`${i} => ${ chr(i) }`);
_x000D_
_x000D_
_x000D_

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Another way of doing this is using nested IF statements. Suppose you have companies table and you want to count number of records in it. A sample query would be something like this

SELECT IF(
      count(*) > 15,
      'good',
      IF(
          count(*) > 10,
          'average',
          'poor'
        ) 
      ) as data_count 
      FROM companies

Here second IF condition works when the first IF condition fails. So Sample Syntax of the IF statement would be IF ( CONDITION, THEN, ELSE). Hope it helps someone.

Python: Best way to add to sys.path relative to the current running script

I use:

from site import addsitedir

Then, can use any relative directory ! addsitedir('..\lib') ; the two dots implies move (up) one directory first.

Remember that it all depends on what your current working directory your starting from. If C:\Joe\Jen\Becky, then addsitedir('..\lib') imports to your path C:\Joe\Jen\lib

C:\
  |__Joe
      |_ Jen
      |     |_ Becky
      |_ lib

Access images inside public folder in laravel

I have created an Asset helper of my own.

First I defined the asset types and path in app/config/assets.php:

return array(

    /*
    |--------------------------------------------------------------------------
    | Assets paths
    |--------------------------------------------------------------------------
    |
    | Location of all application assets, relative to the public folder,
    | may be used together with absolute paths or with URLs.
    |
    */

    'images' => '/storage/images',
    'css' => '/assets/css',
    'img' => '/assets/img',
    'js' => '/assets/js'
);

Then the actual Asset class:

class Asset
{
    private static function getUrl($type, $file)
    {
        return URL::to(Config::get('assets.' . $type) . '/' . $file);
    }

    public static function css($file)
    {
        return self::getUrl('css', $file);
    }

    public static function img($file)
    {
        return self::getUrl('img', $file);
    }

    public static function js($file)
    {
        return self::getUrl('js', $file);
    }

}

So in my view I can do this to show an image:

{{ HTML::image(Asset::img('logo.png'), "My logo")) }}

Or like this to implement a Java script:

{{ HTML::script(Asset::js('my_script.js')) }}

Python 2.6: Class inside a Class?

class Second:
    def __init__(self, data):
        self.data = data

class First:
    def SecondClass(self, data):
        return Second(data)

FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data

java.time.format.DateTimeParseException: Text could not be parsed at index 21

Your original problem was wrong pattern symbol "h" which stands for the clock hour (range 1-12). In this case, the am-pm-information is missing. Better, use the pattern symbol "H" instead (hour of day in range 0-23). So the pattern should rather have been like:

uuuu-MM-dd'T'HH:mm:ss.SSSX (best pattern also suitable for strict mode)

Environment variable to control java.io.tmpdir?

According to the java.io.File Java Docs

The default temporary-file directory is specified by the system property java.io.tmpdir. On UNIX systems the default value of this property is typically "/tmp" or "/var/tmp"; on Microsoft Windows systems it is typically "c:\temp". A different value may be given to this system property when the Java virtual machine is invoked, but programmatic changes to this property are not guaranteed to have any effect upon the the temporary directory used by this method.

To specify the java.io.tmpdir System property, you can invoke the JVM as follows:

java -Djava.io.tmpdir=/path/to/tmpdir

By default this value should come from the TMP environment variable on Windows systems

How can I reload .emacs after changing it?

Although M-x eval-buffer will work you may run into problems with toggles and other similar things. A better approach might be to "mark" or highlight whats new in your .emacs (or even scratch buffer if your just messing around) and then M-x eval-region. Hope this helps.

How do I exclude all instances of a transitive dependency when using Gradle?

Ah, the following works and does what I want:

configurations {
  runtime.exclude group: "org.slf4j", module: "slf4j-log4j12"
}

It seems that an Exclude Rule only has two attributes - group and module. However, the above syntax doesn't prevent you from specifying any arbitrary property as a predicate. When trying to exclude from an individual dependency you cannot specify arbitrary properties. For example, this fails:

dependencies {
  compile ('org.springframework.data:spring-data-hadoop-core:2.0.0.M4-hadoop22') {
    exclude group: "org.slf4j", name: "slf4j-log4j12"
  }
}

with

No such property: name for class: org.gradle.api.internal.artifacts.DefaultExcludeRule

So even though you can specify a dependency with a group: and name: you can't specify an exclusion with a name:!?!

Perhaps a separate question, but what exactly is a module then? I can understand the Maven notion of groupId:artifactId:version, which I understand translates to group:name:version in Gradle. But then, how do I know what module (in gradle-speak) a particular Maven artifact belongs to?

What value could I insert into a bit type column?

Generally speaking, for boolean or bit data types, you would use 0 or 1 like so:

UPDATE tbl SET bitCol = 1 WHERE bitCol = 0

See also:

Convert date to another timezone in JavaScript

Time Zone Offset for your current timezone

date +%s -d '1 Jan 1970'

For my GMT+10 timezone (Australia) it returned -36000

Update TextView Every Second

It's a very old question and I'm sure there are a lot of resources out there. But it's never too much to spread the word to be at the safe side. Currently, if someone else ever want to achieve what the OP asked, you can use: android.widget.TextClock.

TextClock documentation here.

Here's what I've used:

<android.widget.TextClock
    android:id="@+id/digitalClock"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:timeZone="GMT+0000" <!--Greenwich -->
    android:format24Hour="dd MMM yyyy   k:mm:ss"
    android:format12Hour="@null"
    android:textStyle="bold"
    android:layout_alignParentEnd="true" />

How do I view / replay a chrome network debugger har file saved with content?

The Most Reliable way to replay har file is using a free tool like Fiddler, the tool is always free and can be downloaded quickly. The sites for the opening har file are all buggy and cannot open large files. Fiddler is available for all platforms.

https://www.telerik.com/download/fiddler

Go to File Menu -> Import Sessions...

Open Fiddler

Select the "HTTPArchive" Option

Select the Http Archieve option

Browse to your HAR file

enter image description here

The HAR file will open and replay on the fiddler window.

Integrate ZXing in Android Studio

buttion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new com.google.zxing.integration.android.IntentIntegrator(Fragment.this).initiateScan();
            }
        });

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() == null) {
                Log.d("MainActivity", "Cancelled scan");
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            } else {
                Log.d("MainActivity", "Scanned");
                Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
            }
        } else {
            // This is important, otherwise the result will not be passed to the fragment
            super.onActivityResult(requestCode, resultCode, data);
        }
    }



dependencies {
    compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
    compile 'com.google.zxing:core:3.2.1'
    compile 'com.android.support:appcompat-v7:23.1.0'
}

How to secure MongoDB with username and password

User creation with password for a specific database to secure database access :

use dbName

db.createUser(
   {
     user: "dbUser",
     pwd: "dbPassword",
     roles: [ "readWrite", "dbAdmin" ]
   }
)

Python - Create list with numbers between 2 values?

Every answer above assumes range is of positive numbers only. Here is the solution to return list of consecutive numbers where arguments can be any (positive or negative), with the possibility to set optional step value (default = 1).

def any_number_range(a,b,s=1):
""" Generate consecutive values list between two numbers with optional step (default=1)."""
if (a == b):
    return a
else:
    mx = max(a,b)
    mn = min(a,b)
    result = []
    # inclusive upper limit. If not needed, delete '+1' in the line below
    while(mn < mx + 1):
        # if step is positive we go from min to max
        if s > 0:
            result.append(mn)
            mn += s
        # if step is negative we go from max to min
        if s < 0:
            result.append(mx)
            mx += s
    return result

For instance, standard command list(range(1,-3)) returns empty list [], while this function will return [-3,-2,-1,0,1]

Updated: now step may be negative. Thanks @Michael for his comment.

Easiest way to convert a List to a Set in Java

With Java 10, you could now use Set#copyOf to easily convert a List<E> to an unmodifiable Set<E>:

Example:

var set = Set.copyOf(list);

Keep in mind that this is an unordered operation, and null elements are not permitted, as it will throw a NullPointerException.

If you wish for it to be modifiable, then simply pass it into the constructor a Set implementation.

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

To answer your question, yes it does: your synchronized method cannot be executed by more than one thread at a time.

Class Diagrams in VS 2017

I am using VS 2017 Enterprise, you can find an option to install the class diagram extension using he Quick Launch in VS.

PHP check if url parameter exists

Use isset()

$matchFound = (isset($_GET["id"]) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';

EDIT: This is added for the completeness sake. $_GET in php is a reserved variable that is an associative array. Hence, you could also make use of 'array_key_exists(mixed $key, array $array)'. It will return a boolean that the key is found or not. So, the following also will be okay.

$matchFound = (array_key_exists("id", $_GET)) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

If you really want to type ToString inside your query, you could write an expression tree visitor that rewrites the call to ToString with a call to the appropriate StringConvert function:

using System.Linq;
using System.Data.Entity.SqlServer;
using System.Linq.Expressions;
using static System.Linq.Expressions.Expression;
using System;

namespace ToStringRewriting {
    class ToStringRewriter : ExpressionVisitor {
        static MethodInfo stringConvertMethodInfo = typeof(SqlFunctions).GetMethods()
                 .Single(x => x.Name == "StringConvert" && x.GetParameters()[0].ParameterType == typeof(decimal?));

        protected override Expression VisitMethodCall(MethodCallExpression node) {
            var method = node.Method;
            if (method.Name=="ToString") {
                if (node.Object.GetType() == typeof(string)) { return node.Object; }
                node = Call(stringConvertMethodInfo, Convert(node.Object, typeof(decimal?));
            }
            return base.VisitMethodCall(node);
        }
    }
    class Person {
        string Name { get; set; }
        long SocialSecurityNumber { get; set; }
    }
    class Program {
        void Main() {
            Expression<Func<Person, Boolean>> expr = x => x.ToString().Length > 1;
            var rewriter = new ToStringRewriter();
            var finalExpression = rewriter.Visit(expr);
            var dcx = new MyDataContext();
            var query = dcx.Persons.Where(finalExpression);

        }
    }
}

How to remove new line characters from a string?

If speed and low memory usage are important, do something like this:

var sb = new StringBuilder(s.Length);

foreach (char i in s)
    if (i != '\n' && i != '\r' && i != '\t')
        sb.Append(i);

s = sb.ToString();

Extract a subset of a dataframe based on a condition involving a field

Here are the two main approaches. I prefer this one for its readability:

bar <- subset(foo, location == "there")

Note that you can string together many conditionals with & and | to create complex subsets.

The second is the indexing approach. You can index rows in R with either numeric, or boolean slices. foo$location == "there" returns a vector of T and F values that is the same length as the rows of foo. You can do this to return only rows where the condition returns true.

foo[foo$location == "there", ]

Disable scrolling in all mobile devices

use this in style

body
{
overflow:hidden;
width:100%;
}

Use this in head tag

<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />

How do operator.itemgetter() and sort() work?

Answer for Python beginners

In simpler words:

  1. The key= parameter of sort requires a key function (to be applied to be objects to be sorted) rather than a single key value and
  2. that is just what operator.itemgetter(1) will give you: A function that grabs the first item from a list-like object.

(More precisely those are callables, not functions, but that is a difference that can often be ignored.)

Checking session if empty or not

You need to check that Session["emp_num"] is not null before trying to convert it to a string otherwise you will get a null reference exception.

I'd go with your first example - but you could make it slightly more "elegant".

There are a couple of ways, but the ones that springs to mind are:

if (Session["emp_num"] is string)
{
}

or

if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
}

This will return null if the variable doesn't exist or isn't a string.

In Oracle, is it possible to INSERT or UPDATE a record through a view?

YES, you can Update and Insert into view and that edit will be reflected on the original table....
BUT
1-the view should have all the NOT NULL values on the table
2-the update should have the same rules as table... "updating primary key related to other foreign key.. etc"...

Is there a method to generate a UUID with go language

From Russ Cox's post:

There's no official library. Ignoring error checking, this seems like it would work fine:

f, _ := os.Open("/dev/urandom")
b := make([]byte, 16)
f.Read(b)
f.Close()
uuid := fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])

Note: In the original, pre Go 1 version the first line was:

f, _ := os.Open("/dev/urandom", os.O_RDONLY, 0)

Here it compiles and executes, only /dev/urandom returns all zeros in the playground. Should work fine locally.

In the same thread there are some other methods/references/packages found.

How can I get a first element from a sorted list?

Matthew's answer is correct:

list.get(0);

To do what you tried:

list[0];

you'll have to wait until Java 7 is released:

devoxx conference http://img718.imageshack.us/img718/11/capturadepantalla201003cg.png

Here's an interesting presentation by Mark Reinhold about Java 7

It looks like parleys site is currently down, try later :(

How do I strip all spaces out of a string in PHP?

str_replace will do the trick thusly

$new_str = str_replace(' ', '', $old_str);

How to compile .c file with OpenSSL includes?

You need to include the library path (-L/usr/local/lib/)

gcc -o Opentest Opentest.c -L/usr/local/lib/ -lssl -lcrypto

It works for me.

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

I think it is the version error.

try installing this in following order:

  1. sudo apt-get install python3-mysqldb

  2. pip3 install mysqlclient

  3. python3 manage.py makemigrations

  4. python3 manage.py migrate

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

How to set default vim colorscheme

Ubuntu 17.10 default doesn't have the ~/.vimrc file, we need create it and put the setting colorscheme color_scheme_name in it.

By the way, colorscheme desert is good scheme to choose.

What is the best way to remove a table row with jQuery?

$('#myTable tr').click(function(){
    $(this).remove();
    return false;
});

Even a better one

$("#MyTable").on("click", "#DeleteButton", function() {
   $(this).closest("tr").remove();
});

How to Get True Size of MySQL Database?

If you want to find the size of all MySQL databases, us this command, it will show their respective sizes in megabytes;

SELECT table_schema "database", sum(data_length + index_length)/1024/1024 "size in MB" FROM information_schema.TABLES GROUP BY table_schema;

If you have large databases, you can use the following command to show the result in gigabytes;

SELECT table_schema "database", sum(data_length + index_length)/1024/1024/1024 "size in GB" FROM information_schema.TABLES GROUP BY table_schema;

If you want to show the size of only a specific database, for example YOUR_DATABASE_NAME, you could use the following query;

SELECT table_schema "database", sum(data_length + index_length)/1024/1024/1024 "size in GB" FROM information_schema.TABLES WHERE table_schema='YOUR_DATABASE_NAME' GROUP BY table_schema;

Maximum filename length in NTFS (Windows XP and Windows Vista)?

According to MSDN, it's 260 characters. It includes "<NUL>" -the invisible terminating null character, so the actual length is 259.

But read the article, it's a bit more complicated.

I get exception when using Thread.sleep(x) or wait()

You have a lot of reading ahead of you. From compiler errors through exception handling, threading and thread interruptions. But this will do what you want:

try {
    Thread.sleep(1000);                 //1000 milliseconds is one second.
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}

Difference between xcopy and robocopy

Its painful to hear people are still suffering at the hands of *{COPY} whatever the version. I am a seasoned batch and Bash script writer and I recommend rsync , you can run this within cygwin (cygwin.org) or you can locate some binaries floating around . and you can redirect output to 2>&1 to some log file like out.log for later analysing. Good luck people its time to love life again . =M. Kaan=

Keras input explanation: input_shape, units, batch_size, dim, etc

Input Dimension Clarified:

Not a direct answer, but I just realized the word Input Dimension could be confusing enough, so be wary:

It (the word dimension alone) can refer to:

a) The dimension of Input Data (or stream) such as # N of sensor axes to beam the time series signal, or RGB color channel (3): suggested word=> "InputStream Dimension"

b) The total number /length of Input Features (or Input layer) (28 x 28 = 784 for the MINST color image) or 3000 in the FFT transformed Spectrum Values, or

"Input Layer / Input Feature Dimension"

c) The dimensionality (# of dimension) of the input (typically 3D as expected in Keras LSTM) or (#RowofSamples, #of Senors, #of Values..) 3 is the answer.

"N Dimensionality of Input"

d) The SPECIFIC Input Shape (eg. (30,50,50,3) in this unwrapped input image data, or (30, 250, 3) if unwrapped Keras:

Keras has its input_dim refers to the Dimension of Input Layer / Number of Input Feature

model = Sequential()
model.add(Dense(32, input_dim=784))  #or 3 in the current posted example above
model.add(Activation('relu'))

In Keras LSTM, it refers to the total Time Steps

The term has been very confusing, is correct and we live in a very confusing world!!

I find one of the challenge in Machine Learning is to deal with different languages or dialects and terminologies (like if you have 5-8 highly different versions of English, then you need to very high proficiency to converse with different speakers). Probably this is the same in programming languages too.

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

Possible to make labels appear when hovering over a point in matplotlib?

mplcursors worked for me. mplcursors provides clickable annotation for matplotlib. It is heavily inspired from mpldatacursor (https://github.com/joferkington/mpldatacursor), with a much simplified API

import matplotlib.pyplot as plt
import numpy as np
import mplcursors

data = np.outer(range(10), range(1, 5))

fig, ax = plt.subplots()
lines = ax.plot(data)
ax.set_title("Click somewhere on a line.\nRight-click to deselect.\n"
             "Annotations can be dragged.")

mplcursors.cursor(lines) # or just mplcursors.cursor()

plt.show()

Convert Select Columns in Pandas Dataframe to Numpy Array

Please use the Pandas to_numpy() method. Below is an example--

>>> import pandas as pd
>>> df = pd.DataFrame({"A":[1, 2], "B":[3, 4], "C":[5, 6]})
>>> df 
    A  B  C
 0  1  3  5
 1  2  4  6
>>> s_array = df[["A", "B", "C"]].to_numpy()
>>> s_array

array([[1, 3, 5],
   [2, 4, 6]]) 

>>> t_array = df[["B", "C"]].to_numpy() 
>>> print (t_array)

[[3 5]
 [4 6]]

Hope this helps. You can select any number of columns using

columns = ['col1', 'col2', 'col3']
df1 = df[columns]

Then apply to_numpy() method.

DynamoDB vs MongoDB NoSQL

Bear in mind, I've only experimented with MongoDB...

From what I've read, DynamoDB has come a long way in terms of features. It used to be a super-basic key-value store with extremely limited storage and querying capabilities. It has since grown, now supporting bigger document sizes + JSON support and global secondary indices. The gap between what DynamoDB and MongoDB offers in terms of features grows smaller with every month. The new features of DynamoDB are expanded on here.

Much of the MongoDB vs. DynamoDB comparisons are out of date due to the recent addition of DynamoDB features. However, this post offers some other convincing points to choose DynamoDB, namely that it's simple, low maintenance, and often low cost. Another discussion here of database choices was interesting to read, though slightly old.

My takeaway: if you're doing serious database queries or working in languages not supported by DynamoDB, use MongoDB. Otherwise, stick with DynamoDB.

Is there a way to create key-value pairs in Bash script?

In bash, we use

declare -A name_of_dictonary_variable

so that Bash understands it is a dictionary.

For e.g. you want to create sounds dictionary then,

declare -A sounds

sounds[dog]="Bark"

sounds[wolf]="Howl"

where dog and wolf are "keys", and Bark and Howl are "values".

You can access all values using : echo ${sounds[@]} OR echo ${sounds[*]}

You can access all keys only using: echo ${!sounds[@]}

And if you want any value for a particular key, you can use:

${sounds[dog]}

this will give you value (Bark) for key (Dog).

Detect when an image fails to load in Javascript

This:

<img onerror="this.src='/images/image.png'" src="...">

malloc for struct and pointer in C

You could actually do this in a single malloc by allocating for the Vector and the array at the same time. Eg:

struct Vector y = (struct Vector*)malloc(sizeof(struct Vector) + 10*sizeof(double));
y->x = (double*)((char*)y + sizeof(struct Vector));
y->n = 10;

This allocates Vector 'y', then makes y->x point to the extra allocated data immediate after the Vector struct (but in the same memory block).

If resizing the vector is required, you should do it with the two allocations as recommended. The internal y->x array would then be able to be resized while keeping the vector struct 'y' intact.

how to write javascript code inside php

Just echo the javascript out inside the if function

 <form name="testForm" id="testForm"  method="POST"  >
     <input type="submit" name="btn" value="submit" autofocus  onclick="return true;"/>
 </form>
 <?php
    if(isset($_POST['btn'])){
        echo "
            <script type=\"text/javascript\">
            var e = document.getElementById('testForm'); e.action='test.php'; e.submit();
            </script>
        ";
     }
  ?>

What does git rev-parse do?

git rev-parse Also works for getting the current branch name using the --abbrev-ref flag like:

git rev-parse --abbrev-ref HEAD

Converting Decimal to Binary Java

A rather simple than efficient program, yet it does the job.

        Scanner sc = new Scanner(System.in);
        System.out.println("Give me my binaries");
        int str = sc.nextInt(2);
        System.out.println(str);

Linq to SQL .Sum() without group ... into

Try this:

var itemsInCart = from o in db.OrderLineItems
                  where o.OrderId == currentOrder.OrderId
                  select o.WishListItem.Price;

return Convert.ToDecimal(itemsInCart.Sum());

I think it's more simple!

Iterate through dictionary values?

Depending on your version:

Python 2.x:

for key, val in PIX0.iteritems():
    NUM = input("Which standard has a resolution of {!r}?".format(val))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))

Python 3.x:

for key, val in PIX0.items():
    NUM = input("Which standard has a resolution of {!r}?".format(val))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))

You should also get in the habit of using the new string formatting syntax ({} instead of % operator) from PEP 3101:

https://www.python.org/dev/peps/pep-3101/

Eclipse java debugging: source not found

In my case, even after Editing source lookup and Adding project, it didn't worked. I configured the Build path of the project.

enter image description here

After that, I selected JRE System Library and it worked.

enter image description here

HTML Mobile -forcing the soft keyboard to hide

example how i made it , After i fill a Maximum length it will blur from my Field (and the Keyboard will disappear ) , if you have more than one field , you can just add the line that i add '//'

var MaxLength = 8;
    $(document).ready(function () {
        $('#MyTB').keyup(function () {
            if ($(this).val().length >= MaxLength) {
               $('#MyTB').blur();
             //  $('#MyTB2').focus();
         }
          }); });

What is the best way to conditionally apply attributes in AngularJS?

I am using the following to conditionally set the class attr when ng-class can't be used (for example when styling SVG):

ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"

The same approach should work for other attribute types.

(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)

Can't find the 'libpq-fe.h header when trying to install pg gem

Step 1) Make sure postgress is installed in your system ( If it's already installed and you can run postgress server on your machine move to step (2)

apt-get install postgresql postgresql-contrib (sol - fatal error: libpq-fe.h: No such file or directory)
sudo apt-get install ruby-dev (required to install postgress below)
sudo gem install pg
sudo service postgresql restart

Step 2) Some of the c++ files are trying to access libpq-fe.h directly and cant find. So we need to manually search every such file and replace libpq-fe.h with postgresql/libpq-fe.h

Command for searching all occurrences of libpq-fe.h in all dir and subdir is grep -rnw ./ -e 'libpq-fe.h'

3) Go to All the file listed by command run in step 2 and manually change libpq-fe.h with postgresql/libpq-fe.h.

Writing numerical values on the plot with Matplotlib

Use pyplot.text() (import matplotlib.pyplot as plt)

import matplotlib.pyplot as plt

x=[1,2,3]
y=[9,8,7]

plt.plot(x,y)
for a,b in zip(x, y): 
    plt.text(a, b, str(b))
plt.show()

Create SQLite database in android

Better example is here

 try {
   myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);

   /* Create a Table in the Database. */
   myDB.execSQL("CREATE TABLE IF NOT EXISTS "
     + TableName
     + " (Field1 VARCHAR, Field2 INT(3));");

   /* Insert data to a Table*/
   myDB.execSQL("INSERT INTO "
     + TableName
     + " (Field1, Field2)"
     + " VALUES ('Saranga', 22);");

   /*retrieve data from database */
   Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);

   int Column1 = c.getColumnIndex("Field1");
   int Column2 = c.getColumnIndex("Field2");

   // Check if our result was valid.
   c.moveToFirst();
   if (c != null) {
    // Loop through all Results
    do {
     String Name = c.getString(Column1);
     int Age = c.getInt(Column2);
     Data =Data +Name+"/"+Age+"\n";
    }while(c.moveToNext());
   }

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

sudo apt-get install putty

This will automatically install the puttygen tool.

Now to convert the PPK file to be used with SSH command execute the following in terminal

puttygen mykey.ppk -O private-openssh -o my-openssh-key

Then, you can connect via SSH with:

ssh -v [email protected] -i my-openssh-key

http://www.graphicmist.in/use-your-putty-ppk-file-to-ssh-remote-server-in-ubuntu/#comment-28603

Alternative to header("Content-type: text/xml");

No. You can't send headers after they were sent. Try to use hooks in wordpress

Upload files with FTP using PowerShell

I am not sure you can 100% bullet proof the script from not hanging or crashing, as there are things outside your control (what if the server loses power mid-upload?) - but this should provide a solid foundation for getting you started:

# create the FtpWebRequest and configure it
$ftp = [System.Net.FtpWebRequest]::Create("ftp://localhost/me.png")
$ftp = [System.Net.FtpWebRequest]$ftp
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential("anonymous","anonymous@localhost")
$ftp.UseBinary = $true
$ftp.UsePassive = $true
# read in the file to upload as a byte array
$content = [System.IO.File]::ReadAllBytes("C:\me.png")
$ftp.ContentLength = $content.Length
# get the request stream, and write the bytes into it
$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)
# be sure to clean up after ourselves
$rs.Close()
$rs.Dispose()

Heatmap in matplotlib with pcolor?

The python seaborn module is based on matplotlib, and produces a very nice heatmap.

Below is an implementation with seaborn, designed for the ipython/jupyter notebook.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# import the data directly into a pandas dataframe
nba = pd.read_csv("http://datasets.flowingdata.com/ppg2008.csv", index_col='Name  ')
# remove index title
nba.index.name = ""
# normalize data columns
nba_norm = (nba - nba.mean()) / (nba.max() - nba.min())
# relabel columns
labels = ['Games', 'Minutes', 'Points', 'Field goals made', 'Field goal attempts', 'Field goal percentage', 'Free throws made', 
          'Free throws attempts', 'Free throws percentage','Three-pointers made', 'Three-point attempt', 'Three-point percentage', 
          'Offensive rebounds', 'Defensive rebounds', 'Total rebounds', 'Assists', 'Steals', 'Blocks', 'Turnover', 'Personal foul']
nba_norm.columns = labels
# set appropriate font and dpi
sns.set(font_scale=1.2)
sns.set_style({"savefig.dpi": 100})
# plot it out
ax = sns.heatmap(nba_norm, cmap=plt.cm.Blues, linewidths=.1)
# set the x-axis labels on the top
ax.xaxis.tick_top()
# rotate the x-axis labels
plt.xticks(rotation=90)
# get figure (usually obtained via "fig,ax=plt.subplots()" with matplotlib)
fig = ax.get_figure()
# specify dimensions and save
fig.set_size_inches(15, 20)
fig.savefig("nba.png")

The output looks like this: seaborn nba heatmap I used the matplotlib Blues color map, but personally find the default colors quite beautiful. I used matplotlib to rotate the x-axis labels, as I couldn't find the seaborn syntax. As noted by grexor, it was necessary to specify the dimensions (fig.set_size_inches) by trial and error, which I found a bit frustrating.

As noted by Paul H, you can easily add the values to heat maps (annot=True), but in this case I didn't think it improved the figure. Several code snippets were taken from the excellent answer by joelotz.

Pass variables by reference in JavaScript

Simple Object

_x000D_
_x000D_
function foo(x) {
  // Function with other context
  // Modify `x` property, increasing the value
  x.value++;
}

// Initialize `ref` as object
var ref = {
  // The `value` is inside `ref` variable object
  // The initial value is `1`
  value: 1
};

// Call function with object value
foo(ref);
// Call function with object value again
foo(ref);

console.log(ref.value); // Prints "3"
_x000D_
_x000D_
_x000D_


Custom Object

Object rvar

_x000D_
_x000D_
/**
 * Aux function to create by-references variables
 */
function rvar(name, value, context) {
  // If `this` is a `rvar` instance
  if (this instanceof rvar) {
    // Inside `rvar` context...
    
    // Internal object value
    this.value = value;
    
    // Object `name` property
    Object.defineProperty(this, 'name', { value: name });
    
    // Object `hasValue` property
    Object.defineProperty(this, 'hasValue', {
      get: function () {
        // If the internal object value is not `undefined`
        return this.value !== undefined;
      }
    });
    
    // Copy value constructor for type-check
    if ((value !== undefined) && (value !== null)) {
      this.constructor = value.constructor;
    }
    
    // To String method
    this.toString = function () {
      // Convert the internal value to string
      return this.value + '';
    };
  } else {
    // Outside `rvar` context...
    
    // Initialice `rvar` object
    if (!rvar.refs) {
      rvar.refs = {};
    }
    
    // Initialize context if it is not defined
    if (!context) {
      context = window;
    }
    
    // Store variable
    rvar.refs[name] = new rvar(name, value, context);
    
    // Define variable at context
    Object.defineProperty(context, name, {
      // Getter
      get: function () { return rvar.refs[name]; },
      // Setter
      set: function (v) { rvar.refs[name].value = v; },
      // Can be overrided?
      configurable: true
    });

    // Return object reference
    return context[name];
  }
}

// Variable Declaration

  // Declare `test_ref` variable
  rvar('test_ref_1');

  // Assign value `5`
  test_ref_1 = 5;
  // Or
  test_ref_1.value = 5;

  // Or declare and initialize with `5`:
  rvar('test_ref_2', 5);

// ------------------------------
// Test Code

// Test Function
function Fn1 (v) { v.value = 100; }

// Declare
rvar('test_ref_number');

// First assign
test_ref_number = 5;
console.log('test_ref_number.value === 5', test_ref_number.value === 5);

// Call function with reference
Fn1(test_ref_number);
console.log('test_ref_number.value === 100', test_ref_number.value === 100);

// Increase value
test_ref_number++;
console.log('test_ref_number.value === 101', test_ref_number.value === 101);

// Update value
test_ref_number = test_ref_number - 10;
console.log('test_ref_number.value === 91', test_ref_number.value === 91);

// Declare and initialize
rvar('test_ref_str', 'a');
console.log('test_ref_str.value === "a"', test_ref_str.value === 'a');

// Update value
test_ref_str += 'bc';
console.log('test_ref_str.value === "abc"', test_ref_str.value === 'abc');

// Declare other...
rvar('test_ref_number', 5);
test_ref_number.value === 5; // true

// Call function
Fn1(test_ref_number);
test_ref_number.value === 100; // true

// Increase value
test_ref_number++;
test_ref_number.value === 101; // true

// Update value
test_ref_number = test_ref_number - 10;
test_ref_number.value === 91; // true

test_ref_str.value === "a"; // true

// Update value
test_ref_str += 'bc';
test_ref_str.value === "abc"; // true 
_x000D_
_x000D_
_x000D_

How to create virtual column using MySQL SELECT?

Your syntax would create an alias for a as b, but it wouldn't have scope beyond the results of the statement. It sounds like you may want to create a VIEW

How to call stopservice() method of Service class from the calling activity class

@Juri

If you add IntentFilters for your service, you are saying you want to expose your service to other applications, then it may be stopped unexpectedly by other applications.

BigDecimal setScale and round

One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

If you move the decimal point one place to the right, the difference will become clear:

// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456

Error: Module not specified (IntelliJ IDEA)

This is because the className value which you are passing as argument for
forName(String className) method is not found or doesn't exists, or you a re passing the wrong value as the class name. Here is also a link which could help you.

1. https://docs.oracle.com/javase/7/docs/api/java/lang/ClassNotFoundException.html
2. https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)

Update

Module not specified

According to the snapshot you have provided this problem is because you have not determined the app module of your project, so I suggest you to choose the app module from configuration. For example:

enter image description here

An attempt was made to access a socket in a way forbidden by its access permissions

If You need to access SQL server on hostgator remotely using SSMS, you need to white list your IP in hostgator. Usually it takes 1 hour to open port for the whitelisted IP

What's the difference between “mod” and “remainder”?

sign of remainder will be same as the divisible and the sign of modulus will be same as divisor.

Remainder is simply the remaining part after the arithmetic division between two integer number whereas Modulus is the sum of remainder and divisor when they are oppositely signed and remaining part after the arithmetic division when remainder and divisor both are of same sign.

Example of Remainder:

10 % 3 = 1 [here divisible is 10 which is positively signed so the result will also be positively signed]

-10 % 3 = -1 [here divisible is -10 which is negatively signed so the result will also be negatively signed]

10 % -3 = 1 [here divisible is 10 which is positively signed so the result will also be positively signed]

-10 % -3 = -1 [here divisible is -10 which is negatively signed so the result will also be negatively signed]

Example of Modulus:

5 % 3 = 2 [here divisible is 5 which is positively signed so the remainder will also be positively signed and the divisor is also positively signed. As both remainder and divisor are of same sign the result will be same as remainder]

-5 % 3 = 1 [here divisible is -5 which is negatively signed so the remainder will also be negatively signed and the divisor is positively signed. As both remainder and divisor are of opposite sign the result will be sum of remainder and divisor -2 + 3 = 1]

5 % -3 = -1 [here divisible is 5 which is positively signed so the remainder will also be positively signed and the divisor is negatively signed. As both remainder and divisor are of opposite sign the result will be sum of remainder and divisor 2 + -3 = -1]

-5 % -3 = -2 [here divisible is -5 which is negatively signed so the remainder will also be negatively signed and the divisor is also negatively signed. As both remainder and divisor are of same sign the result will be same as remainder]

I hope this will clearly distinguish between remainder and modulus.

Windows 7 SDK installation failure

I'm having the same error as this "Windows 7 SDK installation failure":

Enter image description here

After finding out, I've got the solution.

It may also happen that the SDK installation runs through with a "success" message at the end, but nothing was actually installed. The only way to really find out whether the SDK was installed is to check the respective directory. C:Files\Microsoft SDKs\Windows\v7.1 or C:Files (x 86) SDKs\Windows\v7.1. If the subdirectory "v 7.1" was created and has some content, the SDK was installed. The solution for this problem is the same as for the issue with the error message: Uninstall Microsoft Visual C++ 2010 Redistributable (see below).

Resolution: Uninstall Microsoft Visual C++ 2010 Redistributable installations prior to Windows SDK installation.

Before the installation, I had the following Microsoft Visual C++ 2010 Redistributable installations. Note that the x 64 version is updated.

  • Microsoft Visual C++ 2010 Redistributable x 64-Microsoft Corporation 10.0.40219 15.2 MB 10.0.40219
  • Microsoft Visual C++ 2010 Redistributable-x 86 10.0.30319 Microsoft Corporation 11.0 MB 10.0.30319

TCPDF output without saving file

I've been using the Output("doc.pdf", "I"); and it doesn't work, I'm always asked for saving the file.

I took a look in documentation and found that

I send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF. http://www.tcpdf.org/doc/classTCPDF.html#a3d6dcb62298ec9d42e9125ee2f5b23a1

Then I think you have to use a plugin to print it, otherwise it is going to be downloaded.

Accessing all items in the JToken

If you know the structure of the json that you're receiving then I'd suggest having a class structure that mirrors what you're receiving in json.

Then you can call its something like this...

AddressMap addressMap = JsonConvert.DeserializeObject<AddressMap>(json);

(Where json is a string containing the json in question)

If you don't know the format of the json you've receiving then it gets a bit more complicated and you'd probably need to manually parse it.

check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx for more info

How to convert hashmap to JSON object in Java

You can use:

new JSONObject(map);

Caution: This will only work for a Map<String, String>!

Other functions you can get from its documentation
http://stleary.github.io/JSON-java/index.html

How can I set the default timezone in node.js?

Unfortunately, setting process.env.TZ doesn't work really well - basically it's indeterminate when the change will be effective).

So setting the system's timezone before starting node is your only proper option.

However, if you can't do that, it should be possible to use node-time as a workaround: get your times in local or UTC time, and convert them to the desired timezone. See How to use timezone offset in Nodejs? for details.

Remove redundant paths from $PATH variable

If you're using Bash, you can also do the following if, let's say, you want to remove the directory /home/wrong/dir/ from your PATH variable:

PATH=`echo $PATH | sed -e 's/:\/home\/wrong\/dir\/$//'`

php REQUEST_URI

perhaps

$id = isset($_GET['id'])?$_GET['id']:null;

and

$other_var = isset($_GET['othervar'])?$_GET['othervar']:null;

How to make parent wait for all child processes to finish?

POSIX defines a function: wait(NULL);. It's the shorthand for waitpid(-1, NULL, 0);, which will suspends the execution of the calling process until any one child process exits. Here, 1st argument of waitpid indicates wait for any child process to end.

In your case, have the parent call it from within your else branch.

RegExp in TypeScript

You can do just:

var regex = /^[1-9]\d{0,2}$/g
regex.test('2') // outputs true

append multiple values for one key in a dictionary

d = {} 

# import list of year,value pairs

for year,value in mylist:
    try:
        d[year].append(value)
    except KeyError:
        d[year] = [value]

The Python way - it is easier to receive forgiveness than ask permission!

Simple (I think) Horizontal Line in WPF?

To draw Horizontal 
************************    
<Rectangle  HorizontalAlignment="Stretch"  VerticalAlignment="Center" Fill="DarkCyan" Height="4"/>

To draw vertical 
*******************
 <Rectangle  HorizontalAlignment="Stretch" VerticalAlignment="Center" Fill="DarkCyan" Height="4" Width="Auto" >
        <Rectangle.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform Angle="90"/>
                <TranslateTransform/>
            </TransformGroup>
        </Rectangle.RenderTransform>
    </Rectangle>

How to list active / open connections in Oracle?

select s.sid as "Sid", s.serial# as "Serial#", nvl(s.username, ' ') as "Username", s.machine as "Machine", s.schemaname as "Schema name", s.logon_time as "Login time", s.program as "Program", s.osuser as "Os user", s.status as "Status", nvl(s.process, ' ') as "OS Process id"
from v$session s
where nvl(s.username, 'a') not like 'a' and status like 'ACTIVE'
order by 1,2

This query attempts to filter out all background processes.

How can I convert an RGB image into grayscale in Python?

I came to this question via Google, searching for a way to convert an already loaded image to grayscale.

Here is a way to do it with SciPy:

import scipy.misc
import scipy.ndimage

# Load an example image
# Use scipy.ndimage.imread(file_name, mode='L') if you have your own
img = scipy.misc.face()

# Convert the image
R = img[:, :, 0]
G = img[:, :, 1]
B = img[:, :, 2]
img_gray = R * 299. / 1000 + G * 587. / 1000 + B * 114. / 1000

# Show the image
scipy.misc.imshow(img_gray)

Occurrences of substring in a string

Do you really have to handle the matching yourself ? Especially if all you need is the number of occurences, regular expressions are tidier :

String str = "helloslkhellodjladfjhello";
Pattern p = Pattern.compile("hello");
Matcher m = p.matcher(str);
int count = 0;
while (m.find()){
    count +=1;
}
System.out.println(count);     

How to get all privileges back to the root user in MySQL?

This worked for me on Ubuntu:

Stop MySQL server:

/etc/init.d/mysql stop

Start MySQL from the commandline:

/usr/sbin/mysqld

In another terminal enter mysql and issue:

grant all privileges on *.* to 'root'@'%' with grant option;

You may also want to add

grant all privileges on *.* to 'root'@'localhost' with grant option;

and optionally use a password as well.

flush privileges;

and then exit your MySQL prompt and then kill the mysqld server running in the foreground. Restart with

/etc/init.d/mysql start  

How to convert an NSTimeInterval (seconds) into minutes

Here's a Swift version:

func durationsBySecond(seconds s: Int) -> (days:Int,hours:Int,minutes:Int,seconds:Int) {
    return (s / (24 * 3600),(s % (24 * 3600)) / 3600, s % 3600 / 60, s % 60)
}

Can be used like this:

let (d,h,m,s) = durationsBySecond(seconds: duration)
println("time left: \(d) days \(h) hours \(m) minutes \(s) seconds")

What is the use of the init() usage in JavaScript?

JavaScript doesn't have a built-in init() function, that is, it's not a part of the language. But it's not uncommon (in a lot of languages) for individual programmers to create their own init() function for initialisation stuff.

A particular init() function may be used to initialise the whole webpage, in which case it would probably be called from document.ready or onload processing, or it may be to initialise a particular type of object, or...well, you name it.

What any given init() does specifically is really up to whatever the person who wrote it needed it to do. Some types of code don't need any initialisation.

function init() {
  // initialisation stuff here
}

// elsewhere in code
init();

How could I convert data from string to long in c#

If you want to get the integer part of that number you must first convert it to a floating number then cast to long.

long l1 = (long)Convert.ToDouble("1100.25");

You can use Math class to round up the number as you like, or just truncate...

JFrame.dispose() vs System.exit()

System.exit(); causes the Java VM to terminate completely.

JFrame.dispose(); causes the JFrame window to be destroyed and cleaned up by the operating system. According to the documentation, this can cause the Java VM to terminate if there are no other Windows available, but this should really just be seen as a side effect rather than the norm.

The one you choose really depends on your situation. If you want to terminate everything in the current Java VM, you should use System.exit() and everything will be cleaned up. If you only want to destroy the current window, with the side effect that it will close the Java VM if this is the only window, then use JFrame.dispose().

How can I get the last 7 characters of a PHP string?

For simplicity, if you do not want send a message, try this

$new_string = substr( $dynamicstring, -min( strlen( $dynamicstring ), 7 ) );

How to execute function in SQL Server 2008

you may be create function before so, update your function again using.

Alter FUNCTION dbo.Afisho_rankimin(@emri_rest int)
RETURNS int
AS
  BEGIN
     Declare @rankimi int
     Select @rankimi=dbo.RESTORANTET.Rankimi
     From RESTORANTET
     Where  dbo.RESTORANTET.ID_Rest=@emri_rest
     RETURN @rankimi
END
GO

SELECT dbo.Afisho_rankimin(5) AS Rankimi
GO

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

Suppose you have these buttons on page like :

<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit"value="Enable All" onclick="change()"/>

The js code:

function change(){
   var toenable = document.querySelectorAll(".byBtn");        
    for (var k in toenable){
         toenable[k].removeAttribute("disabled");
    }
}

Renaming a directory in C#

There is no difference between moving and renaming; you should simply call Directory.Move.

In general, if you're only doing a single operation, you should use the static methods in the File and Directory classes instead of creating FileInfo and DirectoryInfo objects.

For more advice when working with files and directories, see here.

How to use an image for the background in tkinter?

A simple tkinter code for Python 3 for setting background image .

from tkinter import *
from tkinter import messagebox
top = Tk()

C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

C.pack()
top.mainloop

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

How to print all information from an HTTP request to the screen, in PHP

Putting together answers from Peter Bailey and Cmyker you get something like:

<?php
foreach ($_SERVER as $key => $value) {
    if (strpos($key, 'HTTP_') === 0) {
        $chunks = explode('_', $key);
        $header = '';
        for ($i = 1; $y = sizeof($chunks) - 1, $i < $y; $i++) {
            $header .= ucfirst(strtolower($chunks[$i])).'-';
        }
        $header .= ucfirst(strtolower($chunks[$i])).': '.$value;
        echo $header."\n";
    }
}
$body = file_get_contents('php://input');
if ($body != '') {
  print("\n$body\n\n");
}
?>

which works with the php -S built-in webserver, which is quite a handy feature of PHP.

How to export a table dataframe in PySpark to csv?

You need to repartition the Dataframe in a single partition and then define the format, path and other parameter to the file in Unix file system format and here you go,

df.repartition(1).write.format('com.databricks.spark.csv').save("/path/to/file/myfile.csv",header = 'true')

Read more about the repartition function Read more about the save function

However, repartition is a costly function and toPandas() is worst. Try using .coalesce(1) instead of .repartition(1) in previous syntax for better performance.

Read more on repartition vs coalesce functions.

SQL Server procedure declare a list

That is not possible with a normal query since the in clause needs separate values and not a single value containing a comma separated list. One solution would be a dynamic query

declare @myList varchar(100)
set @myList = '(1,2,5,7,10)'
exec('select * from DBTable where id IN ' + @myList)

How do I fit an image (img) inside a div and keep the aspect ratio?

Unfortunately max-width + max-height do not fully cover my task... So I have found another solution:

To save the Image ratio while scaling you also can use object-fit CSS3 propperty.

Useful article: Control image aspect ratios with CSS3

img {
    width: 100%; /* or any custom size */
    height: 100%; 
    object-fit: contain;
}

Bad news: IE not supported (Can I Use)

Difference between "enqueue" and "dequeue"

In my opinion one of the worst chosen word's to describe the process, as it is not related to anything in real-life or similar. In general the word "queue" is very bad as if pronounced, it sounds like the English character "q". See the inefficiency here?

enqueue: to place something into a queue; to add an element to the tail of a queue;

dequeue to take something out of a queue; to remove the first available element from the head of a queue

source: https://www.thefreedictionary.com

Add row to query result using select

is it possible to extend query results with literals like this?

Yes.

Select Name
From Customers
UNION ALL
Select 'Jason'
  • Use UNION to add Jason if it isn't already in the result set.
  • Use UNION ALL to add Jason whether or not he's already in the result set.

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

What i have done is that import a new project into eclipse workspace, and that path of that was be

android-sdk-macosx/extras/google/google_play_services/libproject/google-play-services_lib

and add as library in your project.. that it .. simple!! you might require to add support library in your project.

Symfony - generate url with parameter in controller

make sure your controller extends Symfony\Bundle\FrameworkBundle\Controller\Controller;

you should also check app/console debug:router in terminal to see what name symfony has named the route

in my case it used a minus instead of an underscore

i.e blog-show

$uri = $this->generateUrl('blog-show', ['slug' => 'my-blog-post']);

How to detect control+click in Javascript from an onclick div attribute?

I'd recommend using JQuery's keyup and keydown methods on the document, as it normalizes the event codes, to make one solution crossbrowser.

For the right click, you can use oncontextmenu, however beware it can be buggy in IE8. See a chart of compatibility here:

http://www.quirksmode.org/dom/events/contextmenu.html

<p onclick="selectMe(1)" oncontextmenu="selectMe(2)">Click me</p>

$(document).keydown(function(event){
    if(event.which=="17")
        cntrlIsPressed = true;
});

$(document).keyup(function(){
    cntrlIsPressed = false;
});

var cntrlIsPressed = false;


function selectMe(mouseButton)
{
    if(cntrlIsPressed)
    {
        switch(mouseButton)
        {
            case 1:
                alert("Cntrl +  left click");
                break;
            case 2:
                alert("Cntrl + right click");
                break;
            default:
                break;
        }
    }


}

how to generate web service out of wsdl

How about using the wsdl /server or wsdl /serverinterface switches? As far as I understand the wsdl.exe command line properties, that's what you're looking for.

- ADVANCED -

/server

Server switch has been deprecated. Please use /serverInterface instead.
Generate an abstract class for an xml web service implementation using
ASP.NET based on the contracts. The default is to generate client proxy
classes.

On the other hand: why do you want to create obsolete technology solutions? Why not create this web service as a WCF service. That's the current and more modern, much more flexible way to do this!

Marc


UPDATE:

When I use wsdl /server on a WSDL file, I get this file created:

[WebService(Namespace="http://.......")]
public abstract partial class OneCrmServiceType : System.Web.Services.WebService 
{
    /// <remarks/>
    [WebMethod]
    public abstract void OrderCreated(......);
}

This is basically almost exactly the same code that gets generated when you add an ASMX file to your solution (in the code behind file - "yourservice.asmx.cs"). I don't think you can get any closer to creating an ASMX file from a WSDL file.

You can always add the "yourservice.asmx" manually - it doesn't really contain much:

<%@ WebService Language="C#" CodeBehind="YourService.asmx.cs" 
      Class="YourServiceNamespace.YourServiceClass" %>

Python Remove last 3 characters of a string

>>> foo = 'BS1 1AB'
>>> foo.replace(" ", "").rstrip()[:-3].upper()
'BS1'

How to find the kafka version in linux

When you install Kafka in Centos7 with confluent :

yum install confluent-platform-oss-2.11

You can see the version of Kafka with :

yum deplist confluent-platform-oss-2.11

You can read : confluent-kafka-2.11 >= 0.10.2.1

Trigger an event on `click` and `enter`

Use keypress event on usersSearch textbox and look for Enter button. If enter button is pressed then trigger the search button click event which will do the rest of work. Try this.

$('document').ready(function(){
    $('#searchButton').click(function(){
        var search = $('#usersSearch').val();
        $.post('../searchusers.php',{search: search},function(response){
            $('#userSearchResultsTable').html(response);
        });
    })
    $('#usersSearch').keypress(function(e){
        if(e.which == 13){//Enter key pressed
            $('#searchButton').click();//Trigger search button click event
        }
    });

});

Demo

View RDD contents in Python Spark?

In Spark 2.0 (I didn't tested with earlier versions). Simply:

print myRDD.take(n)

Where n is the number of lines and myRDD is wc in your case.

Fix footer to bottom of page

This code working for me :

footer{
    background-color: #333;
    color: #EEE;
    padding: 20px;
    left: 0;
    width: 100%;
    bottom: 0;
    position: fixed;
}

Important thing you should added bottom:0; and position: fixed;

Pass arguments to Constructor in VBA

I use one Factory module that contains one (or more) constructor per class which calls the Init member of each class.

For example a Point class:

Class Point
Private X, Y
Sub Init(X, Y)
  Me.X = X
  Me.Y = Y
End Sub

A Line class

Class Line
Private P1, P2
Sub Init(Optional P1, Optional P2, Optional X1, Optional X2, Optional Y1, Optional Y2)
  If P1 Is Nothing Then
    Set Me.P1 = NewPoint(X1, Y1)
    Set Me.P2 = NewPoint(X2, Y2)
  Else
    Set Me.P1 = P1
    Set Me.P2 = P2
  End If
End Sub

And a Factory module:

Module Factory
Function NewPoint(X, Y)
  Set NewPoint = New Point
  NewPoint.Init X, Y
End Function

Function NewLine(Optional P1, Optional P2, Optional X1, Optional X2, Optional Y1, Optional Y2)
  Set NewLine = New Line
  NewLine.Init P1, P2, X1, Y1, X2, Y2
End Function

Function NewLinePt(P1, P2)
  Set NewLinePt = New Line
  NewLinePt.Init P1:=P1, P2:=P2
End Function

Function NewLineXY(X1, Y1, X2, Y2)
  Set NewLineXY = New Line
  NewLineXY.Init X1:=X1, Y1:=Y1, X2:=X2, Y2:=Y2
End Function

One nice aspect of this approach is that makes it easy to use the factory functions inside expressions. For example it is possible to do something like:

D = Distance(NewPoint(10, 10), NewPoint(20, 20)

or:

D = NewPoint(10, 10).Distance(NewPoint(20, 20))

It's clean: the factory does very little and it does it consistently across all objects, just the creation and one Init call on each creator.

And it's fairly object oriented: the Init functions are defined inside the objects.

EDIT

I forgot to add that this allows me to create static methods. For example I can do something like (after making the parameters optional):

NewLine.DeleteAllLinesShorterThan 10

Unfortunately a new instance of the object is created every time, so any static variable will be lost after the execution. The collection of lines and any other static variable used in this pseudo-static method must be defined in a module.

How to get current instance name from T-SQL

How about this:

EXECUTE xp_regread @rootkey='HKEY_LOCAL_MACHINE',
                   @key='SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQl',
                   @value_name='MSSQLSERVER'

This will get the instance name as well. null means default instance:

SELECT SERVERPROPERTY ('InstanceName')

http://technet.microsoft.com/en-us/library/ms174396.aspx

How to hash a string into 8 digits?

Just to complete JJC answer, in python 3.5.3 the behavior is correct if you use hashlib this way:

$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded

$ python3 -V
Python 3.5.3

Prevent multiple instances of a given app in .NET?

i tried all the solutions here and nothing worked in my C# .net 4.0 project. Hoping to help someone here the solution that worked for me:

As main class variables:

private static string appGuid = "WRITE AN UNIQUE GUID HERE";
private static Mutex mutex;

When you need to check if app is already running:

bool mutexCreated;
mutex = new Mutex(true, "Global\\" + appGuid, out mutexCreated);
if (mutexCreated)
    mutex.ReleaseMutex();

if (!mutexCreated)
{
    //App is already running, close this!
    Environment.Exit(0); //i used this because its a console app
}

I needed to close other istances only with some conditions, this worked well for my purpose

How to check if an NSDictionary or NSMutableDictionary contains a key?

if ([mydict objectForKey:@"mykey"]) {
    // key exists.
}
else
{
    // ...
}

Mask for an Input to allow phone numbers?

No need to reinvent the wheel! Use Currency Mask, unlike TextMaskModule, this one works with number input type and it's super easy to configure. I found when I made my own directive, I had to keep converting between number and string to do calculations. Save yourself the time. Here's the link:

https://github.com/cesarrew/ng2-currency-mask

Tomcat Server Error - Port 8080 already in use

Since it is easy to tackle with Command Prompt. Open the CMD and type following.

netstat -aon | find "8080"

If a process uses above port, it should return something output like this.

TCP    xxx.xx.xx.xx:8080      xx.xx.xx.xxx:443      ESTABLISHED     2222

The last column value (2222) is referred to the Process ID (PID).

Just KILL it as follows.

taskkill /F /PID 2222

Now you can start your server.

Setting "checked" for a checkbox with jQuery

I'm missing the solution. I'll always use:

if ($('#myCheckBox:checked').val() !== undefined)
{
    //Checked
}
else
{
    //Not checked
}

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

I had the same issue (EF Core) while setting up xUnit tests. What 'fixed' it for me in testing was looping through the change tracker entities after setting up the seed data.

  • at the bottom of the SeedAppDbContext() method.

I set up a Test Mock Context:

/// <summary>
/// Get an In memory version of the app db context with some seeded data
/// </summary>
public static AppDbContext GetAppDbContext(string dbName)
{
    //set up the options to use for this dbcontext
    var options = new DbContextOptionsBuilder<AppDbContext>()
        .UseInMemoryDatabase(databaseName: dbName)
        //.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
        .Options;

    var dbContext = new AppDbContext(options);
    dbContext.SeedAppDbContext();
    return dbContext;
}

Extension method to add some seed data:

  • and detach entities in foreach loop at bottom of method.
    public static void SeedAppDbContext(this AppDbContext appDbContext)
    {
       // add companies
       var c1 = new Company() { Id = 1, CompanyName = "Fake Company One", ContactPersonName = "Contact one", eMail = "[email protected]", Phone = "0123456789", AdminUserId = "" };
       c1.Address = new Address() { Id = 1, AddressL1 = "Field Farm", AddressL2 = "Some Lane", City = "some city", PostalCode = "AB12 3CD" };
       appDbContext.CompanyRecords.Add(c1);
                        
       var nc1 = new Company() { Id = 2, CompanyName = "Test Company 2", ContactPersonName = "Contact two", eMail = "[email protected]", Phone = "0123456789", Address = new Address() { }, AdminUserId = "" };
       nc1.Address = new Address() { Id = 2, AddressL1 = "The Barn", AddressL2 = "Some Lane", City = "some city", PostalCode = "AB12 3CD" };
       appDbContext.CompanyRecords.Add(nc1);

       //....and so on....
            
       //last call to commit everything to the memory db
       appDbContext.SaveChanges();

       //and then to detach everything 
       foreach (var entity in appDbContext.ChangeTracker.Entries())
       {
           entity.State = EntityState.Detached;
       }
    }

The controller put method

The .ConvertTo<>() Method is an extension method from ServiceStack

 [HttpPut]
public async Task<IActionResult> PutUpdateCompany(CompanyFullDto company)
{
    if (0 == company.Id)
        return BadRequest();
    try
    {
        Company editEntity = company.ConvertTo<Company>();
        
        //Prior to detaching an error thrown on line below (another instance with id)
        var trackedEntity = _appDbContext.CompanyRecords.Update(editEntity);
        

        await _appDbContext.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException dbError)
    {
        if (!CompanyExists(company.Id))
            return NotFound();
        else
            return BadRequest(dbError);
    }
    catch (Exception Error)
    {
        return BadRequest(Error);
    }
    return Ok();
}

and the test:

    [Fact]
    public async Task PassWhenEditingCompany()
    {
        var _appDbContext = AppDbContextMocker.GetAppDbContext(nameof(CompaniesController));
        var _controller = new CompaniesController(null, _appDbContext);

        //Arrange
        const string companyName = "Fake Company One";
        const string contactPerson = "Contact one";

        const string newCompanyName = "New Fake Company One";
        const string newContactPersonName = "New Contact Person";

        //Act
        var getResult = _controller.GetCompanyById(1);
        var getEntity = (getResult.Result.Result as OkObjectResult).Value;
        var entityDto = getEntity as CompanyFullDto;


        //Assert
        Assert.Equal(companyName, entityDto.CompanyName);
        Assert.Equal(contactPerson, entityDto.ContactPersonName);
        Assert.Equal(1, entityDto.Id);

        //Arrange
        Company entity = entityDto.ConvertTo<Company>();
        entity.CompanyName = newCompanyName;
        entity.ContactPersonName = newContactPersonName;
        CompanyFullDto entityDtoUpd = entity.ConvertTo<CompanyFullDto>();

        //Act
        var result = await _controller.PutUpdateCompany(entityDtoUpd) as StatusCodeResult;

        //Assert           
        Assert.True(result.StatusCode == 200);

        //Act
        getResult = _controller.GetCompanyById(1);
        getEntity = (getResult.Result.Result as OkObjectResult).Value;
        
        entityDto = getEntity as CompanyFullDto;
        
        //Assert
        Assert.Equal(1, entityDto.Id); // didn't add a new record
        Assert.Equal(newCompanyName, entityDto.CompanyName); //updated the name
        Assert.Equal(newContactPersonName, entityDto.ContactPersonName); //updated the contact

//make sure to dispose of the _appDbContext otherwise running the full test will fail.
_appDbContext.Dispose();
    }

Setting max width for body using Bootstrap

In responsive.less, you can comment out the line that imports responsive-1200px-min.less.

// Large desktops

@import "responsive-1200px-min.less";

Like so:

// Large desktops

// @import "responsive-1200px-min.less";

How to connect to MongoDB in Windows?

Steps to start a certain local MongoDB instance and to connect to in from NodeJS app:

  1. Create mongod.cfg for a new database using the path C:\Program Files\MongoDB\Server\4.0\mongod.cfg with the content

    systemLog:
      destination: file
      path: C:\Program Files\MongoDB\Server\4.0\log\mongod.log
    storage:
      dbPath: C:\Program Files\MongoDB\Server\4.0\data\db
    
  2. Install mongoDB database by running

    mongod.exe --config "C:\Program Files\MongoDB\Server\4.0\mongod.cfg" --install

  3. Run a particular mongoDB database

    mongod.exe --config "C:\Program Files\MongoDB\Server\4.0\mongod.cfg"

  4. Run mongoDB service

    mongo 127.0.0.1:27017/db
    

    and !see mongoDB actual connection string to coonect to the service from NodeJS app

    MongoDB shell version v4.0.9
    connecting to: mongodb://127.0.0.1:27017/db?gssapiServiceName=mongodb
    Implicit session: session { "id" : UUID("c7ed5ab4-c64e-4bb8-aad0-ab4736406c03") }
    MongoDB server version: 4.0.9
    Server has startup warnings:
    ...
    

Change :hover CSS properties with JavaScript

You can use mouse events to control like hover. For example, the following code is making visible when you hover that element.

var foo = document.getElementById("foo");
foo.addEventListener('mouseover',function(){
   foo.style.display="block";
})
foo.addEventListener('mouseleave',function(){
   foo.style.display="none";
})

Sum values in foreach loop php

Use +=

$val = 0;

foreach($arr as $var) {
   $val += $var; 
}

echo $val;

Iterating Through a Dictionary in Swift

Here is an alternative for that experiment (Swift 3.0). This tells you exactly which kind of number was the largest.

let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]

var largest = 0
var whichKind: String? = nil

for (kind, numbers) in interestingNumbers {
    for number in numbers {
    if number > largest {
        whichKind = kind
        largest = number
    }
  }
}

print(whichKind)
print(largest)

OUTPUT:
Optional("Square")
25

int array to string

I like using StringBuilder with Aggregate(). The "trick" is that Append() returns the StringBuilder instance itself:

var sb = arr.Aggregate( new StringBuilder(), ( s, i ) => s.Append( i ) );
var result = sb.ToString();     

How to add headers to OkHttp request interceptor?

you can do it this way

private String GET(String url, Map<String, String> header) throws IOException {
        Headers headerbuild = Headers.of(header);
        Request request = new Request.Builder().url(url).headers(headerbuild).
                        build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

Regex pattern for checking if a string starts with a certain substring?

The following will match on any string that starts with mailto, ftp or http:

 RegEx reg = new RegEx("^(mailto|ftp|http)");

To break it down:

  • ^ matches start of line
  • (mailto|ftp|http) matches any of the items separated by a |

I would find StartsWith to be more readable in this case.

gcc error: wrong ELF class: ELFCLASS64

It turns out the compiler version I was using did not match the compiled version done with the coreset.o.

One was 32bit the other was 64bit. I'll leave this up in case anyone else runs into a similar problem.

Get characters after last / in url

$str = basename($url);

Python Requests library redirect new url

I think requests.head instead of requests.get will be more safe to call when handling url redirect,check the github issue here:

r = requests.head(url, allow_redirects=True)
print(r.url)

Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

Even though both AWS and Heroku are cloud platforms, they are different as AWS is IaaS and Heroku is PaaS

Why is my JavaScript function sometimes "not defined"?

It shouldn't be possible for this to happen if you're just including the scripts on the page.

The "copyArray" function should always be available when the JavaScript code starts executing no matter if it is declared before or after it -- unless you're loading the JavaScript files in dynamically with a dependency library. There are all sorts of problems with timing if that's the case.

case statement in where clause - SQL Server

simply do the select:

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND
((@day = 'Monday' AND (Monday = 1))
OR (@day = 'Tuesday' AND (Tuesday = 1))
OR (Wednesday = 1))

Android - R cannot be resolved to a variable

I think I found another solution to this question.

Go to Project > Properties > Java Build Path > tab [Order and Export] > Tick Android Version Checkbox enter image description here Then if your workspace does not build automatically…

Properties again > Build Project enter image description here

How to stretch in width a WPF user control to its window?

Does setting the HorizontalAlignment to Stretch, and the Width to Auto on the user control achieve the desired results?

How do I add a newline to a TextView in Android?

Just try:

Textview_name.settext("something \n  new line "):

In Java file.

Inline onclick JavaScript variable

Yes, JavaScript variables will exist in the scope they are created.

var bannerID = 55;

<input id="EditBanner" type="button" 
  value="Edit Image" onclick="EditBanner(bannerID);"/>


function EditBanner(id) {
   //Do something with id
}

If you use event handlers and jQuery it is simple also

$("#EditBanner").click(function() {
   EditBanner(bannerID);
});

SSLHandshakeException: No subject alternative names present

Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.

But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.

static {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {
            public boolean verify(String hostname, SSLSession session)
            {
                // ip address of the service URL(like.23.28.244.244)
                if (hostname.equals("23.28.244.244"))
                    return true;
                return false;
            }
        });
}

If you happen to be using Java 8, there is a much slicker way of achieving the same result:

static {
    HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}

Why do I get a SyntaxError for a Unicode escape in my file path?

You need to use a raw string, double your slashes or use forward slashes instead:

r'C:\Users\expoperialed\Desktop\Python'
'C:\\Users\\expoperialed\\Desktop\\Python'
'C:/Users/expoperialed/Desktop/Python'

In regular python strings, the \U character combination signals a extended Unicode codepoint escape.

You can hit any number of other issues, for any of the recognised escape sequences, such as \a or \t or \x, etc.

Android DialogFragment vs Dialog

I would recommend using DialogFragment.

Sure, creating a "Yes/No" dialog with it is pretty complex considering that it should be rather simple task, but creating a similar dialog box with Dialog is surprisingly complicated as well.

(Activity lifecycle makes it complicated - you must let Activity manage the lifecycle of the dialog box - and there is no way to pass custom parameters e.g. the custom message to Activity.showDialog if using API levels under 8)

The nice thing is that you can usually build your own abstraction on top of DialogFragment pretty easily.

Generics in C#, using type of a variable as parameter

The point about generics is to give compile-time type safety - which means that types need to be known at compile-time.

You can call generic methods with types only known at execution time, but you have to use reflection:

// For non-public methods, you'll need to specify binding flags too
MethodInfo method = GetType().GetMethod("DoesEntityExist")
                             .MakeGenericMethod(new Type[] { t });
method.Invoke(this, new object[] { entityGuid, transaction });

Ick.

Can you make your calling method generic instead, and pass in your type parameter as the type argument, pushing the decision one level higher up the stack?

If you could give us more information about what you're doing, that would help. Sometimes you may need to use reflection as above, but if you pick the right point to do it, you can make sure you only need to do it once, and let everything below that point use the type parameter in a normal way.

Python IndentationError: unexpected indent

Simply copy your script and put under """ your entire code """ ...

specify this line in a variable.. like,

a = """ your entire code """
print a.replace('    ','    ') # first 4 spaces tab second four space from space bar

print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..

now execute this code, in sublime using ctrl+b, now it will print indented code in console. that's it

Get Multiple Values in SQL Server Cursor

Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:

declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for 
    select
         row_number() over (order by(select null)) as RowNum
        ,Data -- you fields
    from YourIntTable
open @cur
begin try
    fetch last from @cur into @lastNum, @data
    fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value 
    while @i < @lastNum
    begin
        set @i += 1

        --Do your job here
        print @data

        fetch next from @cur into @rowNum, @data
    end
end try
begin catch
    close @cur      --|
    deallocate @cur --|-remove this 3 lines if you do not throw
    ;throw          --|
end catch
close @cur
deallocate @cur

How to do a PUT request with curl?

Using the -X flag with whatever HTTP verb you want:

curl -X PUT -d arg=val -d arg2=val2 localhost:8080

This example also uses the -d flag to provide arguments with your PUT request.

Detect if string contains any spaces

var string  = 'hello world';
var arr = string.split(''); // converted the string to an array and then checked: 
if(arr[i] === ' '){
   console.log(i);
}

I know regex can do the trick too!

How to get phpmyadmin username and password

I had a problem with this. I didn't even create any passwords so I was confused. I googled it and I found out that I should just write root as username and than click GO. I hope it helps.

How to make a phone call in android and come back to my activity when the call is done?

@Dmitri Novikov, FLAG_ACTIVITY_CLEAR_TOP clears any active instance on top of the new one. So, it may end the old instance before it completes the process.

How can I know if Object is String type object?

Use the instanceof syntax.

Like so:

Object foo = "";

if( foo instanceof String ) {
  // do something String related to foo
}

How to handle notification when app in background in Firebase

Simple summary like this

  • if your app is running;

    onMessageReceived()
    

is triggers.

  • if your app is not running (killed by swiping) ;

    onMessageReceived()
    

is not triggered and delivered by direclty. If you have any specialy key-value pair. They don' t work beacuse of onMessageReceived() not working.

I' ve found this way;

In your launcher activity, put this logic,

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState, R.layout.activity_splash);

    if (getIntent().getExtras() != null && getIntent().getExtras().containsKey("PACKAGE_NAME")) {

        // do what you want

        // and this for killing app if we dont want to start
        android.os.Process.killProcess(android.os.Process.myPid());

    } else {

        //continue to app
    }
}

in this if block, search for your keys according to firebase UI.

In this example my key and value like above; (sorry for language =)) enter image description here

When my code works, i get "com.rda.note".

android.os.Process.killProcess(android.os.Process.myPid());

with this line of code, i closed my application and open Google Play Market

happy coding =)

Multiline text in JLabel

I have used JTextArea for multiline JLabels.

JTextArea textarea = new JTextArea ("1\n2\n3\n"+"4\n");

http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html

How to check if an alert exists using WebDriver?

ExpectedConditions is obsolete, so:

        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
        wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent());

C# Selenium 'ExpectedConditions is obsolete'

How do you reindex an array in PHP but with indexes starting from 1?

Here's my own implementation. Keys in the input array will be renumbered with incrementing keys starting from $start_index.

function array_reindex($array, $start_index)
{
    $array = array_values($array);
    $zeros_array = array_fill(0, $start_index, null);
    return array_slice(array_merge($zeros_array, $array), $start_index, null, true);
}

Update multiple rows using select statement

None of above answers worked for me in MySQL, the following query worked though:

UPDATE
    Table1 t1
    JOIN
    Table2 t2 ON t1.ID=t2.ID 
SET
    t1.value =t2.value
WHERE
    ...

Using other keys for the waitKey() function of opencv

If you want to pause the program to take screenshots of the progress

(shown in let's say cv2.imshow)

cv2.waitKey(0) would continue after pressing "Scr" button (or its combination), but you can try this

cv2.waitKey(0)
input('')

cv2.waitkey(0) to give the program enough time to process everything you want to see in the imshow and input('')

to make it wait for you to press Enter in the console window

this works on python 3

Move the mouse pointer to a specific position?

Couldn't this simply be done by getting actual position of the mouse pointer then calculating and compensating sprite/scene mouse actions based off this compensation?

For instance you need the mouse pointer to be bottom center, but it sits top left; hide the cursor, use a shifted cursor image. Shift the cursor movement and map mouse input to match re-positioned cursor sprite (or 'control') clicks When/if bounds are hit, recalculate. If/when the cursor actually hits the point you want it to be, remove compensation.

Disclaimer, not a game developer.

How to assign text size in sp value using java code

This is code for the convert PX to SP format. 100% Works

view.setTextSize(TypedValue.COMPLEX_UNIT_PX, 24);

How to check sbt version?

You can use sbt about

Example: 
    C:\Users\smala>sbt about
    [info] Set current project to smala (in build file:/C:/Users/smala/)
    [info] This is sbt 0.13.6
    [info] The current project is {file:/C:/Users/smala/}smala 0.1-SNAPSHOT
    [info] The current project is built against Scala 2.10.4
    [info] Available Plugins: sbt.plugins.IvyPlugin, sbt.plugins.JvmPlugin,   sbt.plugins.CorePlugin, sbt.plugins.JUnitXmlReportPlugin
    [info] sbt, sbt plugins, and build definitions are using Scala 2.10.4"

Media Player called in state 0, error (-38,0)

Some times file are encoded in a way that Android can't decode. Even some mp4 files can not be played. Please try a different file format (.3gp are played most of the time) and see..

How to call a method function from another class?

In class WeatherRecord:

First import the class if they are in different package else this statement is not requires

Import <path>.ClassName



Then, just referene or call your object like:

Date d;
TempratureRange tr;
d = new Date();
tr = new TempratureRange;
//this can be done in Single Line also like :
// Date d = new Date();



But in your code you are not required to create an object to call function of Date and TempratureRange. As both of the Classes contain Static Function , you cannot call the thoes function by creating object.

Date.date(date,month,year);   // this is enough to call those static function 


Have clear concept on Object and Static functions. Click me

Calculate MD5 checksum for a file

And if you need to calculate the MD5 to see whether it matches the MD5 of an Azure blob, then this SO question and answer might be helpful: MD5 hash of blob uploaded on Azure doesnt match with same file on local machine

How to set selectedIndex of select element using display text?

Try this:

function SelectAnimal()
{
    var animals = document.getElementById('Animals');
    var animalsToFind = document.getElementById('AnimalToFind');
    // get the options length
    var len = animals.options.length;
    for(i = 0; i < len; i++)
    {
      // check the current option's text if it's the same with the input box
      if (animals.options[i].innerHTML == animalsToFind.value)
      {
         animals.selectedIndex = i;
         break;
      }     
    }
}

Adding Buttons To Google Sheets and Set value to Cells on clicking

Consider building an Add-on that has an actual button and not using the outdated method of linking an image to a script function.

In the script editor, under the Help menu >> Welcome Screen >> link to Google Sheets Add-on - will give you sample code to use.

Multiline TextBox multiple newline

I had the same problem. If I add one Environment.Newline I get one new line in the textbox. But if I add two Environment.Newline I get one new line. In my web app I use a whitespace modul that removes all unnecessary white spaces. If i disable this module I get two new lines in my textbox. Hope that helps.

Pattern matching using a wildcard

If you want to examine elements inside a dataframe you should not be using ls() which only looks at the names of objects in the current workspace (or if used inside a function in the current environment). Rownames or elements inside such objects are not visible to ls() (unless of course you add an environment argument to the ls(.)-call). Try using grep() which is the workhorse function for pattern matching of character vectors:

result <- a[ grep("blue", a$x) , ]  # Note need to use `a$` to get at the `x`

If you want to use subset then consider the closely related function grepl() which returns a vector of logicals can be used in the subset argument:

subset(a, grepl("blue", a$x))
      x
2 blue1
3 blue2

Edit: Adding one "proper" use of glob2rx within subset():

result <- subset(a,  grepl(glob2rx("blue*") , x) )
result
      x
2 blue1
3 blue2

I don't think I actually understood glob2rx until I came back to this question. (I did understand the scoping issues that were ar the root of the questioner's difficulties. Anybody reading this should now scroll down to Gavin's answer and upvote it.)