Programs & Examples On #Threshold

The starting point for a new state.

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

GCC dump preprocessor defines

The simple approach (gcc -dM -E - < /dev/null) works fine for gcc but fails for g++. Recently I required a test for a C++11/C++14 feature. Recommendations for their corresponding macro names are published at https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations. But:

g++ -dM -E - < /dev/null | fgrep __cpp_alias_templates

always fails, because it silently invokes the C-drivers (as if invoked by gcc). You can see this by comparing its output against that of gcc or by adding a g++-specific command line option like (-std=c++11) which emits the error message cc1: warning: command line option ‘-std=c++11’ is valid for C++/ObjC++ but not for C.

Because (the non C++) gcc will never support "Templates Aliases" (see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2258.pdf) you must add the -x c++ option to force the invocation of the C++ compiler (Credits for using the -x c++ options instead of an empty dummy file go to yuyichao, see below):

g++ -dM -E -x c++ /dev/null | fgrep __cpp_alias_templates

There will be no output because g++ (revision 4.9.1, defaults to -std=gnu++98) does not enable C++11-features by default. To do so, use

g++ -dM -E -x c++ -std=c++11 /dev/null | fgrep __cpp_alias_templates

which finally yields

#define __cpp_alias_templates 200704

noting that g++ 4.9.1 does support "Templates Aliases" when invoked with -std=c++11.

Can you write nested functions in JavaScript?

Not only can you return a function which you have passed into another function as a variable, you can also use it for calculation inside but defining it outside. See this example:

    function calculate(a,b,fn) {
      var c = a * 3 + b + fn(a,b);
      return  c;
    }

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

    function product(a,b) {
      return a*b;
    }

    document.write(calculate (10,20,sum)); //80
    document.write(calculate (10,20,product)); //250

Convert String to SecureString

below method helps to convert string to secure string

private SecureString ConvertToSecureString(string password)
{
    if (password == null)
        throw new ArgumentNullException("password");

    var securePassword = new SecureString();

    foreach (char c in password)
        securePassword.AppendChar(c);

    securePassword.MakeReadOnly();
    return securePassword;
}

How to dynamically add elements to String array?

Arrays in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).

Instead, use a List:

ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.

Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:

String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

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

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

Connect to SQL Server through PDO using SQL Server Driver

$servername = "";
$username = "";
$password = "";
$database = "";
$port = "1433";
try {
    $conn = new PDO("sqlsrv:server=$servername,$port;Database=$database;ConnectionPooling=0", $username, $password,
        array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        )
    );
} catch (PDOException $e) {
    echo ("Error connecting to SQL Server: " . $e->getMessage());
}

find -exec with multiple commands

1st answer of Denis is the answer to resolve the trouble. But in fact it is no more a find with several commands in only one exec like the title suggest. To answer the one exec with several commands thing we will have to look for something else to resolv. Here is a example:

Keep last 10000 lines of .log files which has been modified in the last 7 days using 1 exec command using severals {} references

1) see what the command will do on which files:

find / -name "*.log" -a -type f -a -mtime -7 -exec sh -c "echo tail -10000 {} \> fictmp; echo cat fictmp \> {} " \;

2) Do it: (note no more "\>" but only ">" this is wanted)

find / -name "*.log" -a -type f -a -mtime -7 -exec sh -c "tail -10000 {} > fictmp; cat fictmp > {} ; rm fictmp" \;

How to use makefiles in Visual Studio?

Makefiles and build files are about automating your build. If you use a script like MSBuild or NAnt, you can build your project or solution directly from command line. This in turn makes it possible to automate the build, have it run by a build server.

Besides building your solution it is typical that a build script includes task to run unit tests, report code coverage and complexity and more.

Query grants for a table in postgres

If you really want one line per user, you can group by grantee (require PG9+ for string_agg)

SELECT grantee, string_agg(privilege_type, ', ') AS privileges
FROM information_schema.role_table_grants 
WHERE table_name='mytable'   
GROUP BY grantee;

This should output something like :

 grantee |   privileges   
---------+----------------
 user1   | INSERT, SELECT
 user2   | UPDATE
(2 rows)

How to get text in QlineEdit when QpushButton is pressed in a string?

Acepted solution implemented in PyQt5

import sys
from PyQt5.QtWidgets import QApplication, QDialog, QFormLayout
from PyQt5.QtWidgets import (QPushButton, QLineEdit)

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect")
        self.pb.clicked.connect(self.button_click)

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)
        self.setLayout(layout)

        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print (shost)


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

How to set width and height dynamically using jQuery

or use this syntax:

$("#mainTable").css("width", "100px");
$("#mainTable").css("height", "200px");

Can an ASP.NET MVC controller return an Image?

Yes you can return Image

public ActionResult GetImage(string imageFileName)
{
    var path = Path.Combine(Server.MapPath("/Images"), imageFileName + ".jpg"); 
    return base.File(path, "image/jpeg");
}

(Please don't forget to mark this as answer)

How to get multiple selected values of select box in php?

You could do like this too. It worked out for me.

<form action="ResultsDulith.php" id="intermediate" name="inputMachine[]" multiple="multiple" method="post">
    <select id="selectDuration" name="selectDuration[]" multiple="multiple"> 
        <option value="1 WEEK" >Last 1 Week</option>
        <option value="2 WEEK" >Last 2 Week </option>
        <option value="3 WEEK" >Last 3 Week</option>
         <option value="4 WEEK" >Last 4 Week</option>
          <option value="5 WEEK" >Last 5 Week</option>
           <option value="6 WEEK" >Last 6 Week</option>
    </select>
     <input type="submit"/> 
</form>

Then take the multiple selection from following PHP code below. It print the selected multiple values accordingly.

$shift=$_POST['selectDuration'];

print_r($shift);

Difference between \b and \B in regex

Source © Copyright RexEgg.com

Word Boundary: \b*

The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).

The regex \bcat\b would, therefore, match cat in a black cat, but it wouldn't match it in catatonic, tomcat or certificate. Removing one of the boundaries, \bcat would match cat in catfish, and cat\b would match cat in tomcat, but not vice-versa. Both, of course, would match cat on its own.

Not-a-word-boundary: \B

\B matches all positions where \b doesn't match. Therefore, it matches:

? When neither side is a word character, for instance at any position in the string $=(@-%++) (including the beginning and end of the string)

? When both sides are a word character, for instance between the H and the i in Hi!

This may not seem very useful, but sometimes \B is just what you want. For instance,

? \Bcat\B will find cat fully surrounded by word characters, as in certificate, but neither on its own nor at the beginning or end of words.

? cat\B will find cat both in certificate and catfish, but neither in tomcat nor on its own.

? \Bcat will find cat both in certificate and tomcat, but neither in catfish nor on its own.

? \Bcat|cat\B will find cat in embedded situation, e.g. in certificate, catfish or tomcat, but not on its own.

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

I believe fcntl() is a POSIX function. Where as ioctl() is a standard UNIX thing. Here is a list of POSIX io. ioctl() is a very kernel/driver/OS specific thing, but i am sure what you use works on most flavors of Unix. some other ioctl() stuff might only work on certain OS or even certain revs of it's kernel.

npm check and update package if needed

To really update just one package install NCU and then run it just for that package. This will bump to the real latest.

npm install -g npm-check-updates

ncu -f your-intended-package-name -u

How to set a Default Route (To an Area) in MVC

This is how I did it. I don't know why MapRoute() doesn't allow you to set the area, but it does return the route object so you can continue to make any additional changes you would like. I use this because I have a modular MVC site that is sold to enterprise customers and they need to be able to drop dlls into the bin folder to add new modules. I allow them to change the "HomeArea" in the AppSettings config.

var route = routes.MapRoute(
                "Home_Default", 
                "", 
                new {controller = "Home", action = "index" },
                new[] { "IPC.Web.Core.Controllers" }
               );
route.DataTokens["area"] = area;

Edit: You can try this as well in your AreaRegistration.RegisterArea for the area you want the user going to by default. I haven't tested it but AreaRegistrationContext.MapRoute does sets route.DataTokens["area"] = this.AreaName; for you.

context.MapRoute(
                    "Home_Default", 
                    "", 
                    new {controller = "Home", action = "index" },
                    new[] { "IPC.Web.Core.Controllers" }
                   );

Button that refreshes the page on click

Though the question is for button, but if anyone wants to refresh the page using <a>, you can simply do

<a href="./">Reload</a>

Fatal error: Call to undefined function mb_strlen()

To fix this install the php7.0-mbstring package:

sudo apt install php7.0-mbstring

Get jQuery version from inspecting the jQuery object

$()['jquery']

Invoke console.log($()) and take note about jquery object fields :

  • jquery
  • selector
  • prevObject

enter image description here

Gulp command not found after install

You need to do this npm install --global gulp. It works for me and i also had this problem. It because you didn't install globally this package.

Java 8 method references: provide a Supplier capable of supplying a parameterized result

optionalUsers.orElseThrow(() -> new UsernameNotFoundException("Username not found"));

How to get back to most recent version in Git?

This did the trick for me (I still was on the master branch):

git reset --hard origin/master

How can I create an MSI setup?

You can use "Visual studio installer project" and its free...

This is very easy to create installer and has GUI.(Most of the freeware MSI creation tool does not have a GUI part)

You will find many tutorials to create an installer easily on the internet

To install. just search Visual Studio Installer Project in your Visual Studio

Visual Studio-> Tools-> Extensions&updates ->search Visual Studio Installer Project. Download it and enjoy...

How to flush output of print function?

Using the -u command-line switch works, but it is a little bit clumsy. It would mean that the program would potentially behave incorrectly if the user invoked the script without the -u option. I usually use a custom stdout, like this:

class flushfile:
  def __init__(self, f):
    self.f = f

  def write(self, x):
    self.f.write(x)
    self.f.flush()

import sys
sys.stdout = flushfile(sys.stdout)

... Now all your print calls (which use sys.stdout implicitly), will be automatically flushed.

How to display pie chart data values of each slice in chart.js

@Hung Tran's answer works perfect. As an improvement, I would suggest not showing values that are 0. Say you have 5 elements and 2 of them are 0 and rest of them have values, the solution above will show 0 and 0%. It is better to filter that out with a not equal to 0 check!

          var val = dataset.data[i];
          var percent = String(Math.round(val/total*100)) + "%";

          if(val != 0) {
            ctx.fillText(dataset.data[i], model.x + x, model.y + y);
            // Display percent in another line, line break doesn't work for fillText
            ctx.fillText(percent, model.x + x, model.y + y + 15);
          }

Updated code below:

var data = {
    datasets: [{
        data: [
            11,
            16,
            7,
            3,
            14
        ],
        backgroundColor: [
            "#FF6384",
            "#4BC0C0",
            "#FFCE56",
            "#E7E9ED",
            "#36A2EB"
        ],
        label: 'My dataset' // for legend
    }],
    labels: [
        "Red",
        "Green",
        "Yellow",
        "Grey",
        "Blue"
    ]
};

var pieOptions = {
  events: false,
  animation: {
    duration: 500,
    easing: "easeOutQuart",
    onComplete: function () {
      var ctx = this.chart.ctx;
      ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
      ctx.textAlign = 'center';
      ctx.textBaseline = 'bottom';

      this.data.datasets.forEach(function (dataset) {

        for (var i = 0; i < dataset.data.length; i++) {
          var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
              total = dataset._meta[Object.keys(dataset._meta)[0]].total,
              mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius)/2,
              start_angle = model.startAngle,
              end_angle = model.endAngle,
              mid_angle = start_angle + (end_angle - start_angle)/2;

          var x = mid_radius * Math.cos(mid_angle);
          var y = mid_radius * Math.sin(mid_angle);

          ctx.fillStyle = '#fff';
          if (i == 3){ // Darker text color for lighter background
            ctx.fillStyle = '#444';
          }

          var val = dataset.data[i];
          var percent = String(Math.round(val/total*100)) + "%";

          if(val != 0) {
            ctx.fillText(dataset.data[i], model.x + x, model.y + y);
            // Display percent in another line, line break doesn't work for fillText
            ctx.fillText(percent, model.x + x, model.y + y + 15);
          }
        }
      });               
    }
  }
};

var pieChartCanvas = $("#pieChart");
var pieChart = new Chart(pieChartCanvas, {
  type: 'pie', // or doughnut
  data: data,
  options: pieOptions
});

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

I used the Visual Studio 2008 Uninstall tool and it worked fine for me.

You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).

Found here, on the MSDN Forum: MSDN forum topic.

I found this answer here

Be sure you run the tool with admin-rights.

How do I wrap text in a pre tag?

I've found that skipping the pre tag and using white-space: pre-wrap on a div is a better solution.

 <div style="white-space: pre-wrap;">content</div>

What is the difference between sed and awk?

sed is a stream editor. It works with streams of characters on a per-line basis. It has a primitive programming language that includes goto-style loops and simple conditionals (in addition to pattern matching and address matching). There are essentially only two "variables": pattern space and hold space. Readability of scripts can be difficult. Mathematical operations are extraordinarily awkward at best.

There are various versions of sed with different levels of support for command line options and language features.

awk is oriented toward delimited fields on a per-line basis. It has much more robust programming constructs including if/else, while, do/while and for (C-style and array iteration). There is complete support for variables and single-dimension associative arrays plus (IMO) kludgey multi-dimension arrays. Mathematical operations resemble those in C. It has printf and functions. The "K" in "AWK" stands for "Kernighan" as in "Kernighan and Ritchie" of the book "C Programming Language" fame (not to forget Aho and Weinberger). One could conceivably write a detector of academic plagiarism using awk.

GNU awk (gawk) has numerous extensions, including true multidimensional arrays in the latest version. There are other variations of awk including mawk and nawk.

Both programs use regular expressions for selecting and processing text.

I would tend to use sed where there are patterns in the text. For example, you could replace all the negative numbers in some text that are in the form "minus-sign followed by a sequence of digits" (e.g. "-231.45") with the "accountant's brackets" form (e.g. "(231.45)") using this (which has room for improvement):

sed 's/-\([0-9.]\+\)/(\1)/g' inputfile

I would use awk when the text looks more like rows and columns or, as awk refers to them "records" and "fields". If I was going to do a similar operation as above, but only on the third field in a simple comma delimited file I might do something like:

awk -F, 'BEGIN {OFS = ","} {gsub("-([0-9.]+)", "(" substr($3, 2) ")", $3); print}' inputfile

Of course those are just very simple examples that don't illustrate the full range of capabilities that each has to offer.

Access Google's Traffic Data through a Web Service

Apparently the information is available using the Google Directions API in its professional edition Maps for work. According to the API's documentation:

Note: Maps for Work users must include client and signature parameters with their requests instead of a key.
[...]
duration_in_traffic indicates the total duration of this leg, taking into account current traffic conditions. The duration in traffic will only be returned if all of the following are true:

  • The directions request includes a departure_time parameter set to a value within a few minutes of the current time.
  • The request includes a valid Google Maps API for Work client and signature parameter.
  • Traffic conditions are available for the requested route.
  • The directions request does not include stopover waypoints.

Notepad++ Regular expression find and delete a line

Step 1

  • SearchFind → (goto Tab) Mark
  • Find what: ^Session.*$
  • Enable the checkbox Bookmark line
  • Enable the checkbox Regular expression (under Search Mode)
  • Click Mark All (this will find the regex and highlights all the lines and bookmark them)

Step 2

  • SearchBookmarkRemove Bookmarked Lines

How to install pip3 on Windows?

For python3.5.3, pip3 is also installed when you install python. When you install it you may not select the add to path. Then you can find where the pip3 located and add it to path manually.

How to use XPath preceding-sibling correctly

I also like to build locators from up to bottom like:

//div[contains(@class,'btn-group')][./button[contains(.,'Arcade Reader')]]/button[@name='settings']

It's pretty simple, as we just search btn-group with button[contains(.,'Arcade Reader')] and get it's button[@name='settings']

That's just another option to build xPath locators

What is the profit of searching wrapper element: you can return it by method (example in java) and just build selenium constructions like:

getGroupByName("Arcade Reader").find("button[name='settings']");
getGroupByName("Arcade Reader").find("button[name='delete']");

or even simplify more

getGroupButton("Arcade Reader", "delete").click();

How to configure slf4j-simple

I noticed that Eemuli said that you can't change the log level after they are created - and while that might be the design, it isn't entirely true.

I ran into a situation where I was using a library that logged to slf4j - and I was using the library while writing a maven mojo plugin.

Maven uses a (hacked) version of the slf4j SimpleLogger, and I was unable to get my plugin code to reroute its logging to something like log4j, which I could control.

And I can't change the maven logging config.

So, to quiet down some noisy info messages, I found I could use reflection like this, to futz with the SimpleLogger at runtime.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
    try
    {
        Logger l = LoggerFactory.getLogger("full.classname.of.noisy.logger");  //This is actually a MavenSimpleLogger, but due to various classloader issues, can't work with the directly.
        Field f = l.getClass().getSuperclass().getDeclaredField("currentLogLevel");
        f.setAccessible(true);
        f.set(l, LocationAwareLogger.WARN_INT);
    }
    catch (Exception e)
    {
        getLog().warn("Failed to reset the log level of " + loggerName + ", it will continue being noisy.", e);
    }

Of course, note, this isn't a very stable / reliable solution... as it will break the next time the maven folks change their logger.

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

I had the same problem and solved it by going to File -> Project Structure... -> Suggestions and then Apply all. Like suggested by @JeffinJ I think the problem was because of the Gradle plugin update.

undefined offset PHP error

If preg_match did not find a match, $matches is an empty array. So you should check if preg_match found an match before accessing $matches[0], for example:

function get_match($regex,$content)
{
    if (preg_match($regex,$content,$matches)) {
        return $matches[0];
    } else {
        return null;
    }
}

For vs. while in C programming?

A for suggest a fixed iteration using an index or variants on this scheme.

A while and do... while are constructions you use when there is a condition that must be checked each time (apart from some index-alike construction, see above). They differ in when the first execution of the condition check is performed.

You can use either construct, but they have their advantages and disadvantages depending on your use case.

Image encryption/decryption using AES256 symmetric block ciphers

Simple API to perform AES encryption on Android. This is the Android counterpart to the AESCrypt library Ruby and Obj-C (with the same defaults):

https://github.com/scottyab/AESCrypt-Android

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

Saving numpy array to txt file row wise

import numpy as np

a = [1,2,3]    
b = np.array(a).reshape((1,3))    
np.savetxt('a.txt',b,fmt='%d')

Convert blob to base64

var audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;

var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
     base64data = reader.result;
     console.log(base64data);
}

What's the correct way to convert bytes to a hex string in Python 3?

import codecs
codecs.getencoder('hex_codec')(b'foo')[0]

works in Python 3.3 (so "hex_codec" instead of "hex").

How can I get the index from a JSON object with value?

You can use Array.findIndex.

_x000D_
_x000D_
var data= [{
  "name": "placeHolder",
  "section": "right"
}, {
  "name": "Overview",
  "section": "left"
}, {
  "name": "ByFunction",
  "section": "left"
}, {
  "name": "Time",
  "section": "left"
}, {
  "name": "allFit",
  "section": "left"
}, {
  "name": "allbMatches",
  "section": "left"
}, {
  "name": "allOffers",
  "section": "left"
}, {
  "name": "allInterests",
  "section": "left"
}, {
  "name": "allResponses",
  "section": "left"
}, {
  "name": "divChanged",
  "section": "right"
}];
var index = data.findIndex(obj => obj.name=="allInterests");

console.log(index);
_x000D_
_x000D_
_x000D_

Unicode character in PHP string

Because JSON directly supports the \uxxxx syntax the first thing that comes into my mind is:

$unicodeChar = '\u1000';
echo json_decode('"'.$unicodeChar.'"');

Another option would be to use mb_convert_encoding()

echo mb_convert_encoding('&#x1000;', 'UTF-8', 'HTML-ENTITIES');

or make use of the direct mapping between UTF-16BE (big endian) and the Unicode codepoint:

echo mb_convert_encoding("\x10\x00", 'UTF-8', 'UTF-16BE');

Android button background color

No need to be that hardcore.
Try this :

YourButtonObject.setBackground(0xff99cc00);

Why can't DateTime.Parse parse UTC date

To correctly parse the string given in the question without changing it, use the following:

using System.Globalization;

string dateString = "Tue, 1 Jan 2008 00:00:00 UTC";
DateTime parsedDate = DateTime.ParseExact(dateString, "ddd, d MMM yyyy hh:mm:ss UTC", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal);

This implementation uses a string to specify the exact format of the date string that is being parsed. The DateTimeStyles parameter is used to specify that the given string is a coordinated universal time string.

Send data from javascript to a mysql database

The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.

So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net

If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.

http://api.jquery.com/jQuery.ajax/

C#: Waiting for all threads to complete

I still think using Join is simpler. Record the expected completion time (as Now+timeout), then, in a loop, do

if(!thread.Join(End-now))
    throw new NotFinishedInTime();

What's the difference between 'git merge' and 'git rebase'?

Suppose originally there were 3 commits, A,B,C:

A-B-C

Then developer Dan created commit D, and developer Ed created commit E:

A-B-C-D-E

Obviously, this conflict should be resolved somehow. For this, there are 2 ways:

MERGE:

A-B-C-D-E-M

Both commits D and E are still here, but we create merge commit M that inherits changes from both D and E. However, this creates diamond shape, which many people find very confusing.

REBASE:

A-B-C-D-E-R

We create commit R, which actual file content is identical to that of merge commit M above. But, we get rid of commit E, like it never existed (denoted by dots - vanishing line). Because of this obliteration, E should be local to developer Ed and should have never been pushed to any other repository. Advantage of rebase is that diamond shape is avoided, and history stays nice straight line - most developers love that!

Rails: Adding an index after adding column

For references you can call

rails generate migration AddUserIdColumnToTable user:references

If in the future you need to add a general index you can launch this

rails g migration AddOrdinationNumberToTable ordination_number:integer:index

Generate code:

class AddOrdinationNumberToTable < ActiveRecord::Migration
  def change
   add_column :tables, :ordination_number, :integer
   add_index :tables, :ordination_number, unique: true
  end
end

Read String line by line

Using Apache Commons IOUtils you can do this nicely via

List<String> lines = IOUtils.readLines(new StringReader(string));

It's not doing anything clever, but it's nice and compact. It'll handle streams as well, and you can get a LineIterator too if you prefer.

Homebrew: Could not symlink, /usr/local/bin is not writable

Following Alex's answer I was able to resolve this issue; seems this to be an issue non specific to the packages being installed but of the permissions of homebrew folders.

sudo chown -R `whoami`:admin /usr/local/bin

For some packages, you may also need to do this to /usr/local/share or /usr/local/opt:

sudo chown -R `whoami`:admin /usr/local/share
sudo chown -R `whoami`:admin /usr/local/opt

How to send a html email with the bash command "sendmail"?

I understand you asked for sendmail but why not use the default mail? It can easily send html emails.

Works on: RHEL 5.10/6.x & CentOS 5.8

Example:

cat ~/campaigns/release-status.html | mail -s "$(echo -e "Release Status [Green]\nContent-Type: text/html")" [email protected] -v

CodeShare: http://www.codeshare.io/8udx5

Dynamically load a function from a DLL

LoadLibrary does not do what you think it does. It loads the DLL into the memory of the current process, but it does not magically import functions defined in it! This wouldn't be possible, as function calls are resolved by the linker at compile time while LoadLibrary is called at runtime (remember that C++ is a statically typed language).

You need a separate WinAPI function to get the address of dynamically loaded functions: GetProcAddress.

Example

#include <windows.h>
#include <iostream>

/* Define a function pointer for our imported
 * function.
 * This reads as "introduce the new type f_funci as the type: 
 *                pointer to a function returning an int and 
 *                taking no arguments.
 *
 * Make sure to use matching calling convention (__cdecl, __stdcall, ...)
 * with the exported function. __stdcall is the convention used by the WinAPI
 */
typedef int (__stdcall *f_funci)();

int main()
{
  HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\Documents and Settings\\User\\Desktop\\test.dll");

  if (!hGetProcIDDLL) {
    std::cout << "could not load the dynamic library" << std::endl;
    return EXIT_FAILURE;
  }

  // resolve function address here
  f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "funci");
  if (!funci) {
    std::cout << "could not locate the function" << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "funci() returned " << funci() << std::endl;

  return EXIT_SUCCESS;
}

Also, you should export your function from the DLL correctly. This can be done like this:

int __declspec(dllexport) __stdcall funci() {
   // ...
}

As Lundin notes, it's good practice to free the handle to the library if you don't need them it longer. This will cause it to get unloaded if no other process still holds a handle to the same DLL.

How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

The top answers in this question may be misleading in some cases. Imagine that the file, whose absolute path you want to find, is in the $PATH variable:

# node is in $PATH variable
type -P node
# /home/user/.asdf/shims/node
cd /tmp
touch node
readlink -e node
# /tmp/node
readlink -m node
# /tmp/node
readlink -f node
# /tmp/node
echo "$(cd "$(dirname "node")"; pwd -P)/$(basename "node")"
# /tmp/node
realpath node
# /tmp/node
realpath -e node
# /tmp/node

# Now let's say that for some reason node does not exist in current directory
rm node
readlink -e node
# <nothing printed>
readlink -m node    
# /tmp/node         # Note: /tmp/node does not exist, but is printed
readlink -f node
# /tmp/node         # Note: /tmp/node does not exist, but is printed
echo "$(cd "$(dirname "node")"; pwd -P)/$(basename "node")"
# /tmp/node         # Note: /tmp/node does not exist, but is printed
realpath node
# /tmp/node         # Note: /tmp/node does not exist, but is printed
realpath -e node
# realpath: node: No such file or directory

Based on the above I can conclude that: realpath -e and readlink -e can be used for finding the absolute path of a file, that we expect to exist in current directory, without result being affected by the $PATH variable. The only difference is that realpath outputs to stderr, but both will return error code if file is not found:

cd /tmp
rm node
realpath -e node ; echo $?
# realpath: node: No such file or directory
# 1
readlink -e node ; echo $?
# 1

Now in case you want the absolute path a of a file that exists in $PATH, the following command would be suitable, independently on whether a file with same name exists in current dir.

type -P example.txt
# /path/to/example.txt

# Or if you want to follow links
readlink -e $(type -P example.txt)
# /originalpath/to/example.txt

# If the file you are looking for is an executable (and wrap again through `readlink -e` for following links )
which executablefile
# /opt/bin/executablefile

And a, fallback to $PATH if missing, example:

cd /tmp
touch node
echo $(readlink -e node || type -P node)
# /tmp/node
rm node
echo $(readlink -e node || type -P node)
# /home/user/.asdf/shims/node

Practical uses of different data structures

I am in the same boat as you do. I need to study for tech interviews, but memorizing a list is not really helpful. If you have 3-4 hours to spare, and want to do a deeper dive, I recommend checking out

mycodeschool
I’ve looked on Coursera and other resources such as blogs and textbooks, but I find them either not comprehensive enough or at the other end of the spectrum, too dense with prerequisite computer science terminologies.

The dude in the video have a bunch of lectures on data structures. Don’t mind the silly drawings, or the slight accent at all. You need to understand not just which data structure to select, but some other points to consider when people think about data structures:

  • pros and cons of the common data structures
  • why each data structure exist
  • how it actually work in the memory
  • specific questions/exercises and deciding which structure to use for maximum efficiency
  • lucid Big 0 explanation

I also posted notes on github if you are interested.

Google MAP API v3: Center & Zoom on displayed markers

for center and auto zoom on display markers

// map: an instance of google.maps.Map object

// latlng_points_array: an array of google.maps.LatLng objects

var latlngbounds = new google.maps.LatLngBounds( );

    for ( var i = 0; i < latlng_points_array.length; i++ ) {
        latlngbounds.extend( latlng_points_array[i] );
    }

map.fitBounds( latlngbounds );

Angular 5, HTML, boolean on checkbox is checked

When you have a copy of an object the [checked] attribute might not work, in that case, you can use (change) in this way:

        <input type="checkbox" [checked]="item.selected" (change)="item.selected = !item.selected">

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

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

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

What does iterator->second mean?

I'm sure you know that a std::vector<X> stores a whole bunch of X objects, right? But if you have a std::map<X, Y>, what it actually stores is a whole bunch of std::pair<const X, Y>s. That's exactly what a map is - it pairs together the keys and the associated values.

When you iterate over a std::map, you're iterating over all of these std::pairs. When you dereference one of these iterators, you get a std::pair containing the key and its associated value.

std::map<std::string, int> m = /* fill it */;
auto it = m.begin();

Here, if you now do *it, you will get the the std::pair for the first element in the map.

Now the type std::pair gives you access to its elements through two members: first and second. So if you have a std::pair<X, Y> called p, p.first is an X object and p.second is a Y object.

So now you know that dereferencing a std::map iterator gives you a std::pair, you can then access its elements with first and second. For example, (*it).first will give you the key and (*it).second will give you the value. These are equivalent to it->first and it->second.

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

Try to change where Member class

public function users() {
    return $this->hasOne('User');
} 

return $this->belongsTo('User');

/exclude in xcopy just for a file type

The /EXCLUDE: argument expects a file containing a list of excluded files.

So create a file called excludedfileslist.txt containing:

.cs\

Then a command like this:

xcopy /r /d /i /s /y /exclude:excludedfileslist.txt C:\dev\apan C:\web\apan

Alternatively you could use Robocopy, but would require installing / copying a robocopy.exe to the machines.

Update

An anonymous comment edit which simply stated "This Solution exclude also css file!"

This is true creating a excludedfileslist.txt file contain just:

.cs

(note no backslash on the end)

Will also exclude all of the following:

  • file1.cs
  • file2.css
  • dir1.cs\file3.txt
  • dir2\anyfile.cs.something.txt

Sometimes people don't read or understand the XCOPY command's help, here is an item I would like to highlight:

Using /exclude

  • List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.

As the example states it excludes "all files with the .obj extension" but it doesn't state that it also excludes files or directories named file1.obj.tmp or dir.obj.output\example2.txt.

There is a way around .css files being excluded also, change the excludedfileslist.txt file to contain just:

.cs\

(note the backslash on the end).

Here is a complete test sequence for your reference:

C:\test1>ver

Microsoft Windows [Version 6.1.7601]

C:\test1>md src
C:\test1>md dst
C:\test1>md src\dir1
C:\test1>md src\dir2.cs
C:\test1>echo "file contents" > src\file1.cs
C:\test1>echo "file contents" > src\file2.css
C:\test1>echo "file contents" > src\dir1\file3.txt
C:\test1>echo "file contents" > src\dir1\file4.cs.txt
C:\test1>echo "file contents" > src\dir2.cs\file5.txt

C:\test1>xcopy /r /i /s /y .\src .\dst
.\src\file1.cs
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
.\src\dir2.cs\file5.txt
5 File(s) copied

C:\test1>echo .cs > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\dir1\file3.txt
1 File(s) copied

C:\test1>echo .cs\ > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
3 File(s) copied

This test was completed on a Windows 7 command line and retested on Windows 10 "10.0.14393".

Note that the last example does exclude .\src\dir2.cs\file5.txt which may or may not be unexpected for you.

Image inside div has extra space below the image

I just added float:left to div and it worked

How do I manage MongoDB connections in a Node.js web application?

I have implemented below code in my project to implement connection pooling in my code so it will create a minimum connection in my project and reuse available connection

/* Mongo.js*/

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/yourdatabasename"; 
var assert = require('assert');

var connection=[];
// Create the database connection
establishConnection = function(callback){

                MongoClient.connect(url, { poolSize: 10 },function(err, db) {
                    assert.equal(null, err);

                        connection = db
                        if(typeof callback === 'function' && callback())
                            callback(connection)

                    }

                )



}

function getconnection(){
    return connection
}

module.exports = {

    establishConnection:establishConnection,
    getconnection:getconnection
}

/*app.js*/
// establish one connection with all other routes will use.
var db = require('./routes/mongo')

db.establishConnection();

//you can also call with callback if you wanna create any collection at starting
/*
db.establishConnection(function(conn){
  conn.createCollection("collectionName", function(err, res) {
    if (err) throw err;
    console.log("Collection created!");
  });
};
*/

// anyother route.js

var db = require('./mongo')

router.get('/', function(req, res, next) {
    var connection = db.getconnection()
    res.send("Hello");

});

Check if property has attribute

If you are using .NET 3.5 you might try with Expression trees. It is safer than reflection:

class CustomAttribute : Attribute { }

class Program
{
    [Custom]
    public int Id { get; set; }

    static void Main()
    {
        Expression<Func<Program, int>> expression = p => p.Id;
        var memberExpression = (MemberExpression)expression.Body;
        bool hasCustomAttribute = memberExpression
            .Member
            .GetCustomAttributes(typeof(CustomAttribute), false).Length > 0;
    }
}

Make Bootstrap's Carousel both center AND responsive?

None of the above solutions worked for me. It's possible that there were some other styles conflicting.

For myself, the following worked, hopefully it may help someone else. I'm using bootstrap 4.

.carousel-inner img {       
   display:block;
   height: auto; 
   max-width: 100%;
}

Cannot execute RUN mkdir in a Dockerfile

The problem is that /var/www doesn't exist either, and mkdir isn't recursive by default -- it expects the immediate parent directory to exist.

Use:

mkdir -p /var/www/app

...or install a package that creates a /var/www prior to reaching this point in your Dockerfile.

Should methods in a Java interface be declared with or without a public access modifier?

I prefer skipping it, I read somewhere that interfaces are by default, public and abstract.

To my surprise the book - Head First Design Patterns, is using public with interface declaration and interface methods... that made me rethink once again and I landed up on this post.

Anyways, I think redundant information should be ignored.

Total memory used by Python process?

import os, win32api, win32con, win32process
han = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION|win32con.PROCESS_VM_READ, 0, os.getpid())
process_memory = int(win32process.GetProcessMemoryInfo(han)['WorkingSetSize'])

Getting indices of True values in a boolean list

TL; DR: use np.where as it is the fastest option. Your options are np.where, itertools.compress, and list comprehension.

See the detailed comparison below, where it can be seen np.where outperforms both itertools.compress and also list comprehension.

>>> from itertools import compress
>>> import numpy as np
>>> t = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]`
>>> t = 1000*t
  • Method 1: Using list comprehension
>>> %timeit [i for i, x in enumerate(t) if x]
457 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
  • Method 2: Using itertools.compress
>>> %timeit list(compress(range(len(t)), t))
210 µs ± 704 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
  • Method 3 (the fastest method): Using numpy.where
>>> %timeit np.where(t)
179 µs ± 593 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Reset IntelliJ UI to Default

From the main menu, select File | Manage IDE Settings | Restore Default Settings.

Alternatively, press Shift twice and type Restore default settings

How to secure an ASP.NET Web API

Have you tried DevDefined.OAuth?

I have used it to secure my WebApi with 2-Legged OAuth. I have also successfully tested it with PHP clients.

It's quite easy to add support for OAuth using this library. Here's how you can implement the provider for ASP.NET MVC Web API:

1) Get the source code of DevDefined.OAuth: https://github.com/bittercoder/DevDefined.OAuth - the newest version allows for OAuthContextBuilder extensibility.

2) Build the library and reference it in your Web API project.

3) Create a custom context builder to support building a context from HttpRequestMessage:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http;
using System.Web;

using DevDefined.OAuth.Framework;

public class WebApiOAuthContextBuilder : OAuthContextBuilder
{
    public WebApiOAuthContextBuilder()
        : base(UriAdjuster)
    {
    }

    public IOAuthContext FromHttpRequest(HttpRequestMessage request)
    {
        var context = new OAuthContext
            {
                RawUri = this.CleanUri(request.RequestUri), 
                Cookies = this.CollectCookies(request), 
                Headers = ExtractHeaders(request), 
                RequestMethod = request.Method.ToString(), 
                QueryParameters = request.GetQueryNameValuePairs()
                    .ToNameValueCollection(), 
            };

        if (request.Content != null)
        {
            var contentResult = request.Content.ReadAsByteArrayAsync();
            context.RawContent = contentResult.Result;

            try
            {
                // the following line can result in a NullReferenceException
                var contentType = 
                    request.Content.Headers.ContentType.MediaType;
                context.RawContentType = contentType;

                if (contentType.ToLower()
                    .Contains("application/x-www-form-urlencoded"))
                {
                    var stringContentResult = request.Content
                        .ReadAsStringAsync();
                    context.FormEncodedParameters = 
                        HttpUtility.ParseQueryString(stringContentResult.Result);
                }
            }
            catch (NullReferenceException)
            {
            }
        }

        this.ParseAuthorizationHeader(context.Headers, context);

        return context;
    }

    protected static NameValueCollection ExtractHeaders(
        HttpRequestMessage request)
    {
        var result = new NameValueCollection();

        foreach (var header in request.Headers)
        {
            var values = header.Value.ToArray();
            var value = string.Empty;

            if (values.Length > 0)
            {
                value = values[0];
            }

            result.Add(header.Key, value);
        }

        return result;
    }

    protected NameValueCollection CollectCookies(
        HttpRequestMessage request)
    {
        IEnumerable<string> values;

        if (!request.Headers.TryGetValues("Set-Cookie", out values))
        {
            return new NameValueCollection();
        }

        var header = values.FirstOrDefault();

        return this.CollectCookiesFromHeaderString(header);
    }

    /// <summary>
    /// Adjust the URI to match the RFC specification (no query string!!).
    /// </summary>
    /// <param name="uri">
    /// The original URI. 
    /// </param>
    /// <returns>
    /// The adjusted URI. 
    /// </returns>
    private static Uri UriAdjuster(Uri uri)
    {
        return
            new Uri(
                string.Format(
                    "{0}://{1}{2}{3}", 
                    uri.Scheme, 
                    uri.Host, 
                    uri.IsDefaultPort ?
                        string.Empty :
                        string.Format(":{0}", uri.Port), 
                    uri.AbsolutePath));
    }
}

4) Use this tutorial for creating an OAuth provider: http://code.google.com/p/devdefined-tools/wiki/OAuthProvider. In the last step (Accessing Protected Resource Example) you can use this code in your AuthorizationFilterAttribute attribute:

public override void OnAuthorization(HttpActionContext actionContext)
{
    // the only change I made is use the custom context builder from step 3:
    OAuthContext context = 
        new WebApiOAuthContextBuilder().FromHttpRequest(actionContext.Request);

    try
    {
        provider.AccessProtectedResourceRequest(context);

        // do nothing here
    }
    catch (OAuthException authEx)
    {
        // the OAuthException's Report property is of the type "OAuthProblemReport", it's ToString()
        // implementation is overloaded to return a problem report string as per
        // the error reporting OAuth extension: http://wiki.oauth.net/ProblemReporting
        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
            {
               RequestMessage = request, ReasonPhrase = authEx.Report.ToString()
            };
    }
}

I have implemented my own provider so I haven't tested the above code (except of course the WebApiOAuthContextBuilder which I'm using in my provider) but it should work fine.

How can I list (ls) the 5 last modified files in a directory?

ls -t list files by creation time not last modified time. Use ls -ltc if you want to list files by last modified time from last to first(top to bottom). Thus to list the last n: ls -ltc | head ${n}

Pass array to where in Codeigniter Active Record

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate,

$this->db->where_in()
ex :  $this->db->where_in('id', array('1','2','3'));

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate

$this->db->or_where_in()
ex :  $this->db->where_in('id', array('1','2','3'));

Reading a single char in Java

i found this way worked nice:

    {
    char [] a;
    String temp;
    Scanner keyboard = new Scanner(System.in);
    System.out.println("please give the first integer :");
    temp=keyboard.next();
    a=temp.toCharArray();
    }

you can also get individual one with String.charAt()

How to show progress dialog in Android?

        final ProgressDialog progDailog = ProgressDialog.show(Inishlog.this, contentTitle, "even geduld aub....", true);//please wait....

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Barcode_edit.setText("");
                showAlert("Product detail saved.");


            }

        };

        new Thread() {
            public void run() {
                try {
         } catch (Exception e) {

                }
                handler.sendEmptyMessage(0);
                progDailog.dismiss();
            }
        }.start();

Return array in a function

template<typename T, size_t N>
using ARR_REF = T (&)[N];

template <typename T, size_t N>
ARR_REF<T,N> ArraySizeHelper(ARR_REF<T,N> arr);

#define arraysize(arr) sizeof(ArraySizeHelper(arr))

JSON Stringify changes time of date because of UTC

Recently I have run into the same issue. And it was resolved using the following code:

x = new Date();
let hoursDiff = x.getHours() - x.getTimezoneOffset() / 60;
let minutesDiff = (x.getHours() - x.getTimezoneOffset()) % 60;
x.setHours(hoursDiff);
x.setMinutes(minutesDiff);

How can JavaScript save to a local file?

Based on http://html5-demos.appspot.com/static/a.download.html:

var fileContent = "My epic novel that I don't want to lose.";
var bb = new Blob([fileContent ], { type: 'text/plain' });
var a = document.createElement('a');
a.download = 'download.txt';
a.href = window.URL.createObjectURL(bb);
a.click();

Modified the original fiddle: http://jsfiddle.net/9av2mfjx/

Case objects vs Enumerations in Scala

For those still looking how to get GatesDa's answer to work: You can just reference the case object after declaring it to instantiate it:

trait Enum[A] {
  trait Value { self: A =>
    _values :+= this
  }
  private var _values = List.empty[A]
  def values = _values
}

sealed trait Currency extends Currency.Value
object Currency extends Enum[Currency] {
  case object EUR extends Currency; 
  EUR //THIS IS ONLY CHANGE
  case object GBP extends Currency; GBP //Inline looks better
}

Deep-Learning Nan loss reasons

The reason for nan, inf or -inf often comes from the fact that division by 0.0 in TensorFlow doesn't result in a division by zero exception. It could result in a nan, inf or -inf "value". In your training data you might have 0.0 and thus in your loss function it could happen that you perform a division by 0.0.

a = tf.constant([2., 0., -2.])
b = tf.constant([0., 0., 0.])
c = tf.constant([1., 1., 1.])
print((a / b) + c)

Output is the following tensor:

tf.Tensor([ inf  nan -inf], shape=(3,), dtype=float32)

Adding a small eplison (e.g., 1e-5) often does the trick. Additionally, since TensorFlow 2 the opteration tf.math.division_no_nan is defined.

Dynamically Changing log4j log level

You can use following code snippet

((ch.qos.logback.classic.Logger)LoggerFactory.getLogger(packageName)).setLevel(ch.qos.logback.classic.Level.toLevel(logLevel));

Disabling Chrome cache for website development

Actually if you don't mind using the bandwidth it is more secure for multiple reasons to disable caching and advised by many security sites.

Chromium shouldn't be arrogant enough to make decisions and enforce settings on users.

You can disable the cache on UNIX with --disk-cache-dir=/dev/null.

As this is unexpected crashes may happen but if they do then that will clearly point to a more severe bug which should be fixed in any case.

Why es6 react component works only with "export default"?

Add { } while importing and exporting: export { ... }; | import { ... } from './Template';

exportimport { ... } from './Template'

export defaultimport ... from './Template'


Here is a working example:

// ExportExample.js
import React from "react";

function DefaultExport() {
  return "This is the default export";
}

function Export1() {
  return "Export without default 1";
}

function Export2() {
  return "Export without default 2";
}

export default DefaultExport;
export { Export1, Export2 };

// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";

export default function App() {
  return (
    <>
      <strong>
        <DefaultExport />
      </strong>
      <br />
      <Export1 />
      <br />
      <Export2 />
    </>
  );
}

??Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark

exceeds the list view threshold 5000 items in Sharepoint 2010

The setting for the list throttle

  • Open the SharePoint Central Administration,
  • go to Application Management --> Manage Web Applications
  • Click to select the web application that hosts your list (eg. SharePoint - 80)
  • At the Ribbon, select the General Settings and select Resource Throttling
  • Then, you can see the 5000 List View Threshold limit and you can edit the value you want.
  • Click OK to save it.

For addtional reading: http://blogs.msdn.com/b/dinaayoub/archive/2010/04/22/sharepoint-2010-how-to-change-the-list-view-threshold.aspx

/bin/sh: apt-get: not found

If you are looking inside dockerfile while creating image, add this line:

RUN apk add --update yourPackageName

How to format column to number format in Excel sheet?

If your 13 digit "number" is really text, that is you don't intend to do any math on it, you can precede it with an apostrophe

Sheet3.Range("c" & k).Value = "'" & Sheet2.Range("c" & i).Value

But I don't see how a 13 digit number would ever get past the If statement because it would always be greater than 1000. Here's an alternate version

Sub CommandClick()

    Dim rCell As Range
    Dim rNext As Range

    For Each rCell In Sheet2.Range("C1:C30000").Cells
        If rCell.Value >= 100 And rCell.Value < 1000 Then
            Set rNext = Sheet3.Cells(Sheet3.Rows.Count, 1).End(xlUp).Offset(1, 0)
            rNext.Resize(1, 3).Value = rCell.Offset(0, -2).Resize(1, 3).Value
        End If
    Next rCell

End Sub

JQuery datepicker language

You need the following line:

<script src="../jquery/development-bundle/ui/i18n/jquery.ui.datepicker-sv.js"></script>

Adjust the path depending on where you put the jquery-files.

How to create a label inside an <input> element?

If you're using HTML5, you can use the placeholder attribute.

<input type="text" name="user" placeholder="Username">

Java: is there a map function?

Since Java 8, there are some standard options to do this in JDK:

Collection<E> in = ...
Object[] mapped = in.stream().map(e -> doMap(e)).toArray();
// or
List<E> mapped = in.stream().map(e -> doMap(e)).collect(Collectors.toList());

See java.util.Collection.stream() and java.util.stream.Collectors.toList().

PHP preg_replace special characters

do this in two steps:

  1. replace not letter characters with this regex:

    [\/\&%#\$]

  2. replace quotes with this regex:

    [\"\']

and use preg_replace:

$stringWithoutNonLetterCharacters = preg_replace("/[\/\&%#\$]/", "_", $yourString);
$stringWithQuotesReplacedWithSpaces = preg_replace("/[\"\']/", " ", $stringWithoutNonLetterCharacters);

Get value from JToken that may not exist (best practices)

You can simply typecast, and it will do the conversion for you, e.g.

var with = (double?) jToken[key] ?? 100;

It will automatically return null if said key is not present in the object, so there's no need to test for it.

how to check if List<T> element contains an item with a Particular Property Value

You don't actually need LINQ for this because List<T> provides a method that does exactly what you want: Find.

Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List<T>.

Example code:

PricePublicModel result = pricePublicList.Find(x => x.Size == 200);

How to cut an entire line in vim and paste it?

Let's say that you wanted to cut the line bbb and paste it under the line ---

Before:

aaa
bbb
---

After:

aaa
---
bbb
  1. Put your cursor on the line bbb
  2. Press d+d
  3. Put your cursor on the line ---
  4. Press p

enter image description here

How to move all HTML element children to another parent using JavaScript?

Modern way:

newParent.append(...oldParent.childNodes);
  1. .append is the replacement for .appendChild. The main difference is that it accepts multiple nodes at once and even plain strings, like .append('hello!')
  2. oldParent.childNodes is iterable so it can be spread with ... to become multiple parameters of .append()

Compatibility tables of both (in short: Edge 17+, Safari 10+):

How to symbolicate crash log Xcode?

If you have the .dSYM and the .crash file in the same sub-folder, these are the steps you can take:

  1. Looking at the backtrace in the .crash file, note the name of the binary image in the second column, and the address in the third column (e.g. 0x00000001000effdc in the example below).
  2. Just under the backtrace, in the "Binary Images" section, note the image name, the architecture (e.g. arm64) and load address (0x1000e4000 in the example below) of the binary image (e.g. TheElements).
  3. Execute the following:

$ atos -arch arm64 -o TheElements.app.dSYM/Contents/Resources/DWARF/TheElements -l 0x1000e4000 0x00000001000effdc -[AtomicElementViewController myTransitionDidStop:finished:context:]

Authoritative source: https://developer.apple.com/library/content/technotes/tn2151/_index.html#//apple_ref/doc/uid/DTS40008184-CH1-SYMBOLICATE_WITH_ATOS

Saving a select count(*) value to an integer (SQL Server)

[update] -- Well, my own foolishness provides the answer to this one. As it turns out, I was deleting the records from myTable before running the select COUNT statement.

How did I do that and not notice? Glad you asked. I've been testing a sql unit testing platform (tsqlunit, if you're interested) and as part of one of the tests I ran a truncate table statement, then the above. After the unit test is over everything is rolled back, and records are back in myTable. That's why I got a record count outside of my tests.

Sorry everyone...thanks for your help.

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

Adding to @Greg Hewgill answer: if you want to be able to match both date-time and only date, you can make the "time" part of the regex optional:

(\d{4})-(\d{2})-(\d{2})( (\d{2}):(\d{2}):(\d{2}))?

this way you will match both 2008-09-01 12:35:42 and 2008-09-01

How to revert a merge commit that's already pushed to remote branch?

This is a very old thread, but I am missing another in my opinion convenient solution:

I never revert a merge. I just create another branch from the revision where everything was ok and then cherry pick everything that needs to picked from the old branch which was added in between.

So, if the GIT history is like this:

  • d
  • c
  • b <<< the merge
  • a
  • ...

I create a new branch from a, cherry pick c and d and then the new branch is clear from b. I can ever decide to do the merge of "b" in my new branch again. The old branch becomes deprecated and will be deleted if "b" is not necessary anymore or still in another (feature/hotfix) branch.

The only problem is now one of the very hardest things in computer science: How do you name the new branch? ;)

Ok, if you failed esp. in devel, you create newdevel as mentioned above, delete old devel and rename newdevel to devel. Mission accomplished. You can now merge the changes again when you want. It is like never merged before....

Using sed to split a string with a delimiter

To split a string with a delimiter with GNU sed you say:

sed 's/delimiter/\n/g'     # GNU sed

For example, to split using : as a delimiter:

$ sed 's/:/\n/g' <<< "he:llo:you"
he
llo
you

Or with a non-GNU sed:

$ sed $'s/:/\\\n/g' <<< "he:llo:you"
he
llo
you

In this particular case, you missed the g after the substitution. Hence, it is just done once. See:

$ echo "string1:string2:string3:string4:string5" | sed s/:/\\n/g
string1
string2
string3
string4
string5

g stands for global and means that the substitution has to be done globally, that is, for any occurrence. See that the default is 1 and if you put for example 2, it is done 2 times, etc.

All together, in your case you would need to use:

sed 's/:/\\n/g' ~/Desktop/myfile.txt

Note that you can directly use the sed ... file syntax, instead of unnecessary piping: cat file | sed.

What do I do when my program crashes with exception 0xc0000005 at address 0?

Exception code 0xc0000005 is an Access Violation. An AV at fault offset 0x00000000 means that something in your service's code is accessing a nil pointer. You will just have to debug the service while it is running to find out what it is accessing. If you cannot run it inside a debugger, then at least install a third-party exception logger framework, such as EurekaLog or MadExcept, to find out what your service was doing at the time of the AV.

Insert php variable in a href

in php

echo '<a href="' . $folder_path . '">Link text</a>';

or

<a href="<?=$folder_path?>">Link text</a>;

or

<a href="<?php echo $folder_path ?>">Link text</a>;

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

Maybe useful for anyone else running into this issue: When setting the port on the properties:

props.put("mail.smtp.port", smtpPort);

..make sure to use a string object. Using a numeric (ie Long) object will cause this statement to seemingly have no effect.

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Installing mysql-python on Centos

Step 1 - Install package

# yum install MySQL-python
Loaded plugins: auto-update-debuginfo, langpacks, presto, refresh-packagekit
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package MySQL-python.i686 0:1.2.3-3.fc15 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package              Arch         Version                 Repository      Size
================================================================================
Installing:
 MySQL-python         i686         1.2.3-3.fc15            fedora          78 k

Transaction Summary
================================================================================
Install       1 Package(s)

Total download size: 78 k
Installed size: 220 k
Is this ok [y/N]: y
Downloading Packages:
Setting up and reading Presto delta metadata
Processing delta metadata
Package(s) data still to download: 78 k
MySQL-python-1.2.3-3.fc15.i686.rpm                       |  78 kB     00:00     
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : MySQL-python-1.2.3-3.fc15.i686                               1/1 

Installed:
  MySQL-python.i686 0:1.2.3-3.fc15                                              

Complete!

Step 2 - Test working

import MySQLdb
db = MySQLdb.connect("localhost","myusername","mypassword","mydb" )
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()    
print "Database version : %s " % data    
db.close()

Ouput:

Database version : 5.5.20 

See full command of running/stopped container in Docker

TL-DR

docker ps --no-trunc and docker inspect CONTAINER provide the entrypoint executed to start the container, along the command passed to, but that may miss some parts such as ${ANY_VAR} because container environment variables are not printed as resolved.

To overcome that, docker inspect CONTAINER has an advantage because it also allow to retrieve separately env variables and their values defined in the container from the Config.Env property.

docker ps and docker inspect provide information about the executed entrypoint and its command. Often, that is a wrapper entrypoint script (.sh) and not the "real" program started by the container. To get information on that, requesting process information with ps or /proc/1/cmdline help.


1) docker ps --no-trunc

It prints the entrypoint and the command executed for all running containers. While it prints the command passed to the entrypoint (if we pass that), it doesn't show value of docker env variables (such as $FOO or ${FOO}).
If our containers use env variables, it may be not enough.

For example, run an alpine container :

docker run --name alpine-example -e MY_VAR=/var alpine:latest sh -c 'ls $MY_VAR'

When use docker -ps such as :

docker ps -a --filter name=alpine-example --no-trunc

It prints :

CONTAINER ID           IMAGE               COMMAND                CREATED             STATUS                     PORTS               NAMES
5b064a6de6d8417...   alpine:latest       "sh -c 'ls $MY_VAR'"   2 minutes ago       Exited (0) 2 minutes ago                       alpine-example

We see the command passed to the entrypoint : sh -c 'ls $MY_VAR' but $MY_VAR is indeed not resolved.

2) docker inspect CONTAINER

When we inspect the alpine-example container :

docker inspect alpine-example | grep -4 Cmd

The command is also there but we don't still see the env variable value :

        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ],

In fact, we could not see interpolated variables with these docker commands.
While as a trade-off, we could display separately both command and env variables for a container with docker inspect :

docker inspect  alpine-example  | grep -4 -E "Cmd|Env"

That prints :

        "Env": [
            "MY_VAR=/var",
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        ],
        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ]

A more docker way would be to use the --format flag of docker inspect that allows to specify JSON attributes to render :

docker inspect --format '{{.Name}} {{.Config.Cmd}}  {{ (.Config.Env) }}'  alpine-example

That outputs :

/alpine-example [sh -c ls $MY_VAR]  [MY_VAR=/var PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]

3) Retrieve the started process from the container itself for running containers

The entrypoint and command executed by docker may be helpful but in some cases, it is not enough because that is "only" a wrapper entrypoint script (.sh) that is responsible to start the real/core process.
For example when I run a Nexus container, the command executed and shown to run the container is "sh -c ${SONATYPE_DIR}/start-nexus-repository-manager.sh".
For PostgreSQL that is "docker-entrypoint.sh postgres".

To get more information, we could execute on a running container docker exec CONTAINER ps aux.
It may print other processes that may not interest us.
To narrow to the initial process launched by the entrypoint, we could do :

docker exec CONTAINER ps -1

I specify 1 because the process executed by the entrypoint is generally the one with the 1 id.

Without ps, we could still find the information in /proc/1/cmdline (in most of Linux distros but not all). For example :

docker exec CONTAINER cat /proc/1/cmdline | sed -e "s/\x00/ /g"; echo    

If we have access to the docker host that started the container, another alternative to get the full command of the process executed by the entrypoint is : : execute ps -PID where PID is the local process created by the Docker daemon to run the container such as :

ps -$(docker container inspect --format '{{.State.Pid}}'  CONTAINER)

User-friendly formatting with docker ps

docker ps --no-trunc is not always easy to read.
Specifying columns to print and in a tabular format may make it better :

docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"

Create an alias may help :

alias dps='docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"'

how to save canvas as png image?

I maybe discovered a better way for not forcing the user to right click and "save image as". Live draw the canvas base64 code into the href of the link and modify it so the download will start automatically. I don't know if it's universally browser compatible, but it should work with the main/new browsers.

var canvas = document.getElementById('your-canvas');
    if (canvas.getContext) {
        var C = canvas.getContext('2d');
    }

$('#your-canvas').mousedown(function(event) {
    // feel free to choose your event ;) 

    // just for example
    // var OFFSET = $(this).offset();
    // var x = event.pageX - OFFSET.left;
    // var y = event.pageY - OFFSET.top;

    // standard data to url
    var imgdata = canvas.toDataURL('image/png');
    // modify the dataUrl so the browser starts downloading it instead of just showing it
    var newdata = imgdata.replace(/^data:image\/png/,'data:application/octet-stream');
    // give the link the values it needs
    $('a.linkwithnewattr').attr('download','your_pic_name.png').attr('href',newdata);

});

You can wrap the <a> around anything you want.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

How to share data between different threads In C# using AOP?

When you start a thread you are executing a method of some chosen class. All attributes of that class are visible.

  Worker myWorker = new Worker( /* arguments */ );

  Thread myThread = new Thread(new ThreadStart(myWorker.doWork));

  myThread.Start();

Your thread is now in the doWork() method and can see any atrributes of myWorker, which may themselves be other objects. Now you just need to be careful to deal with the cases of having several threads all hitting those attributes at the same time.

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

I am getting similar errors recently because recent JDKs (and browsers, and the Linux TLS stack, etc.) refuse to communicate with some servers in my customer's corporate network. The reason of this is that some servers in this network still have SHA-1 certificates.

Please see: https://www.entrust.com/understanding-sha-1-vulnerabilities-ssl-longer-secure/ https://blog.qualys.com/ssllabs/2014/09/09/sha1-deprecation-what-you-need-to-know

If this would be your current case (recent JDK vs deprecated certificate encription) then your best move is to update your network to the proper encription technology.

In case that you should provide a temporal solution for that, please see another answers to have an idea about how to make your JDK trust or distrust certain encription algorithms:

How to force java server to accept only tls 1.2 and reject tls 1.0 and tls 1.1 connections

Anyway I insist that, in case that I have guessed properly your problem, this is not a good solution to the problem and that your network admin should consider removing these deprecated certificates and get a new one.

How to determine if a list of polygon points are in clockwise order?

My C# / LINQ solution is based on the cross product advice of @charlesbretana is below. You can specify a reference normal for the winding. It should work as long as the curve is mostly in the plane defined by the up vector.

using System.Collections.Generic;
using System.Linq;
using System.Numerics;

namespace SolidworksAddinFramework.Geometry
{
    public static class PlanePolygon
    {
        /// <summary>
        /// Assumes that polygon is closed, ie first and last points are the same
        /// </summary>
       public static bool Orientation
           (this IEnumerable<Vector3> polygon, Vector3 up)
        {
            var sum = polygon
                .Buffer(2, 1) // from Interactive Extensions Nuget Pkg
                .Where(b => b.Count == 2)
                .Aggregate
                  ( Vector3.Zero
                  , (p, b) => p + Vector3.Cross(b[0], b[1])
                                  /b[0].Length()/b[1].Length());

            return Vector3.Dot(up, sum) > 0;

        } 

    }
}

with a unit test

namespace SolidworksAddinFramework.Spec.Geometry
{
    public class PlanePolygonSpec
    {
        [Fact]
        public void OrientationShouldWork()
        {

            var points = Sequences.LinSpace(0, Math.PI*2, 100)
                .Select(t => new Vector3((float) Math.Cos(t), (float) Math.Sin(t), 0))
                .ToList();

            points.Orientation(Vector3.UnitZ).Should().BeTrue();
            points.Reverse();
            points.Orientation(Vector3.UnitZ).Should().BeFalse();



        } 
    }
}

Weird PHP error: 'Can't use function return value in write context'

if (isset($_POST('sms_code') == TRUE ) {

change this line to

if (isset($_POST['sms_code']) == TRUE ) {

You are using parentheseis () for $_POST but you wanted square brackets []

:)

OR

if (isset($_POST['sms_code']) && $_POST['sms_code']) { 
//this lets in this block only if $_POST['sms_code'] has some value 

Clear and reset form input fields

To clear your form, admitted that your form's elements values are saved in your state, you can map through your state like that :

  // clear all your form
  Object.keys(this.state).map((key, index) => {
      this.setState({[key] : ""});
   });

If your form is among other fields, you can simply insert them in a particular field of the state like that:

 state={ 
        form: {
        name:"",
        email:""}
      }

      // handle set in nested objects
      handleChange = (e) =>{ 
        e.preventDefault(); 

        const newState = Object.assign({}, this.state);
        newState.form[e.target.name] = e.target.value;
        this.setState(newState);
      }

      // submit and clear state in nested object 
      onSubmit = (e) =>{ 
        e.preventDefault(); 

       var form =   Object.assign({}, this.state.form);
       Object.keys(form).map((key, index) => {
          form[key] = "" ;
        });

       this.setState({form})
      } 

CSS body background image fixed to full screen even when zooming in/out

there is another technique

use

background-size:cover

That is it full set of css is

body { 
    background: url('images/body-bg.jpg') no-repeat center center fixed;
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
} 

Latest browsers support the default property.

Eloquent Collection: Counting and Detect Empty

There are several methods given in Laravel for checking results count/check empty/not empty:

$result->isNotEmpty(); // True if result is not empty.
$result->isEmpty(); // True if result is empty.
$result->count(); // Return count of records in result.

Why am I getting the error "connection refused" in Python? (Sockets)

I was being able to ping my connection but was STILL getting the 'connection refused' error. Turns out I was pinging myself! That's what the problem was.

differences in application/json and application/x-www-form-urlencoded

webRequest.ContentType = "application/x-www-form-urlencoded";

  1. Where does application/x-www-form-urlencoded's name come from?

    If you send HTTP GET request, you can use query parameters as follows:

    http://example.com/path/to/page?name=ferret&color=purple

    The content of the fields is encoded as a query string. The application/x-www-form- urlencoded's name come from the previous url query parameter but the query parameters is in where the body of request instead of url.

    The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character

    e.g. field1=value1&field2=value2

  2. It can be simple request called simple - don't trigger a preflight check

    Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

  1. The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}
  1. "application/json" Content-Type is one of the Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

  1. application/json is beginner-friendly. URL encoded arrays can be a nightmare!

Mockito How to mock and assert a thrown exception?

Assert by exception message:

    try {
        MyAgent.getNameByNode("d");
    } catch (Exception e) {
        Assert.assertEquals("Failed to fetch data.", e.getMessage());
    }

Unable to connect to SQL Server instance remotely

I recently upgraded from SQL 2008 R2 to SQL 2012 and had a similar issue. The problem was the firewall, but more specifically the firewall rule for SQL SERVER. The custom rule was pointed to the prior version of SQL Server. Try this, open Windows Firewall>Advanced setting. Find the SQL Server Rule (it may have a custom name). Right-Click and go to properties, then Programs and Services Tab. If Programs-This program is selected, you should browse for the proper version of sqlserver.exe.

Programmatically set left drawable in a TextView

static private Drawable **scaleDrawable**(Drawable drawable, int width, int height) {

    int wi = drawable.getIntrinsicWidth();
    int hi = drawable.getIntrinsicHeight();
    int dimDiff = Math.abs(wi - width) - Math.abs(hi - height);
    float scale = (dimDiff > 0) ? width / (float)wi : height /
            (float)hi;
    Rect bounds = new Rect(0, 0, (int)(scale * wi), (int)(scale * hi));
    drawable.setBounds(bounds);
    return drawable;
}

Python setup.py develop vs install

From the documentation. The develop will not install the package but it will create a .egg-link in the deployment directory back to the project source code directory.

So it's like installing but instead of copying to the site-packages it adds a symbolic link (the .egg-link acts as a multiplatform symbolic link).

That way you can edit the source code and see the changes directly without having to reinstall every time that you make a little change. This is useful when you are the developer of that project hence the name develop. If you are just installing someone else's package you should use install

How to handle click event in Button Column in Datagridview?

You will add button column like this in your dataGridView

        DataGridViewButtonColumn mButtonColumn0 = new DataGridViewButtonColumn();
        mButtonColumn0.Name = "ColumnA";
        mButtonColumn0.Text = "ColumnA";


        if (dataGridView.Columns["ColumnA"] == null)
        {
            dataGridView.Columns.Insert(2, mButtonColumn0);
        }

Then you can add some actions inside cell click event. I found this is easiest way of doing it.

    private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
    {

        int rowIndex = e.RowIndex;
        int columnIndex = e.ColumnIndex;

        if (dataGridView.Rows[rowIndex].Cells[columnIndex].Selected == true && dataGridView.Columns[columnIndex].Name == "ColumnA")
         {
               //.... do any thing here.
         }


    }

I found that Cell Click event is automatically subscribed often. So I did not need this code below. However, if your cell click event is not subscribed, then add this line of code for your dataGridView.

     this.dataGridView.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView_CellClick);

How can I check if a scrollbar is visible?

You can do this using a combination of the Element.scrollHeight and Element.clientHeight attributes.

According to MDN:

The Element.scrollHeight read-only attribute is a measurement of the height of an element's content, including content not visible on the screen due to overflow. The scrollHeight value is equal to the minimum clientHeight the element would require in order to fit all the content in the viewpoint without using a vertical scrollbar. It includes the element padding but not its margin.

And:

The Element.clientHeight read-only property returns the inner height of an element in pixels, including padding but not the horizontal scrollbar height, border, or margin.

clientHeight can be calculated as CSS height + CSS padding - height of horizontal scrollbar (if present).

Therefore, the element will display a scrollbar if the scroll height is greater than the client height, so the answer to your question is:

function scrollbarVisible(element) {
  return element.scrollHeight > element.clientHeight;
}

Sending emails through SMTP with PHPMailer

As far as I can see everything is right with your code. Your error is:

SMTP Error: Could not authenticate.

Which means that the credentials you've sending are rejected by the SMTP server. Make sure the host, port, username and password are good.

If you want to use STARTTLS, try adding:

$mail->SMTPSecure = 'tls';

If you want to use SMTPS (SSL), try adding:

$mail->SMTPSecure = 'ssl';

Keep in mind that:

  • Some SMTP servers can forbid connections from "outsiders".
  • Some SMTP servers don't support SSL (or TLS) connections.

Maybe this example can help (GMail secure SMTP).

[Source]

Difference between acceptance test and functional test?

They are the same thing.

Acceptance testing is performed on the completed system in as identical as possible to the real production/deployement environment before the system is deployed or delivered.

You can do acceptance testing in an automated manner, or manually.

Get file version in PowerShell

I prefer to install the PowerShell Community Extensions and just use the Get-FileVersionInfo function that it provides.

Like so:

Get-FileVersionInfo MyAssembly.dll

with output like:

ProductVersion   FileVersion      FileName
--------------   -----------      --------
1.0.2907.18095   1.0.2907.18095   C:\Path\To\MyAssembly.dll

I've used it against an entire directory of assemblies with great success.

how to change onclick event with jquery?

(2019) I used $('#'+id).removeAttr().off('click').on('click', function(){...});

I tried $('#'+id).off().on(...), but it wouldn't work to reset the onClick attribute every time it was called to be reset.

I use .on('click',function(){...}); to stay away from having to quote block all my javascript functions.

The O.P. could now use:

$(this).removeAttr('onclick').off('click').on('click', function(){ displayCalendar(document.prjectFrm[ia + 'dtSubDate'],'yyyy-mm-dd', this); });

Where this came through for me is when my div was set with the onClick attribute set statically:

<div onclick = '...'>

Otherwise, if I only had a dynamically attached a listener to it, I would have used the $('#'+id).off().on('click', function(){...});.

Without the off('click') my onClick listeners were being appended not replaced.

Count immediate child div elements using jQuery

$("#foo > div") 

selects all divs that are immediate descendants of #foo
once you have the set of children you can either use the size function:

$("#foo > div").size()

or you can use

$("#foo > div").length

Both will return you the same result

What is the difference between Subject and BehaviorSubject?

A BehaviorSubject holds one value. When it is subscribed it emits the value immediately. A Subject doesn't hold a value.

Subject example (with RxJS 5 API):

const subject = new Rx.Subject();
subject.next(1);
subject.subscribe(x => console.log(x));

Console output will be empty

BehaviorSubject example:

const subject = new Rx.BehaviorSubject(0);
subject.next(1);
subject.subscribe(x => console.log(x));

Console output: 1

In addition:

  • BehaviorSubject should be created with an initial value: new Rx.BehaviorSubject(1)
  • Consider ReplaySubject if you want the subject to hold more than one value

How can I pass a parameter to a Java Thread?

There is a simple way of passing parameters into runnables. Code:

public void Function(final type variable) {
    Runnable runnable = new Runnable() {
        public void run() {
            //Code adding here...
        }
    };
    new Thread(runnable).start();
}

Delete a row from a table by id

The parent of the row is not the object you think, this is what I understand from the error.
Try detecting the parent of the row first, then you can be sure what to write into getElementById part of the parent.

How to filter an array from all elements of another array

The solution of Jack Giffin is great but doesn't work for arrays with numbers bigger than 2^32. Below is a refactored, fast version to filter an array based on Jack's solution but it works for 64-bit arrays.

const Math_clz32 = Math.clz32 || ((log, LN2) => x => 31 - log(x >>> 0) / LN2 | 0)(Math.log, Math.LN2);

const filterArrayByAnotherArray = (searchArray, filterArray) => {

    searchArray.sort((a,b) => a > b);
    filterArray.sort((a,b) => a > b);

    let searchArrayLen = searchArray.length, filterArrayLen = filterArray.length;
    let progressiveLinearComplexity = ((searchArrayLen<<1) + filterArrayLen)>>>0
    let binarySearchComplexity = (searchArrayLen * (32-Math_clz32(filterArrayLen-1)))>>>0;

    let i = 0;

    if (progressiveLinearComplexity < binarySearchComplexity) {
      return searchArray.filter(currentValue => {
        while (filterArray[i] < currentValue) i=i+1|0;
        return filterArray[i] !== currentValue;
      });
    }
    else return searchArray.filter(e => binarySearch(filterArray, e) === null);
}

const binarySearch = (sortedArray, elToFind) => {
  let lowIndex = 0;
  let highIndex = sortedArray.length - 1;
  while (lowIndex <= highIndex) {
    let midIndex = Math.floor((lowIndex + highIndex) / 2);
    if (sortedArray[midIndex] == elToFind) return midIndex; 
    else if (sortedArray[midIndex] < elToFind) lowIndex = midIndex + 1;
    else highIndex = midIndex - 1;
  } return null;
}

Passing functions with arguments to another function in Python?

Use functools.partial, not lambdas! And ofc Perform is a useless function, you can pass around functions directly.

for func in [Action1, partial(Action2, p), partial(Action3, p, r)]:
  func()

T-SQL query to show table definition?

This will return columns, datatypes, and indexes defined on the table:

--List all tables in DB
select * from sysobjects where xtype = 'U'

--Table Definition
sp_help TableName

This will return triggers defined on the table:

--Triggers in SQL Table
select * from sys.triggers where parent_id = object_id(N'SQLTableName') 

Convert a double to a QString

You can use arg(), as follow:

double dbl = 0.25874601;
QString str = QString("%1").arg(dbl);

This overcomes the problem of: "Fixed precision" at the other functions like: setNum() and number(), which will generate random numbers to complete the defined precision

android start activity from service

I had the same problem, and want to let you know that none of the above worked for me. What worked for me was:

 Intent dialogIntent = new Intent(this, myActivity.class);
 dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 this.startActivity(dialogIntent);

and in one my subclasses, stored in a separate file I had to:

public static Service myService;

myService = this;

new SubService(myService);

Intent dialogIntent = new Intent(myService, myActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myService.startActivity(dialogIntent);

All the other answers gave me a nullpointerexception.

What is the best way to dump entire objects to a log in C#?

What I like doing is overriding ToString() so that I get more useful output beyond the type name. This is handy in the debugger, you can see the information you want about an object without needing to expand it.

What is the time complexity of indexing, inserting and removing from common data structures?

Red-Black trees:

  • Insert - O(log n)
  • Retrieve - O(log n)
  • Delete - O(log n)

How to detect chrome and safari browser (webkit)

There is still quirks and inconsistencies in 2019.

For example with scaled svg and pointer events, between browsers.

None of the answer of this topic are working anymore. (maybe those with jquery)

Here is an alternative, by testing with javascript if a css rule is supported, via the native CSS support api. Might evolve, to be adapted!

Note that it's possible to pass many css rules separated by a semicolon, for the finest detection.

_x000D_
_x000D_
if (CSS.supports("( -webkit-box-reflect:unset )")){
  console.log("WEBKIT BROWSER")
  // More math...
 } else {
  console.log("ENJOY")
 }
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
if (CSS.supports("( -moz-user-select:unset )")){
  console.log("FIREFOX!!!")
 }
_x000D_
_x000D_
_x000D_

Beware to not use it in loops, for performance it's better to populate a constant on load:

const ff = CSS.supports("( -moz-user-select:unset )")
if (ff){ //... } 

Using CSS only, the above would be:

_x000D_
_x000D_
@supports (-webkit-box-reflect:unset) {
  div {
    background: red
  }
}

@supports (-moz-user-select:unset) {
  div {
    background: green
  }
}
_x000D_
<div>
  Hello world!!
</div>
_x000D_
_x000D_
_x000D_

List of possible -webkit- only css rules.

List of possible -moz- only rules.

Can I use css support?

Why are arrays of references illegal?

This is an interesting discussion. Clearly arrays of refs are outright illegal, but IMHO the reason why is not so simple as saying 'they are not objects' or 'they have no size'. I'd point out that arrays themselves are not full-fledged objects in C/C++ - if you object to that, try instantiating some stl template classes using an array as a 'class' template parameter, and see what happens. You can't return them, assign them, pass them as parameters. ( an array param is treated as a pointer). But it is legal to make arrays of arrays. References do have a size that the compiler can and must calculate - you can't sizeof() a reference, but you can make a struct containing nothing but references. It will have a size sufficient to contain all the pointers which implement the references. You can't instantiate such a struct without initializing all the members:

struct mys {
 int & a;
 int & b;
 int & c;
};
...
int ivar1, ivar2, arr[200];
mys my_refs = { ivar1, ivar2, arr[12] };

my_refs.a += 3  ;  // add 3 to ivar1

In fact you can add this line to the struct definition

struct mys {
 ...
 int & operator[]( int i ) { return i==0?a : i==1? b : c; }
};

...and now I have something which looks a LOT like an array of refs:

int ivar1, ivar2, arr[200];
mys my_refs = { ivar1, ivar2, arr[12] };

my_refs[1] = my_refs[2]  ;  // copy arr[12] to ivar2
&my_refs[0];               // gives &my_refs.a == &ivar1

Now, this is not a real array, it's an operator overload; it won't do things that arrays normally do like sizeof(arr)/sizeof(arr[0]), for instance. But it does exactly what I want an array of references to do, with perfectly legal C++. Except (a) it's a pain to set up for more than 3 or 4 elements, and (b) it's doing a calculation using a bunch of ?: which could be done using indexing (not with normal C-pointer-calculation-semantics indexing, but indexing nonetheless). I'd like to see a very limited 'array of reference' type which can actually do this. I.e. an array of references would not be treated as a general array of things which are references, but rather it would be a new 'array-of-reference' thing which effectively maps to an internally generated class similar to the one above (but which you unfortunately can't make with templates).

this would probably work, if you don't mind this kind of nasty: recast '*this' as an array of int *'s and return a reference made from one: (not recommended, but it shows how the proper 'array' would work):

 int & operator[]( int i ) { return *(reinterpret_cast<int**>(this)[i]); }

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

Python list directory, subdirectory, and files

It's just an addition, with this you can get the data into CSV format

import sys,os
try:
    import pandas as pd
except:
    os.system("pip3 install pandas")
    
root = "/home/kiran/Downloads/MainFolder" # it may have many subfolders and files inside
lst = []
from fnmatch import fnmatch
pattern = "*.csv"      #I want to get only csv files 
pattern = "*.*"        # Note: Use this pattern to get all types of files and folders 
for path, subdirs, files in os.walk(root):
    for name in files:
        if fnmatch(name, pattern):
            lst.append((os.path.join(path, name)))
df = pd.DataFrame({"filePaths":lst})
df.to_csv("filepaths.csv")

Converting a Java Keystore into PEM Format

I kept getting errors from openssl when using StoBor's command:

MAC verified OK
Error outputting keys and certificates
139940235364168:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:535:
139940235364168:error:23077074:PKCS12 routines:PKCS12_pbe_crypt:pkcs12 cipherfinal error:p12_decr.c:97:
139940235364168:error:2306A075:PKCS12 routines:PKCS12_item_decrypt_d2i:pkcs12 pbe crypt error:p12_decr.c:123:

For some reason, only this style of command would work for my JKS file

keytool -importkeystore -srckeystore foo.jks \
   -destkeystore foo.p12 \
   -srcstoretype jks \
   -srcalias mykey \
   -deststoretype pkcs12 \
   -destkeypass DUMMY123

The key was setting destkeypass, the value of the argument did not matter.

How do I compare a value to a backslash?

Use following code to perform if-else conditioning in python: Here, I am checking the length of the string. If the length is less than 3 then do nothing, if more then 3 then I check the last 3 characters. If last 3 characters are "ing" then I add "ly" at the end otherwise I add "ing" at the end.

Code-

if (len(s)<=3):
    return s
elif s[-3:]=="ing":
    return s+"ly"
else: return s + "ing"

How to drop column with constraint?

I got the same:

ALTER TABLE DROP COLUMN failed because one or more objects access this column message.

My column had an index which needed to be deleted first. Using sys.indexes did the trick:

DECLARE @sql VARCHAR(max)

SELECT @sql = 'DROP INDEX ' + idx.NAME + ' ON tblName'
FROM sys.indexes idx
INNER JOIN sys.tables tbl ON idx.object_id = tbl.object_id
INNER JOIN sys.index_columns idxCol ON idx.index_id = idxCol.index_id
INNER JOIN sys.columns col ON idxCol.column_id = col.column_id
WHERE idx.type <> 0
    AND tbl.NAME = 'tblName'
    AND col.NAME = 'colName'

EXEC sp_executeSql @sql
GO

ALTER TABLE tblName
DROP COLUMN colName

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

For me the problem was solved by restarting the docker daemon:

sudo systemctl restart docker

close fxml window by code, javafx

I found a nice solution which does not need an event to be triggered:

@FXML
private Button cancelButton;

close(new Event(cancelButton, stage, null));

@FXML
private void close(Event event) {
    ((Node)(event.getSource())).getScene().getWindow().hide();                      
}

Can I call an overloaded constructor from another constructor of the same class in C#?

EDIT: According to the comments on the original post this is a C# question.

Short answer: yes, using the this keyword.

Long answer: yes, using the this keyword, and here's an example.

class MyClass
{
   private object someData;

   public MyClass(object data)
   {
      this.someData = data;
   }

   public MyClass() : this(new object())
   {
      // Calls the previous constructor with a new object, 
      // setting someData to that object
   }
}

Using pip behind a proxy with CNTLM

if you want to upgrade pip by proxy, can use (for example in Windows):

python -m pip --proxy http://proxy_user:proxy_password@proxy_hostname:proxy_port insta
ll --upgrade pip

Escaping double quotes in JavaScript onClick event handler

It needs to be HTML-escaped, not Javascript-escaped. Change \" to &quot;

Coding Conventions - Naming Enums

This will probably not make me a lot of new friends, but it should be added that the C# people have a different guideline: The enum instances are "Pascal case" (upper/lower case mixed). See stackoverflow discussion and MSDN Enumeration Type Naming Guidelines.

As we are exchanging data with a C# system, I am tempted to copy their enums exactly, ignoring Java's "constants have uppercase names" convention. Thinking about it, I don't see much value in being restricted to uppercase for enum instances. For some purposes .name() is a handy shortcut to get a readable representation of an enum constant and a mixed case name would look nicer.

So, yes, I dare question the value of the Java enum naming convention. The fact that "the other half of the programming world" does indeed use a different style makes me think it is legitimate to doubt our own religion.

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

Problem

I had a similar problem using axes. The class parameter is frameon but the kwarg is frame_on. axes_api
>>> plt.gca().set(frameon=False)
AttributeError: Unknown property frameon

Solution

frame_on

Example

data = range(100)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(data)
#ax.set(frameon=False)  # Old
ax.set(frame_on=False)  # New
plt.show()

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

Senguttuvan: your solution was the only thing that worked for me.

function btnClose() {
  $(".ui-dialog-titlebar-close").trigger('click');
}

How do you easily horizontally center a <div> using CSS?

The title of the question and the content is actually different, so I will post two solutions for that using Flexbox.

I guess Flexbox will replace/add to the current standard solution by the time IE8 and IE9 is completely destroyed ;)

Check the current Browser compatibility table for flexbox

Single element

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <img src="http://placehold.it/100x100">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Multiple elements but center only one

Default behaviour is flex-direction: row which will align all the child items in a single line. Setting it to flex-direction: column will help the lines to be stacked.

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
.centered {_x000D_
  align-self: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged._x000D_
   </p>_x000D_
  <div class="centered"><img src="http://placehold.it/100x100"></div>_x000D_
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It_x000D_
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to color the Git console?

In your ~/.gitconfig file, simply add this:

[color]
  ui = auto

It takes care of all your git commands.

How to uninstall Apache with command line

Try this :

sc delete Apache2.4

or try this :

C:\Apache24\bin>httpd -k uninstall

hope this will be helpful

Fade Effect on Link Hover?

I know in the question you state "I assume JavaScript is used to create this effect" but CSS can be used too, an example is below.

CSS

.fancy-link {
   color: #333333;
   text-decoration: none;
   transition: color 0.3s linear;
   -webkit-transition: color 0.3s linear;
   -moz-transition: color 0.3s linear;
}

.fancy-link:hover {
   color: #F44336;
}

HTML

<a class="fancy-link" href="#">My Link</a>

And here is a JSFIDDLE for the above code!


Marcel in one of the answers points out you can "transition multiple CSS properties" you can also use "all" to effect the element with all your :hover styles like below.

CSS

.fancy-link {
   color: #333333;
   text-decoration: none;
   transition: all 0.3s linear;
   -webkit-transition: all 0.3s linear;
   -moz-transition: all 0.3s linear;
}

.fancy-link:hover {
   color: #F44336;
   padding-left: 10px;
}

HTML

<a class="fancy-link" href="#">My Link</a>

And here is a JSFIDDLE for the "all" example!

array of string with unknown size

Can you use a List strings and then when you are done use strings.ToArray() to get the array of strings to work with?

How to create a link to a directory

you should use :

ln -s /home/jake/doc/test/2000/something xxx

Why does Date.parse give incorrect results?

Use moment.js to parse dates:

var caseOne = moment("Jul 8, 2005", "MMM D, YYYY", true).toDate();
var caseTwo = moment("2005-07-08", "YYYY-MM-DD", true).toDate();

The 3rd argument determines strict parsing (available as of 2.3.0). Without it moment.js may also give incorrect results.

The model backing the <Database> context has changed since the database was created

None of these solutions would work for us (other than disabling the schema checking altogether). In the end we had a miss-match in our version of Newtonsoft.json

Our AppConfig did not get updated correctly:

<dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
  </dependentAssembly>

The solution was to correct the assembly version to the one we were actually deploying

<dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="10.0.0.0" />
  </dependentAssembly>

Loop until a specific user input

Your code won't work because you haven't assigned anything to n before you first use it. Try this:

def oracle():
    n = None
    while n != 'Correct':
        # etc...

A more readable approach is to move the test until later and use a break:

def oracle():
    guess = 50

    while True:
        print 'Current number = {0}'.format(guess)
        n = raw_input("lower, higher or stop?: ")
        if n == 'stop':
            break
        # etc...

Also input in Python 2.x reads a line of input and then evaluates it. You want to use raw_input.

Note: In Python 3.x, raw_input has been renamed to input and the old input method no longer exists.

Java - sending HTTP parameters via POST method easily

I had the same issue. I wanted to send data via POST. I used the following code:

    URL url = new URL("http://example.com/getval.php");
    Map<String,Object> params = new LinkedHashMap<>();
    params.put("param1", param1);
    params.put("param2", param2);

    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : params.entrySet()) {
        if (postData.length() != 0) postData.append('&');
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    String urlParameters = postData.toString();
    URLConnection conn = url.openConnection();

    conn.setDoOutput(true);

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    writer.write(urlParameters);
    writer.flush();

    String result = "";
    String line;
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    while ((line = reader.readLine()) != null) {
        result += line;
    }
    writer.close();
    reader.close()
    System.out.println(result);

I used Jsoup for parse:

    Document doc = Jsoup.parseBodyFragment(value);
    Iterator<Element> opts = doc.select("option").iterator();
    for (;opts.hasNext();) {
        Element item = opts.next();
        if (item.hasAttr("value")) {
            System.out.println(item.attr("value"));
        }
    }

Android - save/restore fragment state

Try this :

@Override
protected void onPause() {
    super.onPause();
    if (getSupportFragmentManager().findFragmentByTag("MyFragment") != null)
        getSupportFragmentManager().findFragmentByTag("MyFragment").setRetainInstance(true);
}

@Override
protected void onResume() {
    super.onResume();
    if (getSupportFragmentManager().findFragmentByTag("MyFragment") != null)
        getSupportFragmentManager().findFragmentByTag("MyFragment").getRetainInstance();
}

Hope this will help.

Also you can write this to activity tag in menifest file :

  android:configChanges="orientation|screenSize"

Good luck !!!

How to implement a tree data-structure in Java?

Please check the below code, where I have used Tree data structures, without using Collection classes. The code may have bugs/improvements but please use this just for reference

package com.datastructure.tree;

public class BinaryTreeWithoutRecursion <T> {

    private TreeNode<T> root;


    public BinaryTreeWithoutRecursion (){
        root = null;
    }


    public void insert(T data){
        root =insert(root, data);

    }

    public TreeNode<T>  insert(TreeNode<T> node, T data ){

        TreeNode<T> newNode = new TreeNode<>();
        newNode.data = data;
        newNode.right = newNode.left = null;

        if(node==null){
            node = newNode;
            return node;
        }
        Queue<TreeNode<T>> queue = new Queue<TreeNode<T>>();
        queue.enque(node);
        while(!queue.isEmpty()){

            TreeNode<T> temp= queue.deque();
            if(temp.left!=null){
                queue.enque(temp.left);
            }else
            {
                temp.left = newNode;

                queue =null;
                return node;
            }
            if(temp.right!=null){
                queue.enque(temp.right);
            }else
            {
                temp.right = newNode;
                queue =null;
                return node;
            }
        }
        queue=null;
        return node; 


    }

    public void inOrderPrint(TreeNode<T> root){
        if(root!=null){

            inOrderPrint(root.left);
            System.out.println(root.data);
            inOrderPrint(root.right);
        }

    }

    public void postOrderPrint(TreeNode<T> root){
        if(root!=null){

            postOrderPrint(root.left);

            postOrderPrint(root.right);
            System.out.println(root.data);
        }

    }

    public void preOrderPrint(){
        preOrderPrint(root);
    }


    public void inOrderPrint(){
        inOrderPrint(root);
    }

    public void postOrderPrint(){
        inOrderPrint(root);
    }


    public void preOrderPrint(TreeNode<T> root){
        if(root!=null){
            System.out.println(root.data);
            preOrderPrint(root.left);
            preOrderPrint(root.right);
        }

    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        BinaryTreeWithoutRecursion <Integer> ls=  new BinaryTreeWithoutRecursion <>();
        ls.insert(1);
        ls.insert(2);
        ls.insert(3);
        ls.insert(4);
        ls.insert(5);
        ls.insert(6);
        ls.insert(7);
        //ls.preOrderPrint();
        ls.inOrderPrint();
        //ls.postOrderPrint();

    }

}

What is @ModelAttribute in Spring MVC?

At the Method Level

1.When the annotation is used at the method level it indicates the purpose of that method is to add one or more model attributes

@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("india", "india");
}

At the Method Argument 1. When used as a method argument, it indicates the argument should be retrieved from the model. When not present and should be first instantiated and then added to the model and once present in the model, the arguments fields should be populated from all request parameters that have matching names So, it binds the form data with a bean.

 @RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
  public String submit(@ModelAttribute("employee") Employee employee) {
  return "employeeView";
  }

Filter Linq EXCEPT on properties

public static class ExceptByProperty
{
    public static List<T> ExceptBYProperty<T, TProperty>(this List<T> list, List<T> list2, Expression<Func<T, TProperty>> propertyLambda)
    {
        Type type = typeof(T);

        MemberExpression member = propertyLambda.Body as MemberExpression;

        if (member == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a method, not a property.",
                propertyLambda.ToString()));

        PropertyInfo propInfo = member.Member as PropertyInfo;
        if (propInfo == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a field, not a property.",
                propertyLambda.ToString()));

        if (type != propInfo.ReflectedType &&
            !type.IsSubclassOf(propInfo.ReflectedType))
            throw new ArgumentException(string.Format(
                "Expresion '{0}' refers to a property that is not from type {1}.",
                propertyLambda.ToString(),
                type));
        Func<T, TProperty> func = propertyLambda.Compile();
        var ids = list2.Select<T, TProperty>(x => func(x)).ToArray();
        return list.Where(i => !ids.Contains(((TProperty)propInfo.GetValue(i, null)))).ToList();
    }
}

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

For Test this:

        List<testClass> a = new List<testClass>();
        List<testClass> b = new List<testClass>();
        a.Add(new testClass() { ID = 1 });
        a.Add(new testClass() { ID = 2 });
        a.Add(new testClass() { ID = 3 });
        a.Add(new testClass() { ID = 4 });
        a.Add(new testClass() { ID = 5 });

        b.Add(new testClass() { ID = 3 });
        b.Add(new testClass() { ID = 5 });
        a.Select<testClass, int>(x => x.ID);

        var items = a.ExceptBYProperty(b, u => u.ID);

Fixed header, footer with scrollable content

Here's what worked for me. I had to add a margin-bottom so the footer wouldn't eat up my content:

header {
  height: 20px;
  background-color: #1d0d0a;
  position: fixed;
  top: 0;
  width: 100%;
  overflow: hide;
}

content {
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 100px;
  margin-top: 20px;
  overflow: auto;
  width: 80%;
}

footer {
  position: fixed;
  bottom: 0px;
  overflow: hide;
  width: 100%;
}

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

Just to add my $.02 here, I ran into a similar issue just yesterday, where 168 of my tests were missing. I tried most everything in this post - most especially making sure my version(s) of NUnit were the same - all to no avail. I then remembered that I had my tests divided into playlists; and these do not update automatically as you add new tests. So, when I deleted the playlists, BAM!, all of my tests were back once more.

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

Here's my take on the problem. I create AbsoluteLayout overlay which contains Info Window (a regular view with every bit of interactivity and drawing capabilities). Then I start Handler which synchronizes the info window's position with position of point on the map every 16 ms. Sounds crazy, but actually works.

Demo video: https://www.youtube.com/watch?v=bT9RpH4p9mU (take into account that performance is decreased because of emulator and video recording running simultaneously).

Code of the demo: https://github.com/deville/info-window-demo

An article providing details (in Russian): http://habrahabr.ru/post/213415/

How to execute raw SQL in Flask-SQLAlchemy app

This is a simplified answer of how to run SQL query from Flask Shell

First, map your module (if your module/app is manage.py in the principal folder and you are in a UNIX Operating system), run:

export FLASK_APP=manage

Run Flask shell

flask shell

Import what we need::

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
from sqlalchemy import text

Run your query:

result = db.engine.execute(text("<sql here>").execution_options(autocommit=True))

This use the currently database connection which has the application.

SQL Server Script to create a new user

Based on your question, I think that you may be a bit confused about the difference between a User and a Login. A Login is an account on the SQL Server as a whole - someone who is able to log in to the server and who has a password. A User is a Login with access to a specific database.

Creating a Login is easy and must (obviously) be done before creating a User account for the login in a specific database:

CREATE LOGIN NewAdminName WITH PASSWORD = 'ABCD'
GO

Here is how you create a User with db_owner privileges using the Login you just declared:

Use YourDatabase;
GO

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'NewAdminName')
BEGIN
    CREATE USER [NewAdminName] FOR LOGIN [NewAdminName]
    EXEC sp_addrolemember N'db_owner', N'NewAdminName'
END;
GO

Now, Logins are a bit more fluid than I make it seem above. For example, a Login account is automatically created (in most SQL Server installations) for the Windows Administrator account when the database is installed. In most situations, I just use that when I am administering a database (it has all privileges).

However, if you are going to be accessing the SQL Server from an application, then you will want to set the server up for "Mixed Mode" (both Windows and SQL logins) and create a Login as shown above. You'll then "GRANT" priviliges to that SQL Login based on what is needed for your app. See here for more information.

UPDATE: Aaron points out the use of the sp_addsrvrolemember to assign a prepared role to your login account. This is a good idea - faster and easier than manually granting privileges. If you google it you'll see plenty of links. However, you must still understand the distinction between a login and a user.

SQL ROWNUM how to return rows between a specific range

I know this is an old question, however, it is useful to mention the new features in the latest version.

From Oracle 12c onwards, you could use the new Top-n Row limiting feature. No need to write a subquery, no dependency on ROWNUM.

For example, the below query would return the employees between 4th highest till 7th highest salaries in ascending order:

SQL> SELECT empno, sal
  2  FROM   emp
  3  ORDER BY sal
  4  OFFSET 4 ROWS FETCH NEXT 4 ROWS ONLY;

     EMPNO        SAL
---------- ----------
      7654       1250
      7934       1300
      7844       1500
      7499       1600

SQL>

Vim clear last search highlighting

If you want to be able to enable/disable highlighting quickly, you can map a key to

" Press F4 to toggle highlighting on/off, and show current value.
:noremap <F4> :set hlsearch! hlsearch?<CR>

Just put the above snippet in you .vimrc file.

That's the most convenient way for me to show and hide the search highlight with a sing key stroke

For more information check the documentation http://vim.wikia.com/wiki/Highlight_all_search_pattern_matches

How to paste text to end of every line? Sublime 2

Let's say you have these lines of code:

test line one
test line two
test line three
test line four

Using Search and Replace Ctrl+H with Regex let's find this: ^ and replace it with ", we'll have this:

"test line one
"test line two
"test line three
"test line four

Now let's search this: $ and replace it with ", now we'll have this:

"test line one"
"test line two"
"test line three"
"test line four"

Is there a Google Keep API?

I have been waiting to see if Google would open a Keep API. When I discovered Google Tasks, and saw that it had an Android app, web app, and API, I converted over to Tasks. This may not directly answer your question, but it is my solution to the Keep API problem.

Tasks doesn't have a reminder alarm exactly like Keep. I can live without that if I also connect with the Calendar API.

https://developers.google.com/google-apps/tasks/

How to manually install a pypi module without pip/easy_install?

To further explain Sheena's answer, I needed to have setup-tools installed as a dependency of another tool e.g. more-itertools.

Download

Click the Clone or download button and choose your method. I placed these into a dev/py/libs directory in my user home directory. It does not matter where they are saved, because they will not be installed there.

Installing setup-tools

You will need to run the following inside the setup-tools directory.

python bootstrap.py
python setup.py install

General dependencies installation

Now you can navigate to the more-itertools direcotry and install it as normal.

  1. Download the package
  2. Unpackage it if it's an archive
  3. Navigate (cd ...) into the directory containing setup.py
  4. If there are any installation instructions contained in the documentation contained herein, read and follow the instructions OTHERWISE
  5. Type in: python setup.py install

How to call a PHP file from HTML or Javascript


How to make a button call PHP?

I don't care if the page reloads or displays the results immediately;

Good!

Note: If you don't want to refresh the page see "Ok... but how do I Use Ajax anyway?" below.

I just want to have a button on my website make a PHP file run.

That can be done with a form with a single button:

<form action="">
  <input type="submit" value="my button"/>
</form>

That's it.

Pretty much. Also note that there are cases where ajax is really the way to go.

That depends on what you want. In general terms you only need ajax when you want to avoid realoading the page. Still you have said that you don't care about that.


Why I cannot call PHP directly from JavaScript?

If I can write the code inside HTML just fine, why can't I just reference the file for it in there or make a simple call for it in Javascript?

Because the PHP code is not in the HTML just fine. That's an illusion created by the way most server side scripting languages works (including PHP, JSP, and ASP). That code only exists on the server, and it is no reachable form the client (the browser) without a remote call of some sort.

You can see evidence of this if you ask your browser to show the source code of the page. There you will not see the PHP code, that is because the PHP code is not send to the client, therefore it cannot be executed from the client. That's why you need to do a remote call to be able to have the client trigger the execution of PHP code.

If you don't use a form (as shown above) you can do that remote call from JavaScript with a little thing called Ajax. You may also want to consider if what you want to do in PHP can be done directly in JavaScript.


How to call another PHP file?

Use a form to do the call. You can have it to direct the user to a particlar file:

<form action="myphpfile.php">
  <input type="submit" value="click on me!">
</form>

The user will end up in the page myphpfile.php. To make it work for the current page, set action to an empty string (which is what I did in the example I gave you early).

I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

You want to make an operation on the server, you should make your form have the fields you need (even if type="hidden" and use POST):

<form action="" method="POST">
  <input type="text" value="default value, you can edit it" name="myfield">
  <input type="submit" value = "post">
</form>

What do I need to know about it to call a PHP file that will create a text file on a button press?

see: How to write into a file in PHP.


How do you recieve the data from the POST in the server?

I'm glad you ask... Since you are a newb begginer, I'll give you a little template you can follow:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        //Ok we got a POST, probably from a FORM, read from $_POST.
        var_dump($_PSOT); //Use this to see what info we got!
    }
    else
    {
       //You could assume you got a GET
       var_dump($_GET); //Use this to see what info we got!
    }
 ?>
 <!DOCTYPE html>
 <html lang="en">
   <head>
     <meta char-set="utf-8">
     <title>Page title</title>
   </head>
   <body>
     <form action="" method="POST">
       <input type="text" value="default value, you can edit it" name="myfield">
       <input type="submit" value = "post">
     </form>
   </body>
 </html>

Note: you can remove var_dump, it is just for debugging purposes.


How do I...

I know the next stage, you will be asking how to:

  1. how to pass variables form a PHP file to another?
  2. how to remember the user / make a login?
  3. how to avoid that anoying message the appears when you reload the page?

There is a single answer for that: Sessions.

I'll give a more extensive template for Post-Redirect-Get

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        //Do stuff...
        //Write results to session
        session_start();
        $_SESSION['stuff'] = $something;
        //You can store stuff such as the user ID, so you can remeember him.
        //redirect:
        header('Location: ', true, 303);
        //The redirection will cause the browser to request with GET
        //The results of the operation are in the session variable
        //It has empty location because we are redirecting to the same page
        //Otherwise use `header('Location: anotherpage.php', true, 303);`
        exit();
    }
    else
    {
        //You could assume you got a GET
        var_dump($_GET); //Use this to see what info we got!
        //Get stuff from session
        session_start();
        if (array_key_exists('stuff', $_SESSION))
        {
           $something = $_SESSION['stuff'];
           //we got stuff
           //later use present the results of the operation to the user.
        }
        //clear stuff from session:
        unset($_SESSION['stuff']);
        //set headers
        header('Content-Type: text/html; charset=utf-8');
        //This header is telling the browser what are we sending.
        //And it says we are sending HTML in UTF-8 encoding
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
  </head>
  <body>
    <?php if (isset($something)){ echo '<span>'.$something.'</span>'}?>;
    <form action="" method="POST">
      <input type="text" value="default value, you can edit it" name="myfield">
      <input type="submit" value = "post">
    </form>
  </body>
</html>

Please look at php.net for any function call you don't recognize. Also - if you don't have already - get a good tutorial on HTML5.

Also, use UTF-8 because UTF-8!


Notes:

I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately.

If are you using a CMS (Codepress, Joomla, Drupal... etc)? That make put some contraints on how you got to do things.

Also, if you are using a framework, you should look at their documentation or ask at their forum/mailing list/discussion page/contact or try to ask the authors.


Ok... but how do I Use Ajax anyway?

Well... Ajax is made easy by some JavaScript libraries. Since you are a begginer, I'll recomend jQuery.

So, let's send something to the server via Ajax with jQuery, I'll use $.post instead of $.ajax for this example.

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        header('Location: ', true, 303);
        exit();
    }
    else
    {
        var_dump($_GET);
        header('Content-Type: text/html; charset=utf-8');
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
    <script>
        function ajaxmagic()
        {
            $.post(                             //call the server
                "test.php",                     //At this url
                {
                    field: "value",
                    name: "John"
                }                               //And send this data to it
            ).done(                             //And when it's done
                function(data)
                {
                    $('#fromAjax').html(data);  //Update here with the response
                }
            );
        }
    </script>
  </head>
  <body>
    <input type="button" value = "use ajax", onclick="ajaxmagic()">
    <span id="fromAjax"></span>
  </body>
</html>

The above code will send a POST request to the page test.php.

Note: You can mix sessions with ajax and stuff if you want.


How do I...

  1. How do I connect to the database?
  2. How do I prevent SQL injection?
  3. Why shouldn't I use Mysql_* functions?

... for these or any other, please make another questions. That's too much for this one.

jQuery hasAttr checking to see if there is an attribute on an element

I wrote a hasAttr() plugin for jquery that will do all of this very simply, exactly as the OP has requested. More information here

EDIT: My plugin was deleted in the great plugins.jquery.com database deletion disaster of 2010. You can look here for some info on adding it yourself, and why it hasn't been added.

How can I render HTML from another file in a React component?

You could do it if template is a react component.

Template.js

var React = require('react');

var Template = React.createClass({
    render: function(){
        return (<div>Mi HTML</div>);
    }
});

module.exports = Template;

MainComponent.js

var React = require('react');
var ReactDOM = require('react-dom');
var injectTapEventPlugin = require("react-tap-event-plugin");
var Template = require('./Template');

//Needed for React Developer Tools
window.React = React;

//Needed for onTouchTap
//Can go away when react 1.0 release
//Check this repo:
//https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();

var MainComponent = React.createClass({
    render: function() {
        return(
            <Template/>
        );
    }
});

// Render the main app react component into the app div.
// For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
ReactDOM.render(
  <MainComponent />,
  document.getElementById('app')
 );

And if you are using Material-UI, for compatibility use Material-UI Components, no normal inputs.

How Can I Remove “public/index.php” in the URL Generated Laravel?

I just installed Laravel 5 for a project and there is a file in the root called server.php.

Change it to index.php and it works or type in terminal:

$cp server.php index.php

Changing the background color of a drop down list transparent in html

You can actualy fake the transparency of option DOMElements with the following CSS:

CSS

option { 
    /* Whatever color  you want */
    background-color: #82caff;
}

See Demo

The option tag does not support rgba colors yet.

What is the format for the PostgreSQL connection string / URL?

host or hostname would be the i.p address of the remote server, or if you can access it over the network by computer name, that should work to.

Adding items to an object through the .push() method

stuff is an object and push is a method of an array. So you cannot use stuff.push(..).

Lets say you define stuff as an array stuff = []; then you can call push method on it.

This works because the object[key/value] is well formed.

stuff.push( {'name':$(this).attr('checked')} );

Whereas this will not work because the object is not well formed.

stuff.push( {$(this).attr('value'):$(this).attr('checked')} );

This works because we are treating stuff as an associative array and added values to it

stuff[$(this).attr('value')] = $(this).attr('checked');

Getting results between two dates in PostgreSQL

just had the same question, and answered this way, if this could help.

select * 
from table
where start_date between '2012-01-01' and '2012-04-13'
or    end_date   between '2012-01-01' and '2012-04-13'

Difference between a theta join, equijoin and natural join

Cartesian product of two tables gives all the possible combinations of tuples like the example in mathematics the cross product of two sets . since many a times there are some junk values which occupy unnecessary space in the memory too so here joins comes to rescue which give the combination of only those attribute values which are required and are meaningful.

inner join gives the repeated field in the table twice whereas natural join here solves the problem by just filtering the repeated columns and displaying it only once.else, both works the same. natural join is more efficient since it preserves the memory .Also , redundancies are removed in natural join .

equi join of two tables are such that they display only those tuples which matches the value in other table . for example : let new1 and new2 be two tables . if sql query select * from new1 join new2 on new1.id = new.id (id is the same column in two tables) then start from new2 table and join which matches the id in second table . besides , non equi join do not have equality operator they have <,>,and between operator .

theta join consists of all the comparison operator including equality and others < , > comparison operator. when it uses equality(=) operator it is known as equi join .

Force IE9 to emulate IE8. Possible?

On the client side you can add and remove websites to be displayed in Compatibility View from Compatibility View Settings window of IE:

Tools-> Compatibility View Settings

Is there a way that I can check if a data attribute exists?

And what about:

if ($('#dataTable[data-timer]').length > 0) {
    // logic here
}

Convert javascript array to string

jQuery.each is just looping over the array, it doesn't do anything with the return value?. You are looking for jQuery.map (I also think that get() is unnecessary as you are not dealing with jQuery objects):

var blkstr = $.map(value, function(val,index) {                    
     var str = index + ":" + val;
     return str;
}).join(", ");  

DEMO


But why use jQuery at all in this case? map only introduces an unnecessary function call per element.

var values = [];

for(var i = 0, l = value.length; i < l; i++) {
    values.push(i + ':' + value[i]);
}

// or if you actually have an object:

for(var id in value) {
    if(value.hasOwnProperty(id)) {
        values.push(id + ':' + value[id]);
    }
}

var blkstr = values.join(', ');

?: It only uses the return value whether it should continue to loop over the elements or not. Returning a "falsy" value will stop the loop.

Floating point exception( core dump

Floating Point Exception happens because of an unexpected infinity or NaN. You can track that using gdb, which allows you to see what is going on inside your C program while it runs. For more details: https://www.cs.swarthmore.edu/~newhall/unixhelp/howto_gdb.php

In a nutshell, these commands might be useful...

gcc -g myprog.c

gdb a.out

gdb core a.out

ddd a.out

use std::fill to populate vector with increasing numbers

If you really want to use std::fill and are confined to C++98 you can use something like the following,

#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>

struct increasing {
    increasing(int start) : x(start) {}
    operator int () const { return x++; }
    mutable int x;
};

int main(int argc, char* argv[])
{
    using namespace std;

    vector<int> v(10);
    fill(v.begin(), v.end(), increasing(0));
    copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
    cout << endl;
    return 0;
}

Python Iterate Dictionary by Index

I can't think of any reason why you would want to do that. If you just need to iterate over the dictionary, you can just do.

for key, elem in testDict.items():
    print key, elem

OR

for i in testDict:
     print i, testDict[i]

How to append something to an array?

You can use push and apply function to append two arrays.

_x000D_
_x000D_
var array1 = [11, 32, 75];_x000D_
var array2 = [99, 67, 34];_x000D_
_x000D_
Array.prototype.push.apply(array1, array2);_x000D_
console.log(array1);
_x000D_
_x000D_
_x000D_

It will append array2 to array1. Now array1 contains [11, 32, 75, 99, 67, 34]. This code is much simpler than writing for loops to copy each and every items in the array.

Can not change UILabel text color

It is possible, they are not connected in InterfaceBuilder.

Text colour(colorWithRed:(188/255) green:(149/255) blue:(88/255)) is correct, may be mistake in connections,

backgroundcolor is used for the background colour of label and textcolor is used for property textcolor.

How to call a asp:Button OnClick event using JavaScript?

Set style= "display:none;". By setting visible=false, it will not render button in the browser. Thus,client side script wont execute.

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />

html markup should be

<button id="btnsave" onclick="fncsave()">Save</button>

Change javascript to

<script type="text/javascript">
     function fncsave()
     {
        document.getElementById('<%= savebtn.ClientID %>').click();
     }
</script>

How to parse float with two decimal places in javascript?

If your objective is to parse, and your input might be a literal, then you'd expect a float and toFixed won't provide that, so here are two simple functions to provide this:

function parseFloat2Decimals(value) {
    return parseFloat(parseFloat(value).toFixed(2));
}

function parseFloat2Decimals(value,decimalPlaces) {
    return parseFloat(parseFloat(value).toFixed(decimalPlaces));
}

MySQL - How to select data by string length

I used this sentences to filter

SELECT table.field1, table.field2 FROM table WHERE length(field) > 10;

you can change 10 for other number that you want to filter.