Programs & Examples On #Nhibernate mapping

XML mappings for the .NET framework object-relational mapper (ORM) NHibernate as created with .hbm.xml files.

NHibernate.MappingException: No persister for: XYZ

I my case I fetched an entity without await:

var company = _unitOfWork.Session.GetAsync<Company>(id);

and then I tried to delete it:

await _unitOfWork.Session.DeleteAsync(company);

I could not decipher the error message that I'm deleting a Task<Company> instead of Company:

MappingException: No persister for: System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1+AsyncStateMachineBox'1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null],[NHibernate.Impl.SessionImpl+d__54`1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null]], NHibernate, Version=5.3.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4]]

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

Does HTML5 <video> playback support the .avi format?

The HTML specification never specifies any content formats. That's not its job. There's plenty of standards organizations that are more qualified than the W3C to specify video formats.

That's what content negotiation is for.

  • The HTML specification doesn't specify any image formats for the <img> element.
  • The HTML specification doesn't specify any style sheet languages for the <style> element.
  • The HTML specification doesn't specify any scripting languages for the <script> element.
  • The HTML specification doesn't specify any object formats for the <object> and embed elements.
  • The HTML specification doesn't specify any audio formats for the <audio> element.

Why should it specify one for the <video> element?

What is the mouse down selector in CSS?

I recently found out that :active:focus does the same thing in css as :active:hover if you need to override a custom css library, they might use both.

How to increase memory limit for PHP over 2GB?

For others who are experiencing with the same problem, here is the description of the bug in php + patch https://bugs.php.net/bug.php?id=44522

return value after a promise

Use a pattern along these lines:

function getValue(file) {
  return lookupValue(file);
}

getValue('myFile.txt').then(function(res) {
  // do whatever with res here
});

(although this is a bit redundant, I'm sure your actual code is more complicated)

How to quickly check if folder is empty (.NET)?

Here is something that might help you doing it. I managed to do it in two iterations.

 private static IEnumerable<string> GetAllNonEmptyDirectories(string path)
   {
     var directories =
        Directory.EnumerateDirectories(path, "*.*", SearchOption.AllDirectories)
        .ToList();

     var directoryList = 
     (from directory in directories
     let isEmpty = Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories).Length == 0
     where !isEmpty select directory)
     .ToList();

     return directoryList.ToList();
   }

How to deal with persistent storage (e.g. databases) in Docker

@tommasop's answer is good, and explains some of the mechanics of using data-only containers. But as someone who initially thought that data containers were silly when one could just bind mount a volume to the host (as suggested by several other answers), but now realizes that in fact data-only containers are pretty neat, I can suggest my own blog post on this topic: Why Docker Data Containers (Volumes!) are Good

See also: my answer to the question "What is the (best) way to manage permissions for Docker shared volumes?" for an example of how to use data containers to avoid problems like permissions and uid/gid mapping with the host.

To address one of the OP's original concerns: that the data container must not be deleted. Even if the data container is deleted, the data itself will not be lost as long as any container has a reference to that volume i.e. any container that mounted the volume via --volumes-from. So unless all the related containers are stopped and deleted (one could consider this the equivalent of an accidental rm -fr /) the data is safe. You can always recreate the data container by doing --volumes-from any container that has a reference to that volume.

As always, make backups though!

UPDATE: Docker now has volumes that can be managed independently of containers, which further makes this easier to manage.

Location Services not working in iOS 8

To Access User Location in iOS 8 you will have to add,

NSLocationAlwaysUsageDescription in the Info.plist 

This will ask the user for the permission to get their current location.

What is the best way to detect a mobile device?

You could also use server side script and set javascript variables from it.

Example in php

download http://code.google.com/p/php-mobile-detect/ and then set javascript variables.

<script>
//set defaults
var device_type = 'desktop';
</script>

<?php
require_once( 'Mobile_Detect.php');
$detect = new Mobile_Detect();
?>

<script>
device_type="<?php echo ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'mobile') : 'desktop'); ?>";
alert( device_type);
</script>

How to get current time in milliseconds in PHP?

Use microtime(true) in PHP 5, or the following modification in PHP 4:

array_sum(explode(' ', microtime()));

A portable way to write that code would be:

function getMicrotime()
{
    if (version_compare(PHP_VERSION, '5.0.0', '<'))
    {
        return array_sum(explode(' ', microtime()));
    }

    return microtime(true);
}

How to check if a line has one of the strings in a list?

This still loops through the cartesian product of the two lists, but it does it one line:

>>> lines1 = ['soup', 'butter', 'venison']
>>> lines2 = ['prune', 'rye', 'turkey']
>>> search_strings = ['a', 'b', 'c']
>>> any(s in l for l in lines1 for s in search_strings)
True
>>> any(s in l for l in lines2 for s in search_strings)
False

This also have the advantage that any short-circuits, and so the looping stops as soon as a match is found. Also, this only finds the first occurrence of a string from search_strings in linesX. If you want to find multiple occurrences you could do something like this:

>>> lines3 = ['corn', 'butter', 'apples']
>>> [(s, l) for l in lines3 for s in search_strings if s in l]
[('c', 'corn'), ('b', 'butter'), ('a', 'apples')]

If you feel like coding something more complex, it seems the Aho-Corasick algorithm can test for the presence of multiple substrings in a given input string. (Thanks to Niklas B. for pointing that out.) I still think it would result in quadratic performance for your use-case since you'll still have to call it multiple times to search multiple lines. However, it would beat the above (cubic, on average) algorithm.

How to implement a material design circular progress bar in android

The platform uses a vector drawable, so you can't reuse it as in in older versions.
However, the support lib v4 contains a backport of this drawable : http://androidxref.com/5.1.0_r1/xref/frameworks/support/v4/java/android/support/v4/widget/MaterialProgressDrawable.java It has a @hide annotation (it is here for the SwipeRefreshLayout), but nothing prevents you from copying this class in your codebase.

Setting background color for a JFrame

Here's another method:

private void RenkMouseClicked(java.awt.event.MouseEvent evt) {
    renk = JColorChooser.showDialog(null, "Select the background color",
            renk);
    Container a = this.getContentPane();
    a.setBackground(renk);
}

I'm using netbeans ide. For me, JFrame.getContentPane() didn't run. I used JFrame.getContentPane()'s class equivalent this.getContentPane.

Segmentation fault on large array sizes

You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.

If you allocate the array on the heap you should be fine, assuming your machine has enough memory.

int* array = new int[1000000];

But remember that this will require you to delete[] the array. A better solution would be to use std::vector<int> and resize it to 1000000 elements.

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

Set the space between Elements in Row Flutter

Removing Space-:

new Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              GestureDetector(
                child: new Text('Don\'t have an account?',
                    style: new TextStyle(color: Color(0xFF2E3233))),
                onTap: () {},
              ),
              GestureDetector(
                onTap: (){},
                  child: new Text(
                'Register.',
                style: new TextStyle(
                    color: Color(0xFF84A2AF), fontWeight: FontWeight.bold),
              ))
            ],
          ),

OR

GestureDetector(
            onTap: (){},
            child: new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Text('Don\'t have an account?',
                    style: new TextStyle(color: Color(0xFF2E3233))),
                new Text(
                  'Register.',
                  style: new TextStyle(
                  color: Color(0xFF84A2AF), fontWeight: FontWeight.bold),
                )
              ],
            ),
          ),

How can I modify the size of column in a MySQL table?

Have you tried this?

ALTER TABLE <table_name> MODIFY <col_name> VARCHAR(65353);

This will change the col_name's type to VARCHAR(65353)

How to increase dbms_output buffer?

You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.

dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);

Check this

EDIT

As per the comment posted by Frank and Mat, you can also enable it with Null

exec dbms_output.enable(NULL);

buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).

SQL Error: ORA-12899: value too large for column

This answer still comes up high in the list for ORA-12899 and lot of non helpful comments above, even if they are old. The most helpful comment was #4 for any professional trying to find out why they are getting this when loading data.

Some characters are more than 1 byte in length, especially true on SQL Server. And what might fit in a varchar(20) in SQLServer won't fit into a similar varchar2(20) in Oracle.

I ran across this error yesterday with SSIS loading an Oracle database with the Attunity drivers and thought I would save folks some time.

ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted

I was having the same problem and could not figure out what I was doing wrong. Turns out, the auto-complete for Android Studio was changing the text to either all caps or all lower case (depending on whether I typed in upper case or lower cast words before the auto-complete). The OS was not registering the name due to this issue and I would get the error regarding a missing permission. As stated above, ensure your permissions are labeled correctly:

Correct:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Incorrect:

<uses-permission android:name="ANDROID.PERMISSION.ACCESS_FINE_LOCATION" />

Incorrect:

<uses-permission android:name="android.permission.access_fine_location" />

Though this may seem trivial, its easy to overlook.

If there is some setting to make permissions non-case-sensitive, please add a comment with the instructions. Thank you!

How does one convert a HashMap to a List in Java?

If you only want it to iterate over your HashMap, no need for a list:

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values()) {
    System.out.println(s);
}

Of course, if you want to modify your map structurally (i.e. more than only changing the value for an existing key) while iterating, then you better use the "copy to ArrayList" method, since otherwise you'll get a ConcurrentModificationException. Or export as an array:

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values().toArray(new String[]{})) {
    System.out.println(s);
}

How do I change UIView Size?

Swift 3 and Swift 4:

myView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)

Vue component event after render

updated() should be what you're looking for:

Called after a data change causes the virtual DOM to be re-rendered and patched.

The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.

Python MySQLdb TypeError: not all arguments converted during string formatting

'%' keyword is so dangerous because it major cause of 'SQL INJECTION ATTACK'.
So you just using this code.

cursor.execute("select * from table where example=%s", (example,))

or

t = (example,)
cursor.execute("select * from table where example=%s", t)

if you want to try insert into table, try this.

name = 'ksg'
age = 19
sex = 'male'
t  = (name, age, sex)
cursor.execute("insert into table values(%s,%d,%s)", t)

Is there a "standard" format for command line/shell help text?

Typically, your help output should include:

  • Description of what the app does
  • Usage syntax, which:
    • Uses [options] to indicate where the options go
    • arg_name for a required, singular arg
    • [arg_name] for an optional, singular arg
    • arg_name... for a required arg of which there can be many (this is rare)
    • [arg_name...] for an arg for which any number can be supplied
    • note that arg_name should be a descriptive, short name, in lower, snake case
  • A nicely-formatted list of options, each:
    • having a short description
    • showing the default value, if there is one
    • showing the possible values, if that applies
    • Note that if an option can accept a short form (e.g. -l) or a long form (e.g. --list), include them together on the same line, as their descriptions will be the same
  • Brief indicator of the location of config files or environment variables that might be the source of command line arguments, e.g. GREP_OPTS
  • If there is a man page, indicate as such, otherwise, a brief indicator of where more detailed help can be found

Note further that it's good form to accept both -h and --help to trigger this message and that you should show this message if the user messes up the command-line syntax, e.g. omits a required argument.

Timeout for python requests.get entire response

Despite the question being about requests, I find this very easy to do with pycurl CURLOPT_TIMEOUT or CURLOPT_TIMEOUT_MS.

No threading or signaling required:

import pycurl
import StringIO

url = 'http://www.example.com/example.zip'
timeout_ms = 1000
raw = StringIO.StringIO()
c = pycurl.Curl()
c.setopt(pycurl.TIMEOUT_MS, timeout_ms)  # total timeout in milliseconds
c.setopt(pycurl.WRITEFUNCTION, raw.write)
c.setopt(pycurl.NOSIGNAL, 1)
c.setopt(pycurl.URL, url)
c.setopt(pycurl.HTTPGET, 1)
try:
    c.perform()
except pycurl.error:
    traceback.print_exc() # error generated on timeout
    pass # or just pass if you don't want to print the error

How to combine multiple inline style objects?

Actually, there is a formal way to combine and it is like below:

<View style={[style01, style02]} />

But, there is a small issue, if one of them is passed by the parent component and it was created by a combined formal way we have a big problem:

// The passing style02 from props: [parentStyle01, parentStyle02]

// Now:
<View style={[style01, [parentStyle01, parentStyle02]]} />

And this last line causes to have UI bug, surly, React Native cannot deal with a deep array inside an array. So I create my helper function:

import { StyleSheet } from 'react-native';

const styleJoiner = (...arg) => StyleSheet.flatten(arg);

By using my styleJoiner anywhere you can combine any type of style and combine styles. even undefined or other useless types don't cause to break the styling.

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

Open up Windows' System Properties from the control panel and hunt down the environment variables section:

  • Add a JAVA_HOME entry pointing to the directory where the JDK is installed (e.g. C:\Program Files\Java\jre6)
  • Find the Path entry and add the following onto the end ;%JAVA_HOME%\bin
  • OK the changes
  • Restart eclipse so that it is aware of the new environment

Most Java tools will now be able to find your Java installation either by using the JAVA_HOME environment variable or by looking for java.exe / javaw.exe in the Path environment variable.

Select current date by default in ASP.Net Calendar control

Actually, I cannot get selected date in aspx. Here is the way to set selected date in codes:

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
      DateTime dt = DateTime.Now.AddDays(-1);
      Calendar1.VisibleDate = dt;
      Calendar1.SelectedDate = dt;
      Calendar1.TodaysDate = dt;
      ...
    }
 }

In above example, I need to set the default selected date to yesterday. The key point is to set TodayDate. Otherwise, the selected calendar date is always today.

React prevent event bubbling in nested components on click

This is not 100% ideal, but if it is either too much of a pain to pass down props in children -> children fashion or create a Context.Provider/Context.Consumer just for this purpose), and you are dealing with another library which has it's own handler it runs before yours, you can also try:

   function myHandler(e) { 
        e.persist(); 
        e.nativeEvent.stopImmediatePropagation();
        e.stopPropagation(); 
   }

From what I understand, the event.persist method prevents an object from immediately being thrown back into React's SyntheticEvent pool. So because of that, the event passed in React actually doesn't exist by the time you reach for it! This happens in grandchildren because of the way React handle's things internally by first checking parent on down for SyntheticEvent handlers (especially if the parent had a callback).

As long as you are not calling persist on something which would create significant memory to keep creating events such as onMouseMove (and you are not creating some kind of Cookie Clicker game like Grandma's Cookies), it should be perfectly fine!

Also note: from reading around their GitHub occasionally, we should keep our eyes out for future versions of React as they may eventually resolve some of the pain with this as they seem to be going towards making folding React code in a compiler/transpiler.

JavaScript to get rows count of a HTML table

This is another option, using jQuery and getting only tbody rows (with the data) and desconsidering thead/tfoot.

$("#tableId > tbody > tr").length

_x000D_
_x000D_
console.log($("#myTableId > tbody > tr").length);
_x000D_
.demo {
   width:100%;
   height:100%;
   border:1px solid #C0C0C0;
   border-collapse:collapse;
   border-spacing:2px;
   padding:5px;
}

.demo caption {
   caption-side:top;
   text-align:center;
}

.demo th {
   border:1px solid #C0C0C0;
   padding:5px;
   background:#F0F0F0;
}

.demo td {
   border:1px solid #C0C0C0;
   text-align:left;
   padding:5px;
   background:#FFFFFF;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTableId" class="demo">
   <caption>Table 1</caption>
   <thead>
      <tr>
         <th>Header 1</th>
         <th>Header 2</th>
         <th>Header 3</th>
         <th>Header 4</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
   </tbody>
   <tfoot>
      <tr>
         <td colspan=4 style="background:#F0F0F0">&nbsp; </td>
      </tr>
   </tfoot>
</table>
_x000D_
_x000D_
_x000D_

How to install easy_install in Python 2.7.1 on Windows 7

That tool is part of the setuptools (now called Distribute) package. Install Distribute. Of course you'll have to fetch that one manually.

http://pypi.python.org/pypi/distribute#installation-instructions

How to kill all processes with a given partial name?

Sounds bad?

 pkill `pidof myprocess`

example:

# kill all java processes
pkill `pidof java`

MySQL Workbench: "Can't connect to MySQL server on 127.0.0.1' (10061)" error

To connect to a new server, you click on home + add new connection. Put IP or webserver URL in new connection.

how to create

Trim to remove white space

or just use $.trim(str)

socket.emit() vs. socket.send()

With socket.emit you can register custom event like that:

server:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

client:

var socket = io.connect('http://localhost');
socket.on('news', function (data) {
  console.log(data);
  socket.emit('my other event', { my: 'data' });
});

Socket.send does the same, but you don't register to 'news' but to message:

server:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.send('hi');
});

client:

var socket = io.connect('http://localhost');
socket.on('message', function (message) {
  console.log(message);
});

Passing command line arguments from Maven as properties in pom.xml

You can give variable names as project files. For instance in you plugin configuration give only one tag as below:-

<projectFile>${projectName}</projectFile>

Then on command line you can pass the project name as parameter:-

mvn [your-command] -DprojectName=[name of project]

Java: how to represent graphs?

Adjacency List implementation of Graph is appropriate for solving most of the graph related problems.

Java implementation of the same is here on my blog.

Fastest way to check if a string matches a regexp in ruby?

This is a simple benchmark:

require 'benchmark'

"test123" =~ /1/
=> 4
Benchmark.measure{ 1000000.times { "test123" =~ /1/ } }
=>   0.610000   0.000000   0.610000 (  0.578133)

"test123"[/1/]
=> "1"
Benchmark.measure{ 1000000.times { "test123"[/1/] } }
=>   0.718000   0.000000   0.718000 (  0.750010)

irb(main):019:0> "test123".match(/1/)
=> #<MatchData "1">
Benchmark.measure{ 1000000.times { "test123".match(/1/) } }
=>   1.703000   0.000000   1.703000 (  1.578146)

So =~ is faster but it depends what you want to have as a returned value. If you just want to check if the text contains a regex or not use =~

Adding days to $Date in PHP

Here has an easy way to solve this.

<?php
   $date = "2015-11-17";
   echo date('Y-m-d', strtotime($date. ' + 5 days'));
?>

Output will be:

2015-11-22

Solution has found from here - How to Add Days to Date in PHP

ImportError: No module named psycopg2

Recently faced this issue on my production server. I had installed pyscopg2 using

sudo pip install psycopg2

It worked beautifully on my local, but had me for a run on my ec2 server.

sudo python -m pip install psycopg2

The above command worked for me there. Posting here just in case it would help someone in future.

add commas to a number in jQuery

    function delimitNumbers(str) {
      return (str + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
        return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, "$1,") : b) + c;
      });
    }

    alert(delimitNumbers(1234567890));

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

I had the same issue, and the solution is very simple, just change to git bash from cmd or other windows command line tools. Windows sometimes does not work well with git npm dependencies.

Global Variable from a different file Python

After searching, I got this clue: https://instructobit.com/tutorial/108/How-to-share-global-variables-between-files-in-Python

the key is: turn on the function to call the variabel that set to global if a function activated.

then import the variabel again from that file.

i give you the hard example so you can understood:

file chromy.py

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def opennormal():
    global driver
    options = Options()
    driver = webdriver.Chrome(chrome_options=options)

def gotourl(str):
    url = str
    driver.get(url)

file tester.py

from chromy import * #this command call all function in chromy.py, but the 'driver' variable in opennormal function is not exists yet. run: dir() to check what you call.

opennormal() #this command activate the driver variable to global, but remember, at the first import you not import it

#then do this, this is the key to solve:
from chromy import driver #run dir() to check what you call and compare with the first dir() result.

#because you already re-import the global that you need, you can use it now

url = 'https://www.google.com'
gotourl(url)

That's the way you call the global variable that you set in a function. cheers don't forget to give credit

PHP Array to CSV

Arrays of data are converted into csv 'text/csv' format by built in php function fputcsv takes care of commas, quotes and etc..
Look at
https://coderwall.com/p/zvzwwa/array-to-comma-separated-string-in-php
http://www.php.net/manual/en/function.fputcsv.php

How do I find out what type each object is in a ArrayList<Object>?

You can use the getClass() method, or you can use instanceof. For example

for (Object obj : list) {
  if (obj instanceof String) {
   ...
  }
}

or

for (Object obj : list) {
 if (obj.getClass().equals(String.class)) {
   ...
 }
}

Note that instanceof will match subclasses. For instance, of C is a subclass of A, then the following will be true:

C c = new C();
assert c instanceof A;

However, the following will be false:

C c = new C();
assert !c.getClass().equals(A.class)

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

The first answer with best rating is wrong. If value is undefined it will throw an exception in modern browsers. You have to use:

if (typeof(value) !== "undefined" && value)

or

if (typeof value  !== "undefined" && value)

A non well formed numeric value encountered

This is an old question, but there is another subtle way this message can happen. It's explained pretty well here, in the docs.

Imagine this scenerio:

try {
  // code that triggers a pdo exception
} catch (Exception $e) {
  throw new MyCustomExceptionHandler($e);
}

And MyCustomExceptionHandler is defined roughly like:

class MyCustomExceptionHandler extends Exception {
  public function __construct($e) {
    parent::__construct($e->getMessage(), $e->getCode());
  }
}

This will actually trigger a new exception in the custom exception handler because the Exception class is expecting a number for the second parameter in its constructor, but PDOException might have dynamically changed the return type of $e->getCode() to a string.

A workaround for this would be to define you custom exception handler like:

class MyCustomExceptionHandler extends Exception {
  public function __construct($e) {
    parent::__construct($e->getMessage());
    $this->code = $e->getCode();
  }
}

BACKUP LOG cannot be performed because there is no current database backup

In our case it was due to the Recovery Model on the primary database having been changed after we did the backup in preparation for setting up log shipping.

Ensuring the Recovery Model was set to Full Recovery before doing the backup and setting up log shipping resolved it for us.

What is the difference between sscanf or atoi to convert a string to an integer?

When there is no concern about invalid string input or range issues, use the simplest: atoi()

Otherwise, the method with best error/range detection is neither atoi(), nor sscanf(). This good answer all ready details the lack of error checking with atoi() and some error checking with sscanf().

strtol() is the most stringent function in converting a string to int. Yet it is only a start. Below are detailed examples to show proper usage and so the reason for this answer after the accepted one.

// Over-simplified use
int strtoi(const char *nptr) {
  int i = (int) strtol(nptr, (char **)NULL, 10);
  return i; 
}

This is the like atoi() and neglects to use the error detection features of strtol().

To fully use strtol(), there are various features to consider:

  1. Detection of no conversion: Examples: "xyz", or "" or "--0"? In these cases, endptr will match nptr.

    char *endptr;
    int i = (int)strtol(nptr, &endptr, 10);
    if (nptr == endptr) return FAIL_NO_CONVERT;
    
  2. Should the whole string convert or just the leading portion: Is "123xyz" OK?

    char *endptr;
    int i = (int)strtol(nptr, &endptr, 10);
    if (*endptr != '\0') return FAIL_EXTRA_JUNK;
    
  3. Detect if value was so big, the the result is not representable as a long like "999999999999999999999999999999".

    errno = 0;
    long L = strtol(nptr, &endptr, 10);
    if (errno == ERANGE) return FAIL_OVERFLOW;
    
  4. Detect if the value was outside the range of than int, but not long. If int and long have the same range, this test is not needed.

    long L = strtol(nptr, &endptr, 10);
    if (L < INT_MIN || L > INT_MAX) return FAIL_INT_OVERFLOW;
    
  5. Some implementations go beyond the C standard and set errno for additional reasons such as errno to EINVAL in case no conversion was performed or EINVAL The value of the Base parameter is not valid.. The best time to test for these errno values is implementation dependent.

Putting this all together: (Adjust to your needs)

#include <errno.h>
#include <stdlib.h>

int strtoi(const char *nptr, int *error_code) {
  char *endptr;
  errno = 0;
  long i = strtol(nptr, &endptr, 10);

  #if LONG_MIN < INT_MIN || LONG_MAX > INT_MAX
  if (errno == ERANGE || i > INT_MAX || i < INT_MIN) {
    errno = ERANGE;
    i = i > 0 : INT_MAX : INT_MIN;
    *error_code = FAIL_INT_OVERFLOW;
  }
  #else
  if (errno == ERANGE) {
    *error_code = FAIL_OVERFLOW;
  }
  #endif

  else if (endptr == nptr) {
    *error_code = FAIL_NO_CONVERT;
  } else if (*endptr != '\0') {
    *error_code = FAIL_EXTRA_JUNK;
  } else if (errno) {
    *error_code = FAIL_IMPLEMENTATION_REASON;
  }
  return (int) i;
}

Note: All functions mentioned allow leading spaces, an optional leading sign character and are affected by locale change. Additional code is required for a more restrictive conversion.


Note: Non-OP title change skewed emphasis. This answer applies better to original title "convert string to integer sscanf or atoi"

Error using eclipse for Android - No resource found that matches the given name

I had the same issue and tried most of the solutions mentioned above and they did not fix it.. At then end, I went to my .csproj file and viewed it in the text editor, I found that my xml file that I put in the /Drawable was not set to be AndroidResouces it was just of type Content.

Changing that to be of type AndroidResouces fixed the issue for me.

'import' and 'export' may only appear at the top level

I am using Webpack 2.2.0 to bundle my React JS modules.

Encountered a similar issue while importing modules in my main app.js file.

After 30 minutes of headbanging I updated the RegEx for testing the file types in my webpack.config.js.

Carefully notice the ? symbol in test RegEx query.

{
    test: /\.js?$/,
    exclude: /(node_modules)/,
    loader: 'react-hot-loader'
}

It worked for me !!

How to connect Bitbucket to Jenkins properly

By iterating I learned that the Token field and the token in an endpoint can be the same. So I set them to be the same as the user token and it works! Also check that the user has privileges to make a job.

Anyway, you can check access.log and see if Bitbucket makes a try or not.

jenkins

P.S. Also a link to Bitbucket Documentation. May some day it will become more useful.

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

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

What are some good Python ORM solutions?

There is no conceivable way that the unused features in Django will give a performance penalty. Might just come in handy if you ever decide to upscale the project.

Change User Agent in UIWebView

The only problem I have found was change user agent only

- (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSDictionary *dictionary = [NSDictionary 
        dictionaryWithObjectsAndKeys:
        @"Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; ja-jp) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5", 
        @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}

Spring MVC UTF-8 Encoding

Make sure you register Spring's CharacterEncodingFilter in your web.xml (must be the first filter in that file).

<filter>  
    <filter-name>encodingFilter</filter-name>  
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
    <init-param>  
       <param-name>encoding</param-name>  
       <param-value>UTF-8</param-value>  
    </init-param>  
    <init-param>  
       <param-name>forceEncoding</param-name>  
       <param-value>true</param-value>  
    </init-param>  
</filter>  
<filter-mapping>  
    <filter-name>encodingFilter</filter-name>  
    <url-pattern>/*</url-pattern>  
</filter-mapping> 

If you are on Tomcat you might not have set the URIEncoding in your server.xml. If you don't set it to UTF-8 it won't work. Definitely keep the CharacterEncodingFilter. Nevertheless, here's a concise checklist to follow. It will definitely guide you to make this work.

How do I find which transaction is causing a "Waiting for table metadata lock" state?

I had a similar issue with Datagrip and none of these solutions worked.

Once I restarted the Datagrip Client it was no longer an issue and I could drop tables again.

What is the use of "object sender" and "EventArgs e" parameters?

EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.

Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.

Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx

Example:

protected void btn_Click (object sender, EventArgs e){
   Button btn = sender as Button;
   btn.Text = "clicked!";
}

Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked

How to use a Java8 lambda to sort a stream in reverse order?

You can adapt the solution you linked in How to sort ArrayList<Long> in Java in decreasing order? by wrapping it in a lambda:

.sorted((f1, f2) -> Long.compare(f2.lastModified(), f1.lastModified())

note that f2 is the first argument of Long.compare, not the second, so the result will be reversed.

How to install Android SDK on Ubuntu?

To install it on a Debian based system simply do

# Install latest JDK
sudo apt install default-jdk

# install unzip if not installed yet
sudo apt install unzip

# get latest sdk tools - link will change. go to https://developer.android.com/studio/#downloads to get the latest one
cd ~
wget https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip

# unpack archive
unzip sdk-tools-linux-4333796.zip

rm sdk-tools-linux-4333796.zip

mkdir android-sdk
mv tools android-sdk/tools

Then add the Android SDK to your PATH, open ~/.bashrc in editor and add the following lines into the file

# Export the Android SDK path 
export ANDROID_HOME=$HOME/android-sdk
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools

# Fixes sdkmanager error with java versions higher than java 8
export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'

Run

source ~/.bashrc

Show all available sdk packages

sdkmanager --list

Identify latest android platform (here it's 28) and run

sdkmanager "platform-tools" "platforms;android-28"

Now you have adb, fastboot and the latest sdk tools installed

How to quit android application programmatically

First of all, this approach requires min Api 16.

I will divide this solution to 3 parts to solve this problem more widely.

1. If you want to quit application in an Activity use this code snippet:

if(Build.VERSION.SDK_INT>=16 && Build.VERSION.SDK_INT<21){
    finishAffinity();
} else if(Build.VERSION.SDK_INT>=21){
    finishAndRemoveTask();
}

2. If you want to quit the application in a non Activity class which has access to Activity then use this code snippet:

if(Build.VERSION.SDK_INT>=16 && Build.VERSION.SDK_INT<21){
    getActivity().finishAffinity();
} else if(Build.VERSION.SDK_INT>=21){
    getActivity().finishAndRemoveTask();
}

3. If you want to quit the application in a non Activity class and cannot access to Activity such as Service I recommend you to use BroadcastReceiver. You can add this approach to all of your Activities in your project.

Create LocalBroadcastManager and BroadcastReceiver instance variables. You can replace getPackageName()+".closeapp" if you want to.

LocalBroadcastManager mLocalBroadcastManager;
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(getPackageName()+".closeapp")){
            if(Build.VERSION.SDK_INT>=16 && Build.VERSION.SDK_INT<21){
                finishAffinity();
            } else if(Build.VERSION.SDK_INT>=21){
                finishAndRemoveTask();
            }
        }
    }
};

Add these to onCreate() method of Activity.

mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(getPackageName()+".closeapp");
mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, mIntentFilter);

Also, don't forget to call unregister receiver at onDestroy() method of Activity

mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);

For quit application, you must send broadcast using LocalBroadcastManager which I use in my PlayService class which extends Service.

LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(PlayService.this);
localBroadcastManager.sendBroadcast(new Intent(getPackageName() + ".closeapp"));

ALTER TABLE add constraint

Omit the parenthesis:

ALTER TABLE User 
    ADD CONSTRAINT userProperties
    FOREIGN KEY(properties)
    REFERENCES Properties(ID)

Which .NET Dependency Injection frameworks are worth looking into?

I think a good place to start is with Ninject, it is new and has taken into account alot of fine tuning and is really fast. Nate, the developer, really has a great site and great support.

Updating user data - ASP.NET Identity

I have tried the functionality in the same way and when i call UserManager.Updateasync method it succeeds but there is no update in the database. After spending some time i found another solution to update the data in aspnetusers table which is following:

1) you need to create UserDbContext class inheriting from IdentityDbContext class like this:

public class UserDbContext:IdentityDbContext<UserInfo>
{
    public UserDbContext():
        base("DefaultConnection")
    {
        this.Configuration.ProxyCreationEnabled = false;
    }
}

2) then in Account controller update user information like this:

UserDbContext userDbContext = new UserDbContext();
userDbContext.Entry(user).State = System.Data.Entity.EntityState.Modified;
await userDbContext.SaveChangesAsync();

where user is your updated entity.

hope this will help you.

How do I share variables between different .c files?

  1. Try to avoid globals. If you must use a global, see the other answers.
  2. Pass it as an argument to a function.

how to set JAVA_OPTS for Tomcat in Windows?

I like a combination of Gaurav's and user2550946's answer best, but would like to add two more aspects:

  1. Don't use JAVA_OPTS, instead use CATALINA_OPTS. This will be used solely for starting tomcat, not for shutting it down. Typically you want more memory when starting tomcat, but the shutdown process (which just spins up, tells tomcat to shut down and then ends again) doesn't need any specifically tuned resources. In fact, shutdown can even fail if some ridiculous amount of memory is not available from the OS anymore.

  2. On production systems, my recommentation is to claim the maximum allowed memory immediately. Because if you anticipate that the memory will be required sooner or later, you don't want to discover it not being available at 3am in the night - rather when you start up the server. Thus, set -Xmx and -Xms to the same value in production systems. (This makes my aspect 1 even more relevant)

Or, in one line, here's my recommendation:

set "CATALINA_OPTS=%CATALINA_OPTS% -Xms1024M -Xmx1024M"

What is the difference between encode/decode?

mybytestring.encode(somecodec) is meaningful for these values of somecodec:

  • base64
  • bz2
  • zlib
  • hex
  • quopri
  • rot13
  • string_escape
  • uu

I am not sure what decoding an already decoded unicode text is good for. Trying that with any encoding seems to always try to encode with the system's default encoding first.

Gradle store on local file system

For my case, I was using an Ivy repository, and my Gradle dependencies were stored in ~/.ivy2/.

Markdown and including multiple files

I use a includes.txt file with all my files in the right order the I execute pandoc like this:

pandoc -s $(cat includes.txt) --quiet -f markdown -t html5 --css pandoc.css -o index.html

Works like a charm!

What is the best way to add options to a select from a JavaScript object with jQuery?

That's what I did with two-dimensional arrays: The first column is item i, add to innerHTML of the <option>. The second column is record_id i, add to the value of the <option>:

  1. PHP

    $items = $dal->get_new_items(); // Gets data from the database
    $items_arr = array();
    $i = 0;
    foreach ($items as $item)
    {
        $first_name = $item->first_name;
        $last_name = $item->last_name;
        $date = $item->date;
        $show = $first_name . " " . $last_name . ", " . $date;
        $request_id = $request->request_id;
        $items_arr[0][$i] = $show;
        $items_arr[1][$i] = $request_id;
        $i++;
    }
    
    echo json_encode($items_arr);
    
  2. JavaScript/Ajax

            function ddl_items() {
                if (window.XMLHttpRequest) {
                    // Code for Internet Explorer 7+, Firefox, Chrome, Opera, and Safari
                    xmlhttp=new XMLHttpRequest();
                }
                else{
                    // Code for Internet Explorer 6 and Internet Explorer 5
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
    
                xmlhttp.onreadystatechange=function() {
                if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                    var arr = JSON.parse(xmlhttp.responseText);
                    var lstbx = document.getElementById('my_listbox');
    
                    for (var i=0; i<arr.length; i++) {
                        var option = new Option(arr[0][i], arr[1][i]);
                        lstbx.options.add(option);
                    }
                }
            };
    
            xmlhttp.open("GET", "Code/get_items.php?dummy_time=" + new Date().getTime() + "", true);
            xmlhttp.send();
        }
    }
    

How can I change the default Django date template format?

If you need to show short date and time (11/08/2018 03:23 a.m.) you can do it like this:

{{your_date_field|date:"SHORT_DATE_FORMAT"}} {{your_date_field|time:"h:i a"}}

Details for this tag here and more about dates according to the given format here

Example:

<small class="text-muted">Last updated: {{your_date_field|date:"SHORT_DATE_FORMAT"}} {{your_date_field|time:"h:i a"}}</small>

Adding a column after another column within SQL

It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:

ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;

jQuery datepicker, onSelect won't work

The function datepicker is case sensitive and all lowercase. The following however works fine for me:

$(document).ready(function() {
  $('.date-pick').datepicker( {
    onSelect: function(date) {
        alert(date);
    },
    selectWeek: true,
    inline: true,
    startDate: '01/01/2000',
    firstDay: 1
  });
});

How to convert Java String to JSON Object

The string that you pass to the constructor JSONObject has to be escaped with quote():

public static java.lang.String quote(java.lang.String string)

Your code would now be:

JSONObject jsonObj = new JSONObject.quote(jsonString.toString());
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);

AttributeError: 'datetime' module has no attribute 'strptime'

If I had to guess, you did this:

import datetime

at the top of your code. This means that you have to do this:

datetime.datetime.strptime(date, "%Y-%m-%d")

to access the strptime method. Or, you could change the import statement to this:

from datetime import datetime

and access it as you are.

The people who made the datetime module also named their class datetime:

#module  class    method
datetime.datetime.strptime(date, "%Y-%m-%d")

What is web.xml file and what are all things can I do with it?

Deployment descriptor file "web.xml" : Through the proper use of the deployment descriptor file, web.xml, you can control many aspects of the Web application behavior, from preloading servlets, to restricting resource access, to controlling session time-outs.

web.xml : is used to control many facets of a Web application. Using web.xml, you can assign custom URLs for invoking servlets, specify initialization parameters for the entire application as well as for specific servlets, control session timeouts, declare filters, declare security roles, restrict access to Web resources based on declared security roles, and so on.

GSON - Date format

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create();

Above format seems better to me as it has precision up to millis.

Calling remove in foreach loop in Java

I didn't know about iterators, however here's what I was doing until today to remove elements from a list inside a loop:

List<String> names = .... 
for (i=names.size()-1;i>=0;i--) {    
    // Do something    
    names.remove(i);
} 

This is always working, and could be used in other languages or structs not supporting iterators.

Get only part of an Array in Java?

You could wrap your array as a list, and request a sublist of it.

MyClass[] array = ...;
List<MyClass> subArray = Arrays.asList(array).subList(index, array.length);

Get DOM content of cross-domain iframe

If you have an access to that domain/iframe that is loaded, then you can use window.postMessage to communicate between iframe and the main window.

Read the DOM with JavaScript in iframe and send it via postMessage to the top window.

More info here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

What does `void 0` mean?

What does void 0 mean?

void[MDN] is a prefix keyword that takes one argument and always returns undefined.

Examples

void 0
void (0)
void "hello"
void (new Date())
//all will return undefined

What's the point of that?

It seems pretty useless, doesn't it? If it always returns undefined, what's wrong with just using undefined itself?

In a perfect world we would be able to safely just use undefined: it's much simpler and easier to understand than void 0. But in case you've never noticed before, this isn't a perfect world, especially when it comes to Javascript.

The problem with using undefined was that undefined is not a reserved word (it is actually a property of the global object [wtfjs]). That is, undefined is a permissible variable name, so you could assign a new value to it at your own caprice.

alert(undefined); //alerts "undefined"
var undefined = "new value";
alert(undefined) // alerts "new value"

Note: This is no longer a problem in any environment that supports ECMAScript 5 or newer (i.e. in practice everywhere but IE 8), which defines the undefined property of the global object as read-only (so it is only possible to shadow the variable in your own local scope). However, this information is still useful for backwards-compatibility purposes.

alert(window.hasOwnProperty('undefined')); // alerts "true"
alert(window.undefined); // alerts "undefined"
alert(undefined === window.undefined); // alerts "true"
var undefined = "new value";
alert(undefined); // alerts "new value"
alert(undefined === window.undefined); // alerts "false"

void, on the other hand, cannot be overidden. void 0 will always return undefined. undefined, on the other hand, can be whatever Mr. Javascript decides he wants it to be.

Why void 0, specifically?

Why should we use void 0? What's so special about 0? Couldn't we just as easily use 1, or 42, or 1000000 or "Hello, world!"?

And the answer is, yes, we could, and it would work just as well. The only benefit of passing in 0 instead of some other argument is that 0 is short and idiomatic.

Why is this still relevant?

Although undefined can generally be trusted in modern JavaScript environments, there is one trivial advantage of void 0: it's shorter. The difference is not enough to worry about when writing code but it can add up enough over large code bases that most code minifiers replace undefined with void 0 to reduce the number of bytes sent to the browser.

How to check if all elements of a list matches a condition?

If you want to check if any item in the list violates a condition use all:

if all([x[2] == 0 for x in lista]):
    # Will run if all elements in the list has x[2] = 0 (use not to invert if necessary)

To remove all elements not matching, use filter

# Will remove all elements where x[2] is 0
listb = filter(lambda x: x[2] != 0, listb)

difference between throw and throw new Exception()

throw is for rethrowing a caught exception. This can be useful if you want to do something with the exception before passing it up the call chain.

Using throw without any arguments preserves the call stack for debugging purposes.

PHP Get Highest Value from Array

Find highest number, including negative:

return max([abs(max($array)),abs(min($array))]);

What are file descriptors, explained in simple terms?

Hear it from the Horse's Mouth : APUE (Richard Stevens).
To the kernel, all open files are referred to by File Descriptors. A file descriptor is a non-negative number.

When we open an existing file or create a new file, the kernel returns a file descriptor to the process. The kernel maintains a table of all open file descriptors, which are in use. The allotment of file descriptors is generally sequential and they are allotted to the file as the next free file descriptor from the pool of free file descriptors. When we closes the file, the file descriptor gets freed and is available for further allotment.
See this image for more details :

Two Process

When we want to read or write a file, we identify the file with the file descriptor that was returned by open() or create() function call, and use it as an argument to either read() or write().
It is by convention that, UNIX System shells associates the file descriptor 0 with Standard Input of a process, file descriptor 1 with Standard Output, and file descriptor 2 with Standard Error.
File descriptor ranges from 0 to OPEN_MAX. File descriptor max value can be obtained with ulimit -n. For more information, go through 3rd chapter of APUE Book.

Resetting remote to a certain commit

Sourcetree: resetting remote to a certain commit

  1. If you have pushed a bad commit to your remote (origin/feature/1337_MyAwesomeFeature) like below picture

Go to Remotes

  1. Go to Remotes > origin > feature > 1337_MyAwesomeFeature
  2. Right click and choose "Delete origin/feature/1337_MyAwesomeFeature" (Or change name of it if you want a backup and skip step 4.)
  3. Click "Force delete" and "OK".

enter image description here enter image description here

  1. Select your older commit and choose "Reset current branch to this commit"
  2. Choose which mode you want to have (Hard if you don't want your last changes) and "OK".

enter image description here enter image description here

  1. Push this commit to a new origin/feature/1337_MyAwesomeFeature enter image description here

  2. Your local feature branch and your remote feature branch are now on the previous (of your choice) commit enter image description here

Change image source with JavaScript

The problem was that you were using .src without needing it and you also needed to differentiate which img you wanted to change.

function changeImage(a, imgid) {
    document.getElementById(imgid).src=a;
}
<div id="main_img">
    <img id="img" src="1772031_29_b.jpg">
</div>
<div id="thumb_img">
    <img id="1" src='1772031_29_t.jpg'  onclick='changeImage("1772031_29_b.jpg", "1");'>
    <img id="2" src='1772031_55_t.jpg'  onclick='changeImage("1772031_55_b.jpg", "2");'>
    <img id="3" src='1772031_53_t.jpg'  onclick='changeImage("1772031_53_b.jpg", "3");'>
</div>

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Converting a date in MySQL from string field

STR_TO_DATE allows you to do this, and it has a format argument.

How to solve error: "Clock skew detected"?

One of the reason may be improper date/time of your PC.

In Ubuntu PC to check the date and time using:

date

Example, One of the ways to update date and time is:

date -s "23 MAR 2017 17:06:00"

Make an Android button change background on click through XML

To change image by using code

public void onClick(View v) {
   if(v == ButtonName) {
     ButtonName.setImageResource(R.drawable.ImageName);
   }
}

Or, using an XML file:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true"
   android:drawable="@drawable/login_selected" /> <!-- pressed -->
  <item android:state_focused="true"
   android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
  <item android:drawable="@drawable/login" /> <!-- default -->
</selector>

In OnClick, just add this code:

ButtonName.setBackgroundDrawable(getResources().getDrawable(R.drawable.ImageName));

Fixing slow initial load for IIS

I was getting a consistent 15 second delay on the first request after 4 minutes of inactivity. My problem was that my app was using Windows Integrated Authentication to SQL Server and the service profile was in a different domain than the server. This caused a cross-domain authentication from IIS to SQL upon app initialization - and this was the real source of my delay. I changed to using a SQL login instead of windows authentication. The delay was immediately gone. I still have all the app initialization settings in place to help improve performance but they may have not been needed at all in my case.

Recursively find all files newer than a given time

You can also do this without a marker file.

The %s format to date is seconds since the epoch. find's -mmin flag takes an argument in minutes, so divide the difference in seconds by 60. And the "-" in front of age means find files whose last modification is less than age.

time=1312603983
now=$(date +'%s')
((age = (now - time) / 60))
find . -type f -mmin -$age

With newer versions of gnu find you can use -newermt, which makes it trivial.

Include of non-modular header inside framework module

I had the same issue and nothing from above helped me. So I hope my answer will be helpful for somebody. In my case the problem was in ALWAYS_SEARCH_USER_PATHS setting. When it was set to NO project built and worked ok. But as far as one of the pod required it to be set to YES I was receiving an error

Include of non-modular header inside framework module

After couple cups of coffee and all day researching I found out that according to known issues of Xcode 7.1 Beta 2 release notes:

• If you get an error stating "Include of non-modular header inside framework module" for a framework that previously compiled, make sure the "Always Search User Paths" build setting is set to "No". The default is "Yes" only for legacy reasons. (22784786)

I was using XCode 7.3 though, but seems like this bug hasn't been fixed yet.

Setting href attribute at runtime

Small performance test comparision for three solutions:

  1. $(".link").prop('href',"https://example.com")
  2. $(".link").attr('href',"https://example.com")
  3. document.querySelector(".link").href="https://example.com";

enter image description here

Here you can perform test by yourself https://jsperf.com/a-href-js-change


We can read href values in following ways

  1. let href = $(selector).prop('href');
  2. let href = $(selector).attr('href');
  3. let href = document.querySelector(".link").href;

enter image description here

Here you can perform test by yourself https://jsperf.com/a-href-js-read

How to auto adjust the div size for all mobile / tablet display formats?

You can use the viewport height, just set the height of your div to height:100vh;, this will set the height of your div to the height of the viewport of the device, furthermore, if you want it to be exactly as your device screen, set the margin and padding to 0.

Plus, It will be a good idea to set the viewport meta tag:

<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0" />

Please Note that this is relatively new and is not supported in IE8-, take a look at the support list before considering this approach (http://caniuse.com/#search=viewport).

Hope this helps.

How to roundup a number to the closest ten?

You can use the function MROUND(<reference cell>, <round to multiple of digit needed>).

Example:

  1. For a value A1 = 21 round to multiple of 10 it would be written as =MROUND(A1,10) for which Result = 20

  2. For a value Z4 = 55.1 round to multiple of 10 it would be written as =MROUND(Z4,10) for which Result = 60

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

For there to be a Smart Cast of the properties, the data type of the property must be the class that contains the method or behavior that you want to access and NOT that the property is of the type of the super class.


e.g on Android

Be:

class MyVM : ViewModel() {
    fun onClick() {}
}

Solution:

From: private lateinit var viewModel: ViewModel
To: private lateinit var viewModel: MyVM

Usage:

viewModel = ViewModelProvider(this)[MyVM::class.java]
viewModel.onClick {}

GL

SQL DATEPART(dw,date) need monday = 1 and sunday = 7

You can tell SQL Server to use Monday as the start of the week using DATEFIRST like this:

SET DATEFIRST 1

Is there anyway to exclude artifacts inherited from a parent POM?

Redefine the dependency (in the child pom) with scope system pointing to an empty jar :

<dependency>
    <groupId>dependency.coming</groupId>
    <artifactId>from.parent</artifactId>
    <version>0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/empty.jar</systemPath>
</dependency>

The jar can contain just a single empty file :

touch empty.txt
jar cvf empty.txt

"Could not find the main class" error when running jar exported by Eclipse

Have you renamed your project/main class (e.g. through refactoring) ? If yes your Launch Configuration might be set up incorrectly (e.g. refering to the old main class or configuration). Even though the project name appears in the 'export runnable jar' dialog, a closer inspection might reveal an unmatched main class name.

Go to 'Properties->Run/Debug Settings' of your project and make sure your Launch Configuration (the same used to export runnable jar) is set to the right name of project AND your main class is set to name.space.of.your.project/YouMainClass.

Force page scroll position to top at page refresh in HTML

To reset window scroll back to top, $(window).scrollTop(0) in the beforeunload event does the tricks, however, I tested in Chrome 80 it will go back to the old location after the reload.

To prevent that, set the history.scrollRestoration to "manual".

//Reset scroll top

history.scrollRestoration = "manual";

$(window).on('beforeunload', function(){
      $(window).scrollTop(0);
});

What is the opposite of evt.preventDefault();

I supose the "opposite" would be to simulate an event. You could use .createEvent()

Following Mozilla's example:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var cb = document.getElementById("checkbox"); 
  var cancelled = !cb.dispatchEvent(evt);
  if(cancelled) {
    // A handler called preventDefault
    alert("cancelled");
  } else {
    // None of the handlers called preventDefault
    alert("not cancelled");
  }
}

Ref: document.createEvent


jQuery has .trigger() so you can trigger events on elements -- sometimes useful.

$('#foo').bind('click', function() {
      alert($(this).text());
});

$('#foo').trigger('click');

Fastest method of screen capturing on Windows

I wrote a class that implemented the GDI method for screen capture. I too wanted extra speed so, after discovering the DirectX method (via GetFrontBuffer) I tried that, expecting it to be faster.

I was dismayed to find that GDI performs about 2.5x faster. After 100 trials capturing my dual monitor display, the GDI implementation averaged 0.65s per screen capture, while the DirectX method averaged 1.72s. So GDI is definitely faster than GetFrontBuffer, according to my tests.

I was unable to get Brandrew's code working to test DirectX via GetRenderTargetData. The screen copy came out purely black. However, it could copy that blank screen super fast! I'll keep tinkering with that and hope to get a working version to see real results from it.

How do I check if a string contains another string in Swift?

> IN SWIFT 3.0

let str = "Hello Swift"
if str.lowercased().contains("Swift".lowercased()) {
    print("String Contains Another String")
} else {
    print("Not Exists")
}

Output

String Contains Another String

How to concatenate strings in a Windows batch file?

Note that the variables @fname or @ext can be simply concatenated. This:

forfiles /S /M *.pdf /C "CMD /C REN @path @fname_old.@ext"

renames all PDF files to "filename_old.pdf"

Best GUI designer for eclipse?

Visual Editor is a good choice.

It generates very clean code, with no "layout" files beside of your sourcen using a simple but convenient pattern. It's very easy to patch the generated code and directly see the result. There are some stability problems (some times, the preview window does not refresh anymore...), but nothing that a "clean Project" can't fix...

How to use Switch in SQL Server

This is a select statement, so each branch of the case must return something. If you want to perform actions, just use an if.

Function to convert timestamp to human date in javascript

Moment.js can convert unix timestamps into any custom format

In this case : var time = moment(1382086394000).format("DD-MM-YYYY h:mm:ss");

will print 18-10-2013 11:53:14;

Here's a plunker that demonstrates this.

How do I quickly rename a MySQL database (change schema name)?

in phpmyadmin you can easily rename the database

select database 

  goto operations tab

  in that rename Database to :

  type your new database name and click go

ask to drop old table and reload table data click OK in both

Your database is renamed

Loading and parsing a JSON file with multiple JSON objects

That is ill-formatted. You have one JSON object per line, but they are not contained in a larger data structure (ie an array). You'll either need to reformat it so that it begins with [ and ends with ] with a comma at the end of each line, or parse it line by line as separate dictionaries.

Array length in angularjs returns undefined

Make it like this:

$scope.users.data.length;

Loop backwards using indices in Python?

I wanted to loop through a two lists backwards at the same time so I needed the negative index. This is my solution:

a= [1,3,4,5,2]
for i in range(-1, -len(a), -1):
    print(i, a[i])

Result:

-1 2
-2 5
-3 4
-4 3
-5 1

Mysql where id is in array

$string="1,2,3,4,5";
$array=array_map('intval', explode(',', $string));
$array = implode("','",$array);
$query=mysqli_query($conn, "SELECT name FROM users WHERE id IN ('".$array."')");

NB: the syntax is:

SELECT * FROM table WHERE column IN('value1','value2','value3')

Include PHP file into HTML file

In order to get the PHP output into the HTML file you need to either

  • Change the extension of the HTML to file to PHP and include the PHP from there (simple)
  • Load your HTML file into your PHP as a kind of template (a lot of work)
  • Change your environment so it deals with HTML as if it was PHP (bad idea)

MongoDB - admin user not authorized

I followed these steps on Centos 7 for MongoDB 4.2. (Remote user)

Update mongod.conf file

vi /etc/mongod.conf
   net:
     port: 27017
     bindIp: 0.0.0.0 
   security:
     authorization: enabled

Start MongoDB service demon

systemctl start mongod

Open MongoDB shell

mongo

Execute this command on the shell

use admin
db.createUser(
  {
    user: 'admin',
    pwd: 'YouPassforUser',
    roles: [ { role: 'root', db: 'admin' } ]
  }
);

Remote root user has been created. Now you can test this database connection by using any MongoDB GUI tool from your dev machine. Like Robo 3T

iterating through Enumeration of hastable keys throws NoSuchElementException error

Every time you call e.nextElement() you take the next object from the iterator. You have to check e.hasMoreElement() between each call.


Example:

while(e.hasMoreElements()){
    String param = e.nextElement();
    System.out.println(param);
}

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

How can I refresh a page with jQuery?

The question should be,

How to refresh a page with JavaScript

window.location.href = window.location.href; //This is a possibility
window.location.reload(); //Another possiblity
history.go(0); //And another

You're spoiled for choice.

How to show form input fields based on select value?

You have a few issues with your code:

  1. you are missing an open quote on the id of the select element, so: <select name="dbType" id=dbType">

should be <select name="dbType" id="dbType">

  1. $('this') should be $(this): there is no need for the quotes inside the paranthesis.

  2. use .val() instead of .value() when you want to retrieve the value of an option

  3. when u initialize "selection" do it with a var in front of it, unless you already have done it at the beggining of the function

try this:

   $('#dbType').on('change',function(){
        if( $(this).val()==="other"){
        $("#otherType").show()
        }
        else{
        $("#otherType").hide()
        }
    });

http://jsfiddle.net/ks6cv/

UPDATE for use with switch:

$('#dbType').on('change',function(){
     var selection = $(this).val();
    switch(selection){
    case "other":
    $("#otherType").show()
   break;
    default:
    $("#otherType").hide()
    }
});

UPDATE with links for jQuery and jQuery-UI:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>??

What are some alternatives to ReSharper?

VSCommands - not an alternative per se, but rather a complementary tool with plenty of unique features not available in ReSharper, CodeRush, and JustCode.

From the website:

IDE Enhancements

* Custom Formatting
      o Build Output
      o Debug Output
      o Search Output
* Solution Properties
      o Manage Reference Paths
      o Manage Project Properties
* Apply Fix
      o File being used by another process
      o [StyleCop][2] warnings
      o Importing .pfx key file was cancelled
* Search Online
* Cancel Build When First Project Fails
* Advanced Zooming

Solution Explorer Enhancements

* Prevent Accidental Drag & Drop
* Prevent Accidental Linked Item Delete
* Group / Ungroup Items
* Show Assembly Details
* Build Startup Projects
* Open Command Prompt
* Open PowerShell
* Locate Source File
* Open File Location
* Show / Hide All Files
* Edit Project / Solution File
* Copy / Paste As Link
* Copy / Paste Reference
* Open In Expression Blend
* Collapse All
* Clean All Build Configurations

Debugging Assistance

* Attach To Local IIS
* Debug As Administrator
* Debug As Normal user
* Debug As Different user

Code Assistance

* Create Code Contract

Turn off constraints temporarily (MS SQL)

And, if you want to verify that you HAVEN'T broken your relationships and introduced orphans, once you have re-armed your checks, i.e.

ALTER TABLE foo CHECK CONSTRAINT ALL

or

ALTER TABLE foo CHECK CONSTRAINT FK_something

then you can run back in and do an update against any checked columns like so:

UPDATE myUpdatedTable SET someCol = someCol, fkCol = fkCol, etc = etc

And any errors at that point will be due to failure to meet constraints.

How do I create a singleton service in Angular 2?

this seems to be working well for me

@Injectable()
export class MyStaticService {
  static instance: MyStaticService;

  constructor() {
    return MyStaticService.instance = MyStaticService.instance || this;
  }
}

Maven Out of Memory Build Failure

Using .mvn/jvm.config worked for me plus has the added benefit of being linked with the project.

Saving a Numpy array as an image

You can use PyPNG. It's a pure Python (no dependencies) open source PNG encoder/decoder and it supports writing NumPy arrays as images.

Make xargs handle filenames that contain spaces

xargs on MacOS doesn't have -d option, so this solution uses -0 instead.

Get ls to output one file per line, then translate newlines into nulls and tell xargs to use nulls as the delimiter:

ls -1 *mp3 | tr "\n" "\0" | xargs -0 mplayer

javax vs java package

The javax namespace is usually (that's a loaded word) used for standard extensions, currently known as optional packages. The standard extensions are a subset of the non-core APIs; the other segment of the non-core APIs obviously called the non-standard extensions, occupying the namespaces like com.sun.* or com.ibm.. The core APIs take up the java. namespace.

Not everything in the Java API world starts off in core, which is why extensions are usually born out of JSR requests. They are eventually promoted to core based on 'wise counsel'.

The interest in this nomenclature, came out of a faux pas on Sun's part - extensions could have been promoted to core, i.e. moved from javax.* to java.* breaking the backward compatibility promise. Programmers cried hoarse, and better sense prevailed. This is why, the Swing API although part of the core, continues to remain in the javax.* namespace. And that is also how packages get promoted from extensions to core - they are simply made available for download as part of the JDK and JRE.

C# Inserting Data from a form into an access Database

My Code to insert data is not working. It showing no error but data is not showing in my database.

public partial class Form1 : Form { OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString); public Form1() { InitializeComponent(); }

    private void Form1_Load(object sender, EventArgs e)
    {
        
    }

    private void btn_add_Click(object sender, EventArgs e)
    {
        OleDbDataAdapter items = new OleDbDataAdapter();
        connection.Open();
        OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName,  SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
        command.CommandType = CommandType.Text;
        command.ExecuteReader();
        connection.Close();
        MessageBox.Show("Insertd!");
    }
}

Git commit with no commit message

The commit message is a best practice that should be followed at all times. Unless you're the only developer and that isn't going to change any time soon.

git commit -a -m 'asdfasdfadsfsdf'

What's the best way to get the last element of an array without deleting it?

What if you want to get the last element of array inside of the loop of it's array?

The code below will result into an infinite loop:

foreach ($array as $item) {
 $last_element = end($array);
 reset($array);
 if ($last_element == $item) {
   // something useful here
 }
}

The solution is obviously simple for non associative arrays:

$last_element = $array[sizeof ($array) - 1];
foreach ($array as $key => $item) {
 if ($last_element == $item) {
   // something useful here
 }
}

Including .cpp files

What include does is copying all the contents from the file (which is the argument inside the <> or the "" ), so when the preproccesor finishes its work main.cpp will look like:

// iostream stuff

int foo(int a){
    return ++a;
}

int main(int argc, char *argv[])
{
   int x=42;
   std::cout << x <<std::endl;
   std::cout << foo(x) << std::endl;
   return 0;
}

So foo will be defined in main.cpp, but a definition also exists in foop.cpp, so the compiler "gets confused" because of the function duplication.

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

I ran into this having 2 Doctrine DBAL connections, one of those as non-transactional (for important logs), they are intended to run parallel not depending on each other.

CodeExecution(
    TransactionConnectionQuery()
    TransactionlessConnectionQuery()
)

My integration tests were wrapped into transactions for data rollback after very test.

beginTransaction()
CodeExecution(
    TransactionConnectionQuery()
    TransactionlessConnectionQuery() // CONFLICT
)
rollBack()

My solution was to disable the wrapping transaction in those tests and reset the db data in another way.

Check if a string contains another string

Building on Rene's answer, you could also write a function that returned either TRUE if the substring was present, or FALSE if it wasn't:

Public Function Contains(strBaseString As String, strSearchTerm As String) As Boolean
'Purpose: Returns TRUE if one string exists within another
On Error GoTo ErrorMessage
    Contains = InStr(strBaseString, strSearchTerm)
Exit Function
ErrorMessage:
MsgBox "The database has generated an error. Please contact the database administrator, quoting the following error message: '" & Err.Description & "'", vbCritical, "Database Error"
End
End Function

When correctly use Task.Run and when just async-await

One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get

public class PageViewModel : IHandle<SomeMessage>
{
   ...

   public async void Handle(SomeMessage message)
   {
      ShowLoadingAnimation();

      // makes UI very laggy, but still not dead
      await this.contentLoader.LoadContentAsync(); 

      HideLoadingAnimation();   
   }
}

public class ContentLoader 
{
    public async Task LoadContentAsync()
    {
        var tasks = new List<Task>();
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoIoBoundWorkAsync());
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoSomeOtherWorkAsync());

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
}

Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.

Get current cursor position in a textbox

Here's one possible method.

function isMouseInBox(e) {
  var textbox = document.getElementById('textbox');

  // Box position & sizes
  var boxX = textbox.offsetLeft;
  var boxY = textbox.offsetTop;
  var boxWidth = textbox.offsetWidth;
  var boxHeight = textbox.offsetHeight;

  // Mouse position comes from the 'mousemove' event
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
    if(mouseY>=boxY && mouseY<=boxY+boxHeight){
       // Mouse is in the box
       return true;
    }
  }
}

document.addEventListener('mousemove', function(e){
    isMouseInBox(e);
})

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

How can I clear console

In Windows we have multiple options :

  1. clrscr() (Header File : conio.h)

  2. system("cls") (Header File : stdlib.h)

In Linux, use system("clear") (Header File : stdlib.h)

Remove a HTML tag but keep the innerHtml

The simplest way to remove inner html elements and return only text would the JQuery .text() function.

Example:

var text = $('<p>A nice house was found in <b>Toronto</b></p>');

alert( text.html() );
//Outputs A nice house was found in <b>Toronto</b>

alert( text.text() );
////Outputs A nice house was found in Toronto

jsFiddle Demo

How to SUM and SUBTRACT using SQL?

ah homework...

So wait, you need to deduct the balance of items in stock from the total number of those items that have been ordered? I have to tell you that sounds a bit backwards. Generally I think people do it the other way round. Deduct the total number of items ordered from the balance.

If you really need to do that though... Assuming that ITEM is unique in stock_bal...

SELECT s.ITEM, SUM(m.QTY) - s.QTY AS result
FROM stock_bal s
INNER JOIN master_table m ON m.ITEM = s.ITEM
GROUP BY s.ITEM, s.QTY

How to save a list to a file and read it as a list type?

I decided I didn't want to use a pickle because I wanted to be able to open the text file and change its contents easily during testing. Therefore, I did this:

score = [1,2,3,4,5]

with open("file.txt", "w") as f:
    for s in score:
        f.write(str(s) +"\n")
score = []
with open("file.txt", "r") as f:
  for line in f:
    score.append(int(line.strip()))

So the items in the file are read as integers, despite being stored to the file as strings.

from unix timestamp to datetime

If using react:

import Moment from 'react-moment';
Moment.globalFormat = 'D MMM YYYY';

then:

<td><Moment unix>{1370001284}</Moment></td>

What is the largest possible heap size with a 64-bit JVM?

For a 64-bit JVM running in a 64-bit OS on a 64-bit machine, is there any limit besides the theoretical limit of 2^64 bytes or 16 exabytes?

You also have to take hardware limits into account. While pointers may be 64bit current CPUs can only address a less than 2^64 bytes worth of virtual memory.

With uncompressed pointers the hotspot JVM needs a continuous chunk of virtual address space for its heap. So the second hurdle after hardware is the operating system providing such a large chunk, not all OSes support this.

And the third one is practicality. Even if you can have that much virtual memory it does not mean the CPUs support that much physical memory, and without physical memory you will end up swapping, which will adversely affect the performance of the JVM because the GCs generally have to touch a large fraction of the heap.

As other answers mention compressed oops: By bumping the object alignment higher than 8 bytes the limits with compressed oops can be increased beyond 32GB

Difference between JOIN and INNER JOIN

They are functionally equivalent, but INNER JOIN can be a bit clearer to read, especially if the query has other join types (i.e. LEFT or RIGHT or CROSS) included in it.

How do I set the default schema for a user in MySQL

There is no default database for user. There is default database for current session.

You can get it using DATABASE() function -

SELECT DATABASE();

And you can set it using USE statement -

USE database1;

You should set it manually - USE db_name, or in the connection string.

How to get everything after a certain character?

The strpos() finds the offset of the underscore, then substr grabs everything from that index plus 1, onwards.

$data = "123_String";    
$whatIWant = substr($data, strpos($data, "_") + 1);    
echo $whatIWant;

If you also want to check if the underscore character (_) exists in your string before trying to get it, you can use the following:

if (($pos = strpos($data, "_")) !== FALSE) { 
    $whatIWant = substr($data, $pos+1); 
}

Passing argument to alias in bash

Usually when I want to pass arguments to an alias in Bash, I use a combination of an alias and a function like this, for instance:

function __t2d {                                                                
         if [ "$1x" != 'x' ]; then                                              
            date -d "@$1"                                                       
         fi                                                                     
} 

alias t2d='__t2d'                                                               

How can I remove a trailing newline?


This will work both for windows and linux (bit expensive with re sub if you are looking for only re solution)

import re 
if re.search("(\\r|)\\n$", line):
    line = re.sub("(\\r|)\\n$", "", line)

How to fetch all Git branches

When you clone a repository all the information of the branches is actually downloaded but the branches are hidden. With the command

$ git branch -a

you can show all the branches of the repository, and with the command

$ git checkout -b branchname origin/branchname

you can then "download" them manually one at a time.


However, there is a much cleaner and quicker way, though it's a bit complicated. You need three steps to accomplish this:

  1. First step

    create a new empty folder on your machine and clone a mirror copy of the .git folder from the repository:

    $ cd ~/Desktop && mkdir my_repo_folder && cd my_repo_folder
    $ git clone --mirror https://github.com/planetoftheweb/responsivebootstrap.git .git
    

    the local repository inside the folder my_repo_folder is still empty, there is just a hidden .git folder now that you can see with a "ls -alt" command from the terminal.

  2. Second step

    switch this repository from an empty (bare) repository to a regular repository by switching the boolean value "bare" of the git configurations to false:

    $ git config --bool core.bare false
    
  3. Third Step

    Grab everything that inside the current folder and create all the branches on the local machine, therefore making this a normal repo.

    $ git reset --hard
    

So now you can just type the command git branch and you can see that all the branches are downloaded.

This is the quick way in which you can clone a git repository with all the branches at once, but it's not something you wanna do for every single project in this way.

How to add local jar files to a Maven project?

To install third party jar, Please call the command like below

mvn install:install-file -DgroupId= -DartifactId= -Dversion= -Dpackaging=jar -Dfile=path

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

Moq cannot mock non-virtual methods and sealed classes. While running a test using mock object, MOQ actually creates an in-memory proxy type which inherits from your "XmlCupboardAccess" and overrides the behaviors that you have set up in the "SetUp" method. And as you know in C#, you can override something only if it is marked as virtual which isn't the case with Java. Java assumes every non-static method to be virtual by default.

Another thing I believe you should consider is introducing an interface for your "CupboardAccess" and start mocking the interface instead. It would help you decouple your code and have benefits in the longer run.

Lastly, there are frameworks like : TypeMock and JustMock which work directly with the IL and hence can mock non-virtual methods. Both however, are commercial products.

Debug/run standard java in Visual Studio Code IDE and OS X?

I can tell you for Windows.

  1. Install Java Extension Pack and Code Runner Extension from VS Code Extensions.

  2. Edit your java home location in VS Code settings, "java.home": "C:\\Program Files\\Java\\jdk-9.0.4".

  3. Check if javac is recognized in VS Code internal terminal. If this check fails, try opening VS Code as administrator.

  4. Create a simple Java program in Main.java file as:

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world");     
    }
}

Note: Do not add package in your main class.

  1. Right click anywhere on the java file and select run code.

  2. Check the output in the console.

Done, hope this helps.

How to set the JSTL variable value in javascript?

You have to use the normal string concatenation but you have to make sure the value is a Valid XML string, you will find a good practice to write XML in this source http://oreilly.com/pub/h/2127, or if you like you can use an API in javascript to write XML as helma for example.

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

In your cshtml,

<tr ng-repeat="value in Results">                
 <td>{{value.FileReceivedOn | mydate | date : 'dd-MM-yyyy'}} </td>
</tr>

In Your JS File, maybe app.js,

Outside of app.controller, add the below filter.

Here the "mydate" is the function which you are calling for parsing the date. Here the "app" is the variable which contains the angular.module

app.filter("mydate", function () {
    var re = /\/Date\(([0-9]*)\)\//;
    return function (x) {
        var m = x.match(re);
        if (m) return new Date(parseInt(m[1]));
        else return null;
    };
});

How to change background color in the Notepad++ text editor?

Go to Settings -> Style Configurator

Select Theme: Choose whichever you like best (the top two are easiest to read by most people's preference)

what is the multicast doing on 224.0.0.251?

If you don't have avahi installed then it's probably cups.

how to make a new line in a jupyter markdown cell

"We usually put ' (space)' after the first sentence before a new line, but it doesn't work in Jupyter."

That inspired me to try using two spaces instead of just one - and it worked!!

(Of course, that functionality could possibly have been introduced between when the question was asked in January 2017, and when my answer was posted in March 2018.)

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

I did like this :

public static class JsonExtension
{
    public static string ToJson(this object value)
    {
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            NullValueHandling = NullValueHandling.Ignore,
            ReferenceLoopHandling = ReferenceLoopHandling.Serialize
        };
        return JsonConvert.SerializeObject(value, settings);
    }
}

this a simple extension method in MVC core , it's going to give the ToJson() ability to every object in your project , In my opinion in a MVC project most of object should have the ability to become json ,off course it depends :)

A weighted version of random.choice

I looked the pointed other thread and came up with this variation in my coding style, this returns the index of choice for purpose of tallying, but it is simple to return the string ( commented return alternative):

import random
import bisect

try:
    range = xrange
except:
    pass

def weighted_choice(choices):
    total, cumulative = 0, []
    for c,w in choices:
        total += w
        cumulative.append((total, c))
    r = random.uniform(0, total)
    # return index
    return bisect.bisect(cumulative, (r,))
    # return item string
    #return choices[bisect.bisect(cumulative, (r,))][0]

# define choices and relative weights
choices = [("WHITE",90), ("RED",8), ("GREEN",2)]

tally = [0 for item in choices]

n = 100000
# tally up n weighted choices
for i in range(n):
    tally[weighted_choice(choices)] += 1

print([t/sum(tally)*100 for t in tally])

How to specify the private SSH-key to use when executing shell command on Git?

Way better idea to add that host or ip to the .ssh/config file like so:

Host (a space separated list of made up aliases you want to use for the host)
    User git
    Hostname (ip or hostname of git server)
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_(the key you want for this repo)

Getting the IP Address of a Remote Socket Endpoint

RemoteEndPoint is a property, its type is System.Net.EndPoint which inherits from System.Net.IPEndPoint.

If you take a look at IPEndPoint's members, you'll see that there's an Address property.

Detect if an element is visible with jQuery

You're looking for:

.is(':visible')

Although you should probably change your selector to use jQuery considering you're using it in other places anyway:

if($('#testElement').is(':visible')) {
    // Code
}

It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible') on the child will return false (which makes sense).

jQuery 3

:visible has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible):

Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!

Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.


Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle():

function toggleTestElement() {
    $('#testElement').fadeToggle('fast');
}

Concatenating strings in C, which method is more efficient?

Here's some madness for you, I actually went and measured it. Bloody hell, imagine that. I think I got some meaningful results.

I used a dual core P4, running Windows, using mingw gcc 4.4, building with "gcc foo.c -o foo.exe -std=c99 -Wall -O2".

I tested method 1 and method 2 from the original post. Initially kept the malloc outside the benchmark loop. Method 1 was 48 times faster than method 2. Bizarrely, removing -O2 from the build command made the resulting exe 30% faster (haven't investigated why yet).

Then I added a malloc and free inside the loop. That slowed down method 1 by a factor of 4.4. Method 2 slowed down by a factor of 1.1.

So, malloc + strlen + free DO NOT dominate the profile enough to make avoiding sprintf worth while.

Here's the code I used (apart from the loops were implemented with < instead of != but that broke the HTML rendering of this post):

void a(char *first, char *second, char *both)
{
    for (int i = 0; i != 1000000 * 48; i++)
    {
        strcpy(both, first);
        strcat(both, " ");
        strcat(both, second);
    }
}

void b(char *first, char *second, char *both)
{
    for (int i = 0; i != 1000000 * 1; i++)
        sprintf(both, "%s %s", first, second);
}

int main(void)
{
    char* first= "First";
    char* second = "Second";
    char* both = (char*) malloc((strlen(first) + strlen(second) + 2) * sizeof(char));

    // Takes 3.7 sec with optimisations, 2.7 sec WITHOUT optimisations!
    a(first, second, both);

    // Takes 3.7 sec with or without optimisations
    //b(first, second, both);

    return 0;
}

..The underlying connection was closed: An unexpected error occurred on a receive

My Hosting server block requesting URL And code site getting the same error Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

enter image description here

After a lot of time spent and apply the following step to resolve this issue

  1. Added line before the call web URL

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

  2. still issue not resolve then I upgrade .net version to 4.7.2 but I think it's optional

  3. Last change I have checked my hosting server security level which causes to TLS handshaking for this used "https://www.ssllabs.com/ssltest/index.html" site
    and also check to request URL security level then I find the difference is requested URL have to enable a weak level Cipher Suites you can see in the below image

enter image description here

Now here are my hosting server supporting Cipher Suites

enter image description here

here is called if you have control over requesting URL host server then you can sync this both server Cipher Suites. but in my case, it's not possible so I have applied the following script in Windows PowerShell on my hosting server for enabling required weak level Cipher Suites.

Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_GCM_SHA384"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_128_GCM_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_128_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA"

after applying the above script my hosting server Cipher Suites level look like

enter image description here

Then my issue resolved.

Note: server security level downgrade is not a recommended option.

Moment.js get day name from date

var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('ddd');
console.log(weekDayName);

Result: Wed

var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('dddd');
console.log(weekDayName);

Result: Wednesday

How to programmatically tell if a Bluetooth device is connected?

This code is for the headset profiles, probably it will work for other profiles too. First you need to provide profile listener (Kotlin code):

private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) 
            mBluetoothHeadset = proxy as BluetoothHeadset            
    }

    override fun onServiceDisconnected(profile: Int) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null
        }
    }
}

Then while checking bluetooth:

mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)
if (!mBluetoothAdapter.isEnabled) {
    return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
}

It takes a bit of time until onSeviceConnected is called. After that you may get the list of the connected headset devices from:

mBluetoothHeadset!!.connectedDevices

How can I rename a conda environment?

conda should have given us a simple tool like cond env rename <old> <new> but it hasn't. Simply renaming the directory, as in this previous answer, of course, breaks the hardcoded hashbangs(#!). Hence, we need to go one more level deeper to achieve what we want.

conda env list
# conda environments:
#
base                  *  /home/tgowda/miniconda3
junkdetect               /home/tgowda/miniconda3/envs/junkdetect
rtg                      /home/tgowda/miniconda3/envs/rtg

Here I am trying to rename rtg --> unsup (please bear with those names, this is my real use case)

$ cd /home/tgowda/miniconda3/envs 
$ OLD=rtg
$ NEW=unsup
$ mv $OLD $NEW   # rename dir

$ conda env list
# conda environments:
#
base                  *  /home/tgowda/miniconda3
junkdetect               /home/tgowda/miniconda3/envs/junkdetect
unsup                    /home/tgowda/miniconda3/envs/unsup


$ conda activate $NEW
$ which python
  /home/tgowda/miniconda3/envs/unsup/bin/python

the previous answer reported upto this, but wait, we are not done yet! the pending task is, $NEW/bin dir has a bunch of executable scripts with hashbangs (#!) pointing to the $OLD env paths.

See jupyter, for example:

$ which jupyter
/home/tgowda/miniconda3/envs/unsup/bin/jupyter

$ head -1 $(which jupyter) # its hashbang is still looking at old
#!/home/tgowda/miniconda3/envs/rtg/bin/python

So, we can easily fix it with a sed

$ sed  -i.bak "s:envs/$OLD/bin:envs/$NEW/bin:" $NEW/bin/*  
# `-i.bak` created backups, to be safe

$ head -1 $(which jupyter) # check if updated
#!/home/tgowda/miniconda3/envs/unsup/bin/python
$ jupyter --version # check if it works
jupyter core     : 4.6.3
jupyter-notebook : 6.0.3

$ rm $NEW/bin/*.bak  # remove backups

Now we are done

I think it should be trivial to write a portable script to do all those and bind it to conda env rename old new.


I tested this on ubuntu. For whatever unforseen reasons, if things break and you wish to revert the above changes:

$ mv $NEW  $OLD
$ sed  -i.bak "s:envs/$NEW/bin:envs/$OLD/bin:" $OLD/bin/*

Can I update a component's props in React.js?

if you use recompose, use mapProps to make new props derived from incoming props

Edit for example:

import { compose, mapProps } from 'recompose';

const SomeComponent = ({ url, onComplete }) => (
  {url ? (
    <View />
  ) : null}
)

export default compose(
  mapProps(({ url, storeUrl, history, ...props }) => ({
    ...props,
    onClose: () => {
      history.goBack();
    },
    url: url || storeUrl,
  })),
)(SomeComponent);

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

For individual element the code below could be used:

private boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }
for (int second = 0;; second++) {
            if (second >= 60){
                fail("timeout");
            }
            try {
                if (isElementPresent(By.id("someid"))){
                    break;
                }
                }
            catch (Exception e) {

            }
            Thread.sleep(1000);
        }

LINQ to Entities does not recognize the method

I got the same error in this code:

 var articulos_en_almacen = xx.IV00102.Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

this was the exactly error:

System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[conector_gp.Models.almacenes_por_sucursal])' method, and this method cannot be translated into a store expression.'

I solved this way:

var articulos_en_almacen = xx.IV00102.ToList().Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

I added a .ToList() before my table, this decouple the Entity and linq code, and avoid my next linq expression be translated

NOTE: this solution isn't optimal, because avoid entity filtering, and simply loads all table into memory

How to write a simple Html.DropDownListFor()?

@using (Html.BeginForm()) {
    <p>Do you like pizza?
        @Html.DropDownListFor(x => x.likesPizza, new[] {
            new SelectListItem() {Text = "Yes", Value = bool.TrueString},
            new SelectListItem() {Text = "No", Value = bool.FalseString}
        }, "Choose an option") 
    </p>
    <input type = "submit" value = "Submit my answer" />
} 

I think this answer is similar to Berat's, in that you put all the code for your DropDownList directly in the view. But I think this is an efficient way of creating a y/n (boolean) drop down list, so I wanted to share it.

Some notes for beginners:

  • Don't worry about what 'x' is called - it is created here, for the first time, and doesn't link to anything else anywhere else in the MVC app, so you can call it what you want - 'x', 'model', 'm' etc.
  • The placeholder that users will see in the dropdown list is "Choose an option", so you can change this if you want.
  • There's a bit of text preceding the drop down which says "Do you like pizza?"
  • This should be complete text for a form, including a submit button, I think

Hope this helps someone,

How can I move a tag on a git branch to a different commit?

One other way:

Move tag in remote repo.(Replace HEAD with any other if needed.)

$ git push --force origin HEAD:refs/tags/v0.0.1.2

Fetch changes back.

$ git fetch --tags

PHPExcel Make first row bold

Try this

$objPHPExcel->getActiveSheet()->getStyle('A1:D1')->getFont()->setBold(true);

Write a number with two decimal places SQL Server

This is how the kids are doing it today:

DECLARE @test DECIMAL(18,6) = 123.456789
SELECT FORMAT(@test, '##.##')

123.46

Where does Android app package gets installed on phone

An application when installed on a device or on an emulator will install at:

/data/data/APP_PACKAGE_NAME

The APK itself is placed in the /data/app/ folder.

These paths, however, are in the System Partition and to access them, you will need to have root. This is for a device. On the emulator, you can see it in your logcat (DDMS) in the File Explorer tab

By the way, it only shows the package name that is defined in your Manifest.XML under the package="APP_PACKAGE_NAME" attribute. Any other packages you may have created in your project in Eclipse do not show up here.

TypeError: $(...).modal is not a function with bootstrap Modal

Run

npm i @types/jquery
npm install -D @types/bootstrap

in the project to add the jquery types in your Angular Project. After that include

import * as $ from "jquery";
import * as bootstrap from "bootstrap";

in your app.module.ts

Add

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

in your index.html just before the body closing tag.

And if you are running Angular 2-7 include "jquery" in the types field of tsconfig.app.json file.

This will remove all error of 'modal' and '$' in your Angular project.

Write applications in C or C++ for Android?

Maybe you are looking for this?

http://www.mosync.com/

It is a middle layer for developing for several mobile platforms using c++.

Transpose a matrix in Python

Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)

import numpy as np

a = np.array([(1,2,3), (4,5,6)])

b = a.transpose()

Summing elements in a list

def sumoflist(l):    
    total = 0    
    for i in l:
        total +=i
    return total

How to assign more memory to docker container

Allocate maximum memory to your docker machine from (docker preference -> advance )

Screenshot of advance settings: Screenshot of advance settings.

This will set the maximum limit docker consume while running containers. Now run your image in new container with -m=4g flag for 4 gigs ram or more. e.g.

docker run -m=4g {imageID}

Remember to apply the ram limit increase changes. Restart the docker and double check that ram limit did increased. This can be one of the factor you not see the ram limit increase in docker containers.

Missing XML comment for publicly visible type or member

Insert an XML comment. ;-)

/// <summary>
/// Describe your member here.
/// </summary>
public string Something
{
    get;
    set;
}

This may appear like a joke at the first glance, but it may actually be useful. For me it turned out to be helpful to think about what methods do even for private methods (unless really trivial, of course).

Error when trying vagrant up

I know this is old, but I got exactly the same error. Turns out I was missing this step that is clearly in the documentation.

I needed to edit the Vagrantfile to set the config.vm.box equal to the image I had downloaded, hashicorp/precise32. By default it was set to base.

Here's what the documentation says:

Now that the box has been added to Vagrant, we need to configure our project to use it as a base. Open the Vagrantfile and change the contents to the following:

Vagrant.configure("2") do |config|
  config.vm.box = "hashicorp/precise32"
end

Close Current Tab

Use this:

window.open('', '_self');

This only works in chrome; it is a bug. It will be fixed in the future, so use this hacky solution with this in mind.

Double.TryParse or Convert.ToDouble - which is faster and safer?

Lots of hate for the Convert class here... Just to balance a little bit, there is one advantage for Convert - if you are handed an object,

Convert.ToDouble(o);

can just return the value easily if o is already a Double (or an int or anything readily castable).

Using Double.Parse or Double.TryParse is great if you already have it in a string, but

Double.Parse(o.ToString());

has to go make the string to be parsed first and depending on your input that could be more expensive.

DateTime.Compare how to check if a date is less than 30 days old?

Compare is unnecessary, Days / TotalDays are unnecessary.

All you need is

if (expireDate < DateTime.Now) {
    // has expired
} else {
    // not expired
}

note this will work if you decide to use minutes or months or even years as your expiry criteria.

npm install -g less does not work: EACCES: permission denied

I have tried all the suggested solutions but nothing worked.

I am using macOS Catalina 10.15.3

Go to /usr/local/

Select bin folder > Get Info

Add your user to Sharing & Permissions. Read & Write Permissions. enter image description here

And go to terminal and run npm install -g @ionic/cli

It has helped me.

Javascript - Get Image height

It's worth noting that in Firefox 3 and Safari, resizing an image by just changing the height and width doesn't look too bad. In other browsers it can look very noisy because it's using nearest-neighbor resampling. Of course, you're paying to serve a larger image, but that might not matter.

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

Converting XDocument to XmlDocument and vice versa

You can use the built in xDocument.CreateReader() and an XmlNodeReader to convert back and forth.

Putting that into an Extension method to make it easier to work with.

using System;
using System.Xml;
using System.Xml.Linq;

namespace MyTest
{
    internal class Program
    {
        private static void Main(string[] args)
        {

            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<Root><Child>Test</Child></Root>");

            var xDocument = xmlDocument.ToXDocument();
            var newXmlDocument = xDocument.ToXmlDocument();
            Console.ReadLine();
        }
    }

    public static class DocumentExtensions
    {
        public static XmlDocument ToXmlDocument(this XDocument xDocument)
        {
            var xmlDocument = new XmlDocument();
            using(var xmlReader = xDocument.CreateReader())
            {
                xmlDocument.Load(xmlReader);
            }
            return xmlDocument;
        }

        public static XDocument ToXDocument(this XmlDocument xmlDocument)
        {
            using (var nodeReader = new XmlNodeReader(xmlDocument))
            {
                nodeReader.MoveToContent();
                return XDocument.Load(nodeReader);
            }
        }
    }
}

Sources:

How to convert a char array to a string?

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

using namespace std;

int main ()
{
  char *tmp = (char *)malloc(128);
  int n=sprintf(tmp, "Hello from Chile.");

  string tmp_str = tmp;


  cout << *tmp << " : is a char array beginning with " <<n <<" chars long\n" << endl;
  cout << tmp_str << " : is a string with " <<n <<" chars long\n" << endl;

 free(tmp); 
 return 0;
}

OUT:

H : is a char array beginning with 17 chars long

Hello from Chile. :is a string with 17 chars long

Moment.js transform to date object

.toDate did not really work for me, So, Here is what i did :

futureStartAtDate = new Date(moment().locale("en").add(1, 'd').format("MMM DD, YYYY HH:MM"))

hope this helps

How can I run an external command asynchronously from Python?

There are several answers here but none of them satisfied my below requirements:

  1. I don't want to wait for command to finish or pollute my terminal with subprocess outputs.

  2. I want to run bash script with redirects.

  3. I want to support piping within my bash script (for example find ... | tar ...).

The only combination that satiesfies above requirements is:

subprocess.Popen(['./my_script.sh "arg1" > "redirect/path/to"'],
                 stdout=subprocess.PIPE, 
                 stderr=subprocess.PIPE,
                 shell=True)

How to convert local time string to UTC?

import time

import datetime

def Local2UTC(LocalTime):

    EpochSecond = time.mktime(LocalTime.timetuple())
    utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)

    return utcTime

>>> LocalTime = datetime.datetime.now()

>>> UTCTime = Local2UTC(LocalTime)

>>> LocalTime.ctime()

'Thu Feb  3 22:33:46 2011'

>>> UTCTime.ctime()

'Fri Feb  4 05:33:46 2011'

To the power of in C?

There's no operator for such usage in C, but a family of functions:

double pow (double base , double exponent);
float powf (float base  , float exponent);
long double powl (long double base, long double exponent);

Note that the later two are only part of standard C since C99.

If you get a warning like:

"incompatible implicit declaration of built in function 'pow' "

That's because you forgot #include <math.h>.

Conda command is not recognized on Windows 10

To prevent having further issues with SSL you should add all those to Path :

 SETX PATH "%PATH%;C:\<path>\Anaconda3;C:\<path>\Anaconda3\Scripts;C:\<path>\Anaconda3\Library\bin"

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

receiving json and deserializing as List of object at spring mvc controller

This is not possible the way you are trying it. The Jackson unmarshalling works on the compiled java code after type erasure. So your

public @ResponseBody ModelMap setTest(@RequestBody List<TestS> refunds, ModelMap map) 

is really only

public @ResponseBody ModelMap setTest(@RequestBody List refunds, ModelMap map) 

(no generics in the list arg).

The default type Jackson creates when unmarshalling a List is a LinkedHashMap.

As mentioned by @Saint you can circumvent this by creating your own type for the list like so:

class TestSList extends ArrayList<TestS> { }

and then modifying your controller signature to

public @ResponseBody ModelMap setTest(@RequestBody TestSList refunds, ModelMap map) {

Lombok annotations do not compile under Intellij idea

None of the advanced answers to this question resolved the problem for me.

I managed to solve the problem by adding a dependencie to lombok in the pom.xml file, i.e. :

<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.16.12</version>
</dependency>

I am using IntelliJ 2016.3.14 with maven-3.3.9

Hope my answer will be helpful for you

JavaScript closure inside loops – simple practical example

You could use a declarative module for lists of data such as query-js(*). In these situations I personally find a declarative approach less surprising

var funcs = Query.range(0,3).each(function(i){
     return  function() {
        console.log("My value: " + i);
    };
});

You could then use your second loop and get the expected result or you could do

funcs.iterate(function(f){ f(); });

(*) I'm the author of query-js and therefor biased towards using it, so don't take my words as a recommendation for said library only for the declarative approach :)