Programs & Examples On #Context free grammar

In formal language theory, a context-free grammar (CFG) is a grammar subject to a special constraint: that the left-hand side (LHS) consist of a single non-terminal symbol. CFGs are capable of representing the set of context-free languages (CFLs).

Regular vs Context Free Grammars

a regular grammer is never ambiguous because it is either left linear or right linear so we cant make two decision tree for regular grammer so it is always unambiguous.but othert than regular grammar all are may or may not be regular

Sending string via socket (python)

client.py

import socket

s = socket.socket()
s.connect(('127.0.0.1',12345))
while True:
    str = raw_input("S: ")
    s.send(str.encode());
    if(str == "Bye" or str == "bye"):
        break
    print "N:",s.recv(1024).decode()
s.close()

server.py

import socket

s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print "Socket Up and running with a connection from",addr
while True:
    rcvdData = c.recv(1024).decode()
    print "S:",rcvdData
    sendData = raw_input("N: ")
    c.send(sendData.encode())
    if(sendData == "Bye" or sendData == "bye"):
        break
c.close()

This should be the code for a small prototype for the chatting app you wanted. Run both of them in separate terminals but then just check for the ports.

Group dataframe and get sum AND count?

df.groupby('Company Name').agg({'Organisation name':'count','Amount':'sum'})\
    .apply(lambda x: x.sort_values(['count','sum'], ascending=False))

jQuery form input select by id

If you have more than one element with the same ID, then you have invalid HTML.

But you can acheive the same result using classes instead. That's what they're designed for.

<input class='b' ... >

You can give it an ID as well if you need to, but it should be unique.

Once you've got the class in there, you can reference it with a dot instead of the hash, like so:

var value = $('#a .b').val();

or

var value = $('#a input.b').val();

which will limit it to 'b' class elements that are inputs within the form (which seems to be close to what you're asking for).

Move layouts up when soft keyboard is shown?

It might be late but I want to add few things. In Android Studio Version 4.0.1, and Gradle Version 6.1.1, the windowSoftInputMode will not work as expected if you are adding the following flags in your Activity :

getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
        );

After wasting lot of time, I have found that hack. In order for adjustResize or AdjustPanor any attribute of windowSoftInputMode to work properly, you need to remove that from your activity.

How to stick a footer to bottom in css?

This worked for me:

.footer
{
  width: 100%;
  bottom: 0;
  clear: both;
}

Get a worksheet name using Excel VBA

Function MySheet()

  ' uncomment the below line to make it Volatile
  'Application.Volatile
   MySheet = Application.Caller.Worksheet.Name

End Function

This should be the function you are looking for

What is the default username and password in Tomcat?

My answer is tested on Windows 7 with installation of NetBeans IDE 6.9.1 which has bundled Tomcat version 6.0.26. The instruction may work with other tomcat versions according to my opinion.

If you are starting the Apache Tomcat server from the Servers panel in NetBeans IDE then you shall know that the Catalina base and config files used by NetBeans IDE to start the Tomcat server are kept at a different location.

Steps to know the catalina base directory for your installation:

  1. Right click on the Apache Tomcat node in Servers panel and choose properties option in the context menu. This will open a dialog box named Servers.
  2. Check the directory name of the field Catalina Base, this is that directory where the current conf/tomcat-users.xml is located and which you want to open and read.
    (In my case it is C:\Users\Tushar Joshi\.netbeans\6.9\apache-tomcat-6.0.26_base )
  3. Open this directory in My Computer and go to the conf directory where you will find the actual tomcat-users.xml file used by NetBeans IDE. NetBeans IDE comes configured with one default password with username="ide" and some random password, you may change this username and password if you want or use it for your login also
  4. This dialog box also have username and password field which are populated with these default username and password and NetBeans IDE also offers you to open the manager application by right clicking on the manager node under the Apache Tomcat node in Servers panel
  5. The only problem with the NetBeans IDE is it tries to open the URL http://localhost:8084/manager/ which shall be http://localhost:8084/manager/html now

Extract and delete all .gz in a directory- Linux

There's more than one way to do this obviously.

    # This will find files recursively (you can limit it by using some 'find' parameters. 
    # see the man pages
    # Final backslash required for exec example to work
    find . -name '*.gz' -exec gunzip '{}' \;

    # This will do it only in the current directory
    for a in *.gz; do gunzip $a; done

I'm sure there's other ways as well, but this is probably the simplest.

And to remove it, just do a rm -rf *.gz in the applicable directory

Making RGB color in Xcode

Color picker plugin for Interface Builder

There's a nice color picker from Panic which works well with IB: http://panic.com/~wade/picker/

Xcode plugin

This one gives you a GUI for choosing colors: http://www.youtube.com/watch?v=eblRfDQM0Go

Objective-C

UIColor *color = [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1.0];

Swift

let color = UIColor(red: 160/255, green: 97/255, blue: 5/255, alpha: 1.0)

Pods and libraries

There's a nice pod named MPColorTools: https://github.com/marzapower/MPColorTools

Bootstrap modal opening on page load

Use a document.ready() event around your call.

$(document).ready(function () {

    $('#memberModal').modal('show');

});

jsFiddle updated - http://jsfiddle.net/uvnggL8w/1/

What's the difference between .NET Core, .NET Framework, and Xamarin?

  1. .NET is the Ecosystem based on c# language
  2. .NET Standard is Standard (in other words, specification) of .NET Ecosystem .

.Net Core Class Library is built upon the .Net Standard. .NET Standard you can make only class-library project that cannot be executed standalone and should be referenced by another .NET Core or .NET Framework executable project.If you want to implement a library that is portable to the .Net Framework, .Net Core and Xamarin, choose a .Net Standard Library

  1. .NET Framework is a framework based on .NET and it supports Windows and Web applications

(You can make executable project (like Console application, or ASP.NET application) with .NET Framework

  1. ASP.NET is a web application development technology which is built over the .NET Framework
  2. .NET Core also a framework based on .NET.

It is the new open-source and cross-platform framework to build applications for all operating system including Windows, Mac, and Linux.

  1. Xamarin is a framework to develop a cross platform mobile application(iOS, Android, and Windows Mobile) using C#

Implementation support of .NET Standard[blue] and minimum viable platform for full support of .NET Standard (latest: [https://docs.microsoft.com/en-us/dotnet/standard/net-standard#net-implementation-support])

Maven: Failed to retrieve plugin descriptor error

I had a similar issue with Eclipse and the same steps as Sanders did solve it. It happens because the proxy restricts call to maven repository

  1. Go to D:\Maven\apache-maven-3.0.4-bin\apache-maven-3.0.4\conf (ie your maven installation folder)
  2. Copy settings.xml and paste it in .m2 folder, which is in the users folder of your windows machine.
  3. Add the proxy setting

Something like this:

 <proxies>
    <!-- proxy
      Specification for one proxy, to be used in connecting to the network.
     -->
    <proxy>      
      <active>true</active>
      <protocol>http</protocol>
      <username>your username</username>
      <password>password</password>    
      <host>proxy.host.net</host>
      <port>80</port>  
    </proxy>

  </proxies>

Changing the CommandTimeout in SQL Management studio

Changing Command Execute Timeout in Management Studio:

Click on Tools -> Options

Select Query Execution from tree on left side and enter command timeout in "Execute Timeout" control.

Changing Command Timeout in Server:

In the object browser tree right click on the server which give you timeout and select "Properties" from context menu.

Now in "Server Properties -....." dialog click on "Connections" page in "Select a Page" list (on left side). On the right side you will get property

Remote query timeout (in seconds, 0 = no timeout):
[up/down control]

you can set the value in up/down control.

Bootstrap 4, how to make a col have a height of 100%?

I came across this problem because my cols exceeded the row grid length (> 12)

A solution using 100% Bootstrap 4:

Since the rows in Bootstrap are already display: flex

You just need to add flex-fill to the Col, and h-100 to the container and any children.

Pen here: https://codepen.io/joshkopecek/pen/Exjdgjo

<div class="container-fluid h-100">
  <div class="row justify-content-center h-100">

    <div class="col-4 hidden-md-down flex-fill" id="yellow">
      XXXX
    </div>

    <div id="blue" class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8 h-100">
      Form Goes Here
    </div>

    <div id="green" class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8 h-100">
      Another form
    </div>
  </div>
</div>

Extract a part of the filepath (a directory) in Python

import os

directory = os.path.abspath('\\') # root directory
print(directory) # e.g. 'C:\'

directory = os.path.abspath('.') # current directory
print(directory) # e.g. 'C:\Users\User\Desktop'

parent_directory, directory_name = os.path.split(directory)
print(directory_name) # e.g. 'Desktop'
parent_parent_directory, parent_directory_name = os.path.split(parent_directory)
print(parent_directory_name) # e.g. 'User'

This should also do the trick.

PHP - count specific array values

array_count_values only works for integers and strings. If you happen to want counts for float/numeric values (and you are heedless of small variations in precision or representation), this works:

function arrayCountValues($arr) {
  $vals = [];
  foreach ($arr as $val) { array_push($vals,strval($val)); }
  $cnts = array_count_values($vals);
  arsort($cnts);
  return $cnts;
}

Note that I return $cnts with the keys as strings. It would be easy to reconvert them, but I'm trying to determine the mode for the values, so I only need to re-convert the first (several) values.

I tested a version which looped, creating an array of counts rather than using array_count_values, and this turned out to be more efficient (by maybe 8-10%)!

How to change link color (Bootstrap)

ul.nav li a, ul.nav li a:visited {
    color: #anycolor !important;
}

ul.nav li a:hover, ul.nav li a:active {
    color: #anycolor !important;
}

ul.nav li.active a {
    color: #anycolor !important;
}

Change the styles as you wish.

Print to the same line and not a new line?

For Python 3+

for i in range(5):
    print(str(i) + '\r', sep='', end ='', file = sys.stdout , flush = False)

Php $_POST method to get textarea value

Make sure your escaping the HTML characters

E.g.

// Always check an input variable is set before you use it
if (isset($_POST['contact_list'])) {
    // Escape any html characters
    echo htmlentities($_POST['contact_list']);
}

This would occur because of the angle brackets and the browser thinking they are tags.

See: http://php.net/manual/en/function.htmlentities.php

How to add title to subplots in Matplotlib?

A shorthand answer assuming import matplotlib.pyplot as plt:

plt.gca().set_title('title')

as in:

plt.subplot(221)
plt.gca().set_title('title')
plt.subplot(222)
etc...

Then there is no need for superfluous variables.

How to create a responsive image that also scales up in Bootstrap 3

I guess image is than corrupted. Example: image size is 195px X 146px.

It will work inside lower resolutions like tablets. When you have 1280 X 800 resolution it will force larger as there is also width 100 %. Maybe CSS inside media query like icons fonts is the best solution.

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

Firstly, why doesn't your solution work. You mix up a lot of concepts. Mostly character class with other ones. In the first character class you use | which stems from alternation. In character classes you don't need the pipe. Just list all characters (and character ranges) you want:

[Uu]

Or simply write u if you use the case-insensitive modifier. If you write a pipe there, the character class will actually match pipes in your subject string.

Now in the second character class you use the comma to separate your characters for some odd reason. That does also nothing but include commas into the matchable characters. s and W are probably supposed to be the built-in character classes. Then escape them! Otherwise they will just match literal s and literal W. But then \W already includes everything else you listed there, so a \W alone (without square brackets) would have been enough. And the last part (^a-zA-Z) also doesn't work, because it will simply include ^, (, ) and all letters into the character class. The negation syntax only works for entire character classes like [^a-zA-Z].

What you actually want is to assert that there is no letter in front or after your u. You can use lookarounds for that. The advantage is that they won't be included in the match and thus won't be removed:

r'(?<![a-zA-Z])[uU](?![a-zA-Z])'

Note that I used a raw string. Is generally good practice for regular expressions, to avoid problems with escape sequences.

These are negative lookarounds that make sure that there is no letter character before or after your u. This is an important difference to asserting that there is a non-letter character around (which is similar to what you did), because the latter approach won't work at the beginning or end of the string.

Of course, you can remove the spaces around you from the replacement string.

If you don't want to replace u that are next to digits, you can easily include the digits into the character classes:

r'(?<![a-zA-Z0-9])[uU](?![a-zA-Z0-9])'

And if for some reason an adjacent underscore would also disqualify your u for replacement, you could include that as well. But then the character class coincides with the built-in \w:

r'(?<!\w)[uU](?!\w)'

Which is, in this case, equivalent to EarlGray's r'\b[uU]\b'.

As mentioned above you can shorten all of these, by using the case-insensitive modifier. Taking the first expression as an example:

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.I)

or

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.IGNORECASE)

depending on your preference.

I suggest that you do some reading through the tutorial I linked several times in this answer. The explanations are very comprehensive and should give you a good headstart on regular expressions, which you will probably encounter again sooner or later.

Convert from java.util.date to JodaTime

http://joda-time.sourceforge.net/quickstart.html

Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:

* Date - a JDK instant
* Calendar - a JDK calendar
* String - in ISO8601 format
* Long - in milliseconds
* any Joda-Time datetime class

Efficient way to do batch INSERTS with JDBC

You can use addBatch and executeBatch for batch insert in java See the Example : Batch Insert In Java

How to push both value and key into PHP array

I would like to add my answer to the table and here it is :

//connect to db ...etc
$result_product = /*your mysql query here*/ 
$array_product = array(); 
$i = 0;

foreach ($result_product as $row_product)
{
    $array_product [$i]["id"]= $row_product->id;
    $array_product [$i]["name"]= $row_product->name;
    $i++;
}

//you can encode the array to json if you want to send it to an ajax call
$json_product =  json_encode($array_product);
echo($json_product);

hope that this will help somebody

How to replace all spaces in a string

    $('#title').keyup(function () {
        var replaceSpace = $(this).val();

        var result = replaceSpace.replace(/\s/g, ";");

        $("#keyword").val(result);

    });

Since the javascript replace function do not replace 'all', we can make use the regular expression for replacement. As per your need we have to replace all space ie the \s in your string globally. The g character after the regular expressions represents the global replacement. The seond parameter will be the replacement character ie the semicolon.

Best way to iterate through a Perl array

If you only care about the elements of @Array, use:

for my $el (@Array) {
# ...
}

or

If the indices matter, use:

for my $i (0 .. $#Array) {
# ...
}

Or, as of perl 5.12.1, you can use:

while (my ($i, $el) = each @Array) {
# ...
}

If you need both the element and its index in the body of the loop, I would expect using each to be the fastest, but then you'll be giving up compatibility with pre-5.12.1 perls.

Some other pattern than these might be appropriate under certain circumstances.

JPA: unidirectional many-to-one and cascading delete

Create a bi-directional relationship, like this:

@Entity
public class Parent implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
    private Set<Child> children;
}

Generics/templates in python?

Since python is dynamically typed, this is super easy. In fact, you'd have to do extra work for your BinaryTree class not to work with any data type.

For example, if you want the key values which are used to place the object in the tree available within the object from a method like key() you just call key() on the objects. For example:

class BinaryTree(object):

    def insert(self, object_to_insert):
        key = object_to_insert.key()

Note that you never need to define what kind of class object_to_insert is. So long as it has a key() method, it will work.

The exception is if you want it to work with basic data types like strings or integers. You'll have to wrap them in a class to get them to work with your generic BinaryTree. If that sounds too heavy weight and you want the extra efficiency of actually just storing strings, sorry, that's not what Python is good at.

INSERT IF NOT EXISTS ELSE UPDATE?

You should use the INSERT OR IGNORE command followed by an UPDATE command: In the following example name is a primary key:

INSERT OR IGNORE INTO my_table (name, age) VALUES ('Karen', 34)
UPDATE my_table SET age = 34 WHERE name='Karen'

The first command will insert the record. If the record exists, it will ignore the error caused by the conflict with an existing primary key.

The second command will update the record (which now definitely exists)

jQuery CSS Opacity

try using .animate instead of .css or even just on the opacity one and leave .css on the display?? may b

jQuery(document).ready(function(){
if (jQuery('#nav .drop').animate('display') === 'block') {
    jQuery('#main').animate('opacity') = '0.6';

How to debug external class library projects in visual studio?

Assume the path of

Project A

C:\Projects\ProjectA

Project B

C:\Projects\ProjectB

and the dll of ProjectB is in

C:\Projects\ProjectB\bin\Debug\

To debug into ProjectB from ProjectA, do the following

  1. Copy B's dll with dll's .PDB to the ProjectA's compiling directory.
  2. Now debug ProjectA. When code reaches the part where you need to call dll's method or events etc while debugging, press F11 to step into the dll's code.

NOTE : DO NOT MISS TO COPY THE .PDB FILE

Word wrap for a label in Windows Forms

I would recommend setting AutoEllipsis property of label to true and AutoSize to false. If text length exceeds label bounds, it'll add three dots (...) at the end and automatically set the complete text as a tooltip. So users can see the complete text by hovering over the label.

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

With PostgreSQL 9.5, this is now native functionality (like MySQL has had for several years):

INSERT ... ON CONFLICT DO NOTHING/UPDATE ("UPSERT")

9.5 brings support for "UPSERT" operations. INSERT is extended to accept an ON CONFLICT DO UPDATE/IGNORE clause. This clause specifies an alternative action to take in the event of a would-be duplicate violation.

...

Further example of new syntax:

INSERT INTO user_logins (username, logins)
VALUES ('Naomi',1),('James',1) 
ON CONFLICT (username)
DO UPDATE SET logins = user_logins.logins + EXCLUDED.logins;

Changing Tint / Background color of UITabBar

I have been able to make it work by subclassing a UITabBarController and using private classes:

@interface UITabBarController (private)
- (UITabBar *)tabBar;
@end

@implementation CustomUITabBarController


- (void)viewDidLoad {
    [super viewDidLoad];

    CGRect frame = CGRectMake(0.0, 0.0, self.view.bounds.size.width, 48);
    UIView *v = [[UIView alloc] initWithFrame:frame];
    [v setBackgroundColor:kMainColor];
    [v setAlpha:0.5];
    [[self tabBar] addSubview:v];
    [v release];

}
@end

Calculate rolling / moving average in C++

I used a deque... seems to work for me. This example has a vector, but you could skip that aspect and simply add them to deque.

#include <deque>

template <typename T>
double mov_avg(vector<T> vec, int len){
  deque<T> dq = {};
  for(auto i = 0;i < vec.size();i++){
    if(i < len){
      dq.push_back(vec[i]);
    }
    else {
      dq.pop_front();
      dq.push_back(vec[i]);
    }
  }
  double cs = 0;
  for(auto i : dq){
    cs += i;
  }
  return cs / len;
}



//Skip the vector portion, track the input number (or size of deque), and the value.


  double len = 10;
  double val; //Accept as input
  double instance; //Increment each time input accepted.

  deque<double> dq;
  if(instance < len){
      dq.push_back(val);
  }
  else {
      dq.pop_front();
      dq.push_back(val);
    }
  }
  double cs = 0;
  for(auto i : dq){
    cs += i;
  }
  double rolling_avg = cs / len;

//To simplify further -- add values to this, then simply average the deque.

 int MAX_DQ = 3;
 void add_to_dq(deque<double> &dq, double value){
    if(dq.size() < MAX_DQ){
      dq.push_back(value);
    }else {
      dq.pop_front();
      dq.push_back(value);
    }
  }
 

Another sort of hack I use occasionally is using mod to overwrite values in a vector.

  vector<int> test_mod = {0,0,0,0,0};
  int write = 0;
  int LEN = 5;
  
  int instance = 0; //Filler for N -- of Nth Number added.
  int value = 0; //Filler for new number.

  write = instance % LEN;
  test_mod[write] = value;
  //Will write to 0, 1, 2, 3, 4, 0, 1, 2, 3, ...
  //Then average it for MA.

  //To test it...
  int write_idx = 0;
  int len = 5;
  int new_value;
  for(auto i=0;i<100;i++){
      cin >> new_value;
      write_idx = i % len;
      test_mod[write_idx] = new_value;

This last (hack) has no buckets, buffers, loops, nothing. Simply a vector that's overwritten. And it's 100% accurate (for avg / values in vector). Proper order is rarely maintained, as it starts rewriting backwards (at 0), so 5th index would be at 0 in example {5,1,2,3,4}, etc.

Difference between objectForKey and valueForKey?

Here's a great reason to use objectForKey: wherever possible instead of valueForKey: - valueForKey: with an unknown key will throw NSUnknownKeyException saying "this class is not key value coding-compliant for the key ".

npm install errors with Error: ENOENT, chmod

Ok it looks like NPM is using your .gitignore as a base for the .npmignore file, and thus ignores /lib. If you add a blank .npmignore file into the root of your application, everything should work.

[edit] - more info on this behaviour here: https://docs.npmjs.com/misc/developers#keeping-files-out-of-your-package

How do you change the width and height of Twitter Bootstrap's tooltips?

With Bootstrap 4 I use

.tooltip-inner {
    margin-left: 50%;
    max-width: 50%;
    width: 50%;
    min-width: 300px;
}

How to change the height of a <br>?

Here is a solution that works in IE, Firefox, and Chrome. The idea is to increase the font size of the br element from the body size of 14px to 18px, and lower the element by 4px so the extra size is below the text line. The result is 4px of extra whitespace below the br.

br 
{ 
font-size: 18px; 
vertical-align: -4px; 
}  

What is a regex to match ONLY an empty string?

As @Bohemian and @mbomb007 mentioned before, this works AND has the additional advantage of being more readable:

console.log(/^(?!.)/s.test("")); //true

Breaking to a new line with inline-block?

If you're OK with not using <p>s (only <div>s and <span>s), this solution might even allow you to align your inline-blocks center or right, if you want to (or just keep them left, the way you originally asked for). While the solution might still work with <p>s, I don't think the resulting HTML code would be quite correct, but it's up to you anyways.

The trick is to wrap each one of your <span>s with a corresponding <div>. This way we're taking advantage of the line break caused by the <div>'s display: block (default), while still keeping the visual green box tight to the limits of the text (with your display: inline-block declaration).

_x000D_
_x000D_
.text span {_x000D_
   background:rgba(165, 220, 79, 0.8);_x000D_
   display:inline-block;_x000D_
   padding:7px 10px;_x000D_
   color:white;_x000D_
}_x000D_
.large {  font-size:80px }
_x000D_
<div class="text">_x000D_
  <div><span class="medium">We</span></div>_x000D_
  <div><span class="large">build</span></div>_x000D_
  <div><span class="medium">the</span></div>_x000D_
  <div><span class="large">Internet</span></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can I have multiple Xcode versions installed?

  1. First, remove the current Xcode installation from your machine. You can probably skip this step but I wanted to start fresh. Plus — Xcode was behaving a little weird lately so this is a good opportunity to do that.
  2. Install Xcode 8 from the App Store. Make sure project files (.xcodeproj) and workspace files (.xcworkspace) can be opened with the new Xcode installation (remember to select the Later option whenever prompted).
  3. Download the Xcode 7.3.1 dmg file from Apple. Double-tap the newly downloaded dmg file in order to get the standard “Drag to install Xcode in your Applications folder”. Don’t do that. Instead, drag the Xcode icon to the desktop. Change the file name to Xcode 7.3.1. Now drag it to the Applications folder.

Now you have two versions of Xcode installed on your machine. Xcode 7.3.1 and Xcode 8.

Details: Install Xcode 7 & Xcode 8 side by side

Steps to send a https request to a rest service in Node js

Note if you are using https.request do not directly use the body from res.on('data',... This will fail if you have a large data coming in chunks. So you need to concatenate all the data and then process the response in res.on('end'. Example -

  var options = {
    hostname: "www.google.com",
    port: 443,
    path: "/upload",
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(post_data)
    }
  };

  //change to http for local testing
  var req = https.request(options, function (res) {
    res.setEncoding('utf8');

    var body = '';

    res.on('data', function (chunk) {
      body = body + chunk;
    });

    res.on('end',function(){
      console.log("Body :" + body);
      if (res.statusCode != 200) {
        callback("Api call failed with response code " + res.statusCode);
      } else {
        callback(null);
      }
    });

  });

  req.on('error', function (e) {
    console.log("Error : " + e.message);
    callback(e);
  });

  // write data to request body
  req.write(post_data);
  req.end();

How to do an INNER JOIN on multiple columns

If you want to search on both FROM and TO airports, you'll want to join on the Airports table twice - then you can use both from and to tables in your results set:

SELECT
   Flights.*,fromAirports.*,toAirports.*
FROM
   Flights
INNER JOIN 
   Airports fromAirports on Flights.fairport = fromAirports.code
INNER JOIN 
   Airports toAirports on Flights.tairport = toAirports.code
WHERE
 ...

How/When does Execute Shell mark a build as failure in Jenkins?

First things first, hover the mouse over the grey area below. Not part of the answer, but absolutely has to be said:

If you have a shell script that does "checkout, build, deploy" all by itself, then why are you using Jenkins? You are foregoing all the features of Jenkins that make it what it is. You might as well have a cron or an SVN post-commit hook call the script directly. Jenkins performing the SVN checkout itself is crucial. It allows the builds to be triggered only when there are changes (or on timer, or manual, if you prefer). It keeps track of changes between builds. It shows those changes, so you can see which build was for which set of changes. It emails committers when their changes caused successful or failed build (again, as configured as you prefer). It will email committers when their fixes fixed the failing build. And more and more. Jenkins archiving the artifacts also makes them available, per build, straight off Jenkins. While not as crucial as the SVN checkout, this is once again an integral part of what makes it Jenkins. Same with deploying. Unless you have a single environment, deployment usually happens to multiple environments. Jenkins can keep track of which environment a specific build (with specific set of SVN changes) is deployed it, through the use of Promotions. You are foregoing all of this. It sounds like you are told "you have to use Jenkins" but you don't really want to, and you are doing it just to get your bosses off your back, just to put a checkmark "yes, I've used Jenkins"

The short answer is: the exit code of last command of the Jenkin's Execute Shell build step is what determines the success/failure of the Build Step. 0 - success, anything else - failure. Note, this is determining the success/failure of the build step, not the whole job run. The success/failure of the whole job run can further be affected by multiple build steps, and post-build actions and plugins.

You've mentioned Build step 'Execute shell' marked build as failure, so we will focus just on a single build step. If your Execute shell build step only has a single line that calls your shell script, then the exit code of your shell script will determine the success/failure of the build step. If you have more lines, after your shell script execution, then carefully review them, as they are the ones that could be causing failure.

Finally, have a read here Jenkins Build Script exits after Google Test execution. It is not directly related to your question, but note that part about Jenkins launching the Execute Shell build step, as a shell script with /bin/sh -xe

The -e means that the shell script will exit with failure, even if just 1 command fails, even if you do error checking for that command (because the script exits before it gets to your error checking). This is contrary to normal execution of shell scripts, which usually print the error message for the failed command (or redirect it to null and handle it by other means), and continue.

To circumvent this, add set +e to the top of your shell script.

Since you say your script does all it is supposed to do, chances are the failing command is somewhere at the end of the script. Maybe a final echo? Or copy of artifacts somewhere? Without seeing the full console output, we are just guessing.

Please post the job run's console output, and preferably the shell script itself too, and then we could tell you exactly which line is failing.

Disable Laravel's Eloquent timestamps

You either have to declare public $timestamps = false; in every model, or create a BaseModel, define it there, and have all your models extend it instead of eloquent. Just bare in mind pivot tables MUST have timestamps if you're using Eloquent.

Update: Note that timestamps are no longer REQUIRED in pivot tables after Laravel v3.

Update: You can also disable timestamps by removing $table->timestamps() from your migration.

Git: Could not resolve host github.com error while cloning remote repository in git

do i need to configure proxy settings? because my office has got proxy servers.

Yes, you can do so by setting HTTP_PROXY, and HTTPS_PROXY environment variables.

See "Syncing with github":

set HTTPS_PROXY=http://<login_internet>:<password_internet>@aproxy:aport
set HTTP_PROXY=http://<login_internet>:<password_internet>@aproxy:aport
set NO_PROXY=localhost,my.company

(To avoid putting your credentials -- username/password -- in clear in the proxy URL, see below)

Note the NO_PROXY, to allow to access internal site to your company

You also can register that in your git config:

git config --global http.proxy http://<login_internet>:<password_internet>@aproxy:aport

But if you have incorrect proxy Git settings, remove them:

cd /path/to/repo
git config --unset http.proxy
git config --global --unset http.proxy
git config --system --unset http.proxy

git config --unset https.proxy
git config --global --unset https.proxy
git config --system --unset https.proxy

# double-check with:
git config -l --show-origin | grep -i proxy

No credentials needed: use genotrance/px.
If you are, as I am, in a company behind a NTLM proxy, all you need to do is:

  • unzip px-v0.4.0.zip anywhere you want
  • change the px.ini config file (put it in %USERPROFILE%), chaging the server line:
    [proxy]
    server = proxy.my.company:8080  <= use your company proxy:port
    listen = 127.0.0.1
    port = 3128
    
  • use HTTP(S) proxy variable without your credentials! (the px proxy will reuse the ones from the current Widows session, either through Microsoft SSPI or Microsoft Kerberos)

That will give you:

set HTTPS_PROXY=http://127.0.0.1:3128
set HTTP_PROXY=http://127.0.0.1:3128
set NO_PROXY=localhost,my.company

Not able to access adb in OS X through Terminal, "command not found"

If you are using zsh on an OS X, you have to edit the zshrc file.

Use vim or your favorite text editor to open zshrc file:

vim ~/.zshrc

Paste the path to adb in this file:

export PATH="/Users/{$USER}/Library/Android/sdk/platform-tools":$PATH

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

Best practices for SQL varchar column length

Whenever I set up a new SQL table I feel the same way about 2^n being more "even"... but to sum up the answers here, there is no significant impact on storage space simply by defining varchar(2^n) or even varchar(MAX).

That said, you should still anticipate the potential implications on storage and performance when setting a high varchar() limit. For example, let's say you create a varchar(MAX) column to hold product descriptions with full-text indexing. If 99% of descriptions are only 500 characters long, and then suddenly you get somebody who replaces said descriptions with wikipedia articles, you may notice unanticipated significant storage and performance hits.

Another thing to consider from Bill Karwin:

There's one possible performance impact: in MySQL, temporary tables and MEMORY tables store a VARCHAR column as a fixed-length column, padded out to its maximum length. If you design VARCHAR columns much larger than the greatest size you need, you will consume more memory than you have to. This affects cache efficiency, sorting speed, etc.

Basically, just come up with reasonable business constraints and error on a slightly larger size. As @onedaywhen pointed out, family names in UK are usually between 1-35 characters. If you decide to make it varchar(64), you're not really going to hurt anything... unless you're storing this guy's family name that's said to be up to 666 characters long. In that case, maybe varchar(1028) makes more sense.

And in case it's helpful, here's what varchar 2^5 through 2^10 might look like if filled:

varchar(32)     Lorem ipsum dolor sit amet amet.

varchar(64)     Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie

varchar(128)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas

varchar(256)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt

varchar(512)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt
                dolor tellus, sit amet porta neque varius vitae. Seduse molestie
                lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
                mollis diam pretium gravida. In facilisis vitae tortor id vulput
                ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie

varchar(1024)   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt
                dolor tellus, sit amet porta neque varius vitae. Seduse molestie
                lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
                mollis diam pretium gravida. In facilisis vitae tortor id vulput
                ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie
                dapibus leo lobortis eleifend. Vivamus vitae diam turpis. Vivamu
                nec tristique magna, vel tincidunt diam. Maecenas elementum semi
                quam. In ut est porttitor, sagittis nulla id, fermentum turpist.
                Curabitur pretium nibh a imperdiet cursus. Sed at vulputate este
                proin fermentum pretium justo, ac malesuada eros et Pellentesque
                vulputate hendrerit molestie. Aenean imperdiet a enim at finibus
                fusce ut ullamcorper risus, a cursus massa. Nunc non dapibus vel
                Lorem ipsum dolor sit amet, consectetur Praesent ut ultrices sit

Invalid shorthand property initializer

Change the = to : to fix the error.

var makeRequest = function(message) {<br>
 var options = {<br>
  host: 'localhost',<br>
  port : 8080,<br>
  path : '/',<br>
  method: 'POST'<br>
 }

How to uninstall Apache with command line

If Apache was installed using NSIS installer it should have left an uninstaller. You should search inside Apache installation directory for executable named unistaller.exe or something like that. NSIS uninstallers support /S flag by default for silent uninstall. So you can run something like "C:\Program Files\<Apache installation dir here>\uninstaller.exe" /S

From NSIS documentation:

3.2.1 Common Options

/NCRC disables the CRC check, unless CRCCheck force was used in the script. /S runs the installer or uninstaller silently. See section 4.12 for more information. /D sets the default installation directory ($INSTDIR), overriding InstallDir and InstallDirRegKey. It must be the last parameter used in the command line and must not contain any quotes, even if the path contains spaces. Only absolute paths are supported.

How can I get the last character in a string?

Javascript strings have a length property that will tell you the length of the string.

Then all you have to do is use the substr() function to get the last character:

var myString = "Test3";
var lastChar = myString.substr(myString.length -1);

edit: yes, or use the array notation as the other posts before me have done.

Lots of String functions explained here

printf formatting (%d versus %u)

You can find a list of formatting escapes on this page.

%d is a signed integer, while %u is an unsigned integer. Pointers (when treated as numbers) are usually non-negative.

If you actually want to display a pointer, use the %p format specifier.

Grant all on a specific schema in the db to a group role in PostgreSQL

My answer is similar to this one on ServerFault.com.

To Be Conservative

If you want to be more conservative than granting "all privileges", you might want to try something more like these.

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;

The use of public there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.

Access to the Schema

To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.

You will not notice this requirement when first using Postgres. By default every database has a first schema named public. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.

GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;

Excerpt from the Postgres doc:

For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.

For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.

Existing Objects Versus Future

These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.

Use Font Awesome icon as CSS content

a:before {
     content: "\f055";
     font-family: FontAwesome;
     left:0;
     position:absolute;
     top:0;
}

Example Link: https://codepen.io/bungeedesign/pen/XqeLQg

Get Icon code from: https://fontawesome.com/cheatsheet?from=io

Move to next item using Java 8 foreach loop in stream

Another solution: go through a filter with your inverted conditions : Example :

if(subscribtion.isOnce() && subscribtion.isCalled()){
                continue;
}

can be replaced with

.filter(s -> !(s.isOnce() && s.isCalled()))

The most straightforward approach seem to be using "return;" though.

Iterating over arrays in Python 3

While iterating over a list or array with this method:

ar = [10, 11, 12]
for i in ar:
    theSum = theSum + ar[i]

You are actually getting the values of list or array sequentially in i variable. If you print the variable i inside the for loop. You will get following output:

10
11
12

However, in your code you are confusing i variable with index value of array. Therefore, while doing ar[i] will mean ar[10] for the first iteration. Which is of course index out of range throwing IndexError

Edit You can read this for better understanding of different methods of iterating over array or list in Python

Cannot install Aptana Studio 3.6 on Windows

I had this issue and it was because of limited internet connection to source. You can use a proxy (VPN) but the better solution is download manually NodeJs from the source https://nodejs.org/download/ and Git, too.

after installation manually, aptana will check if they installed or not.

How to stop docker under Linux

The output of ps aux looks like you did not start docker through systemd/systemctl.

It looks like you started it with:

sudo dockerd -H gridsim1103:2376

When you try to stop it with systemctl, nothing should happen as the resulting dockerd process is not controlled by systemd. So the behavior you see is expected.

The correct way to start docker is to use systemd/systemctl:

systemctl enable docker
systemctl start docker

After this, docker should start on system start.

EDIT: As you already have the docker process running, simply kill it by pressing CTRL+C on the terminal you started it. Or send a kill signal to the process.

Save matplotlib file to a directory

If the directory you wish to save to is a sub-directory of your working directory, simply specify the relative path before your file name:

    fig.savefig('Sub Directory/graph.png')

If you wish to use an absolute path, import the os module:

    import os
    my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.
    ...
    fig.savefig(my_path + '/Sub Directory/graph.png')

If you don't want to worry about the leading slash in front of the sub-directory name, you can join paths intelligently as follows:

    import os
    my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.
    my_file = 'graph.png'
    ...
    fig.savefig(os.path.join(my_path, my_file))        

500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid

In my case I needed to install the IIS URL rewrite module 2.0 because it is being used in the web.config and this was the first time running site on new machine.

How can I scroll a web page using selenium webdriver in python?

same method as shown here:

in python you can just use

driver.execute_script("window.scrollTo(0, Y)")

(Y is the vertical position you want to scroll to)

const vs constexpr on variables

No difference here, but it matters when you have a type that has a constructor.

struct S {
    constexpr S(int);
};

const S s0(0);
constexpr S s1(1);

s0 is a constant, but it does not promise to be initialized at compile-time. s1 is marked constexpr, so it is a constant and, because S's constructor is also marked constexpr, it will be initialized at compile-time.

Mostly this matters when initialization at runtime would be time-consuming and you want to push that work off onto the compiler, where it's also time-consuming, but doesn't slow down execution time of the compiled program

html cellpadding the left side of a cell

I choose to use both methods. Cellpadding on the table as a fallback in case the inline style doesn't stick and inline style for most clients.

_x000D_
_x000D_
<table cellpadding="5">_x000D_
  <tr>_x000D_
    <td style='padding:5px 10px 5px 5px'>Content</td>_x000D_
    <td style='padding:5px 10px 5px 5px'>Content</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

ListView item background via custom selector

I've been frustrated by this myself and finally solved it. As Romain Guy hinted to, there's another state, "android:state_selected", that you must use. Use a state drawable for the background of your list item, and use a different state drawable for listSelector of your list:

list_row_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:background="@drawable/listitem_background"
    >
...
</LinearLayout>

listitem_background.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@color/android:transparent" />
    <item android:drawable="@drawable/listitem_normal" />
</selector>

layout.xml that includes the ListView:

...
<ListView 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:listSelector="@drawable/listitem_selector"
   />
...

listitem_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/listitem_pressed" />
    <item android:state_focused="true" android:drawable="@drawable/listitem_selected" />
</selector>

How can I create keystore from an existing certificate (abc.crt) and abc.key files?

Adding to @MK Yung and @Bruno's answer.. Do enter a password for the destination keystore. I saw my console hanging when I entered the command without a password.

openssl pkcs12 -export -in abc.crt -inkey abc.key -out abc.p12 -name localhost  -passout pass:changeit

Get property value from string using reflection

You never mention what object you are inspecting, and since you are rejecting ones that reference a given object, I will assume you mean a static one.

using System.Reflection;
public object GetPropValue(string prop)
{
    int splitPoint = prop.LastIndexOf('.');
    Type type = Assembly.GetEntryAssembly().GetType(prop.Substring(0, splitPoint));
    object obj = null;
    return type.GetProperty(prop.Substring(splitPoint + 1)).GetValue(obj, null);
}

Note that I marked the object that is being inspected with the local variable obj. null means static, otherwise set it to what you want. Also note that the GetEntryAssembly() is one of a few available methods to get the "running" assembly, you may want to play around with it if you are having a hard time loading the type.

How to run TypeScript files from command line?

We have following steps:

  1. First you need to install typescript

    npm install -g typescript
    
  2. Create one file helloworld.ts

    function hello(person){
       return "Hello, " + person;
    }
    let user = "Aamod Tiwari";
    const result = hello(user);
    console.log("Result", result)
    
  3. Open command prompt and type the following command

    tsc helloworld.ts
    
  4. Again run the command

    node helloworld.js
    
  5. Result will display on console

How to put text in the upper right, or lower right corner of a "box" using css

<style>
  #content { width: 300px; height: 300px; border: 1px solid black; position: relative; }
  .topright { position: absolute; top: 5px; right: 5px; text-align: right; }
  .bottomright { position: absolute; bottom: 5px; right: 5px; text-align: right; }
</style>
<div id="content">
  <div class="topright">here</div>
  <div class="bottomright">and here</div>
  Lorem ipsum etc................
</div>

Removing duplicate elements from an array in Swift

swift 2

with uniq function answer:

func uniq<S: SequenceType, E: Hashable where E==S.Generator.Element>(source: S) -> [E] {
    var seen: [E:Bool] = [:]
    return source.filter({ (v) -> Bool in
        return seen.updateValue(true, forKey: v) == nil
    })
}

use:

var test = [1,2,3,4,5,6,7,8,9,9,9,9,9,9]
print(uniq(test)) //1,2,3,4,5,6,7,8,9

How to decode a Base64 string?

I had issues with spaces showing in between my output and there was no answer online at all to fix this issue. I literally spend many hours trying to find a solution and found one from playing around with the code to the point that I almost did not even know what I typed in at the time that I got it to work. Here is my fix for the issue: [System.Text.Encoding]::UTF8.GetString(([System.Convert]::FromBase64String($base64string)|?{$_}))

How to change Screen buffer size in Windows Command Prompt from batch script

Here's what I did in case someone finds it useful (I used a lot of things according to the rest of the answers in this thread):

First I adjusted the layout settings as needed. This changes the window size immediately so it was easier to set the exact size that I wanted. By the way I didn't know that I can also have visible width smaller than width buffer. This was nice since I usually hate a long line to be wrapped. enter image description here

Then after clicking ok, I opened regedit.exe and went to "HKEY_CURRENT_USER\Console". There is a new child entry there "%SystemRoot%_system32_cmd.exe". I right clicked on that and selected Export: enter image description here

I saved this as "cmd_settings.reg". Then I created a batch script that imports those settings, invokes my original batch script (name batch_script.bat) and then deletes what I imported in order for the command line window to return to default settings:

regedit /s cmd_settings.reg
start /wait batch_script.bat
reg delete "HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_cmd.exe" /f

This is a sample batch that could be invoked ("batch_script.bat"):

@echo off
echo test!
pause
exit

Don't forget the exit command at the end of your script if you want the reg delete line to run after the script execution.

Summernote image upload

I tested this code and Works

Javascript

<script>
$(document).ready(function() {
  $('#summernote').summernote({
    height: 200,
    onImageUpload: function(files, editor, welEditable) {
      sendFile(files[0], editor, welEditable);
    }
  });

  function sendFile(file, editor, welEditable) {
    data = new FormData();
    data.append("file", file);
    $.ajax({
      data: data,
      type: "POST",
      url: "Your URL POST (php)",
      cache: false,
      contentType: false,
      processData: false,
      success: function(url) {
        editor.insertImage(welEditable, url);
      }
    });
  }
});
</script>

PHP

if ($_FILES['file']['name']) {
  if (!$_FILES['file']['error']) {
    $name = md5(rand(100, 200));
    $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    $filename = $name.
    '.'.$ext;
    $destination = '/assets/images/'.$filename; //change this directory
    $location = $_FILES["file"]["tmp_name"];
    move_uploaded_file($location, $destination);
    echo 'http://test.yourdomain.al/images/'.$filename; //change this URL
  } else {
    echo $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
  }
}

Update:

After 0.7.0 onImageUpload should be inside callbacks option as mentioned by @tugberk

$('#summernote').summernote({
    height: 200,
    callbacks: {
        onImageUpload: function(files, editor, welEditable) {
            sendFile(files[0], editor, welEditable);
        }
    }
});

What is the lifetime of a static variable in a C++ function?

FWIW, Codegear C++Builder doesn't destruct in the expected order according to the standard.

C:\> sample.exe 1 2
Created in foo
Created in if
Destroyed in foo
Destroyed in if

... which is another reason not to rely on the destruction order!

How to sum the values of a JavaScript object?

Now you can make use of reduce function and get the sum.

_x000D_
_x000D_
const object1 = { 'a': 1 , 'b': 2 , 'c':3 }_x000D_
_x000D_
console.log(Object.values(object1).reduce((a, b) => a + b, 0));
_x000D_
_x000D_
_x000D_

size of struct in C

The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).

For example:

struct foo_t {
    int x;
    char c;
};

Even though the c field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8 (on a 32-bit system - rather a system with a 32-bit int type) because there will need to be 3 bytes of padding after the c field.

Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.

How to specify maven's distributionManagement organisation wide?

There's no need for a parent POM.

You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.

To do it on the build server, just pass to the mvn command:

-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases

See https://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html for details which options can be set.

It's also possible to set this in your settings.xml.

Just create a profile there which is enabled and contains the property.

Example settings.xml:

<settings>
[...]
  <profiles>
    <profile>
      <id>nexus</id>
      <properties>
        <altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
        <altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
      </properties>
    </profile>
  </profiles>

  <activeProfiles>
    <activeProfile>nexus</activeProfile>
  </activeProfiles>

</settings>

Make sure that credentials for "snapshots" and "releases" are in the <servers> section of your settings.xml

The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message

Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter

To fix this, you can enforce a newer version of the plug-in:

        <build>
          <pluginManagement>
            <plugins>
              <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8</version>
              </plugin>
            </plugins>
          </pluginManagement>
        </build>

How to plot all the columns of a data frame in R

Using some of the tips above (especially thanks @daroczig for the names(df)[i] form) this function prints a histogram for numeric variables and a bar chart for factor variables. A good start to exploring a data frame:

par(mfrow=c(3,3),mar=c(2,1,1,1)) #my example has 9 columns

dfplot <- function(data.frame)
{
  df <- data.frame
  ln <- length(names(data.frame))
  for(i in 1:ln){
    mname <- substitute(df[,i])
      if(is.factor(df[,i])){
        plot(df[,i],main=names(df)[i])}
        else{hist(df[,i],main=names(df)[i])}
  }
}

Best wishes, Mat.

How to add System.Windows.Interactivity to project?

I have had the exact same problem with a solution, that System.Windows.Interactivity was required for one of the project in Visual Studio 2019, and I tried to install Blend for Visual Studio SDK for .NET from Visual Studio 2019 Individual components, but it did not exist in it.

The consequence of that, I was not able to build the project in my solution with repetitive of following similar error on different XAML parts of the project:

The tag 'Interaction.Behaviors' does not exist in XML namespace 'clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity'.

Image with all errors The above mentioned errors snapshot example

The solution, the way I solved it, is by installing Microsoft Expression Blend Software Development Kit (SDK) for .NET 4 from Microsoft.

Thanks to my colleague @felza, mentioned that System.Windows.Interactivity requires this sdk, that is suppose to be located in this folder:

C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0

In my case it was not installed. I have had this folder C:\Program Files (x86)\Microsoft SDKs with out Expression\Blend\.NETFramework\v4.0 folder inside it.

After installing it, all errors disappeared.

Link error "undefined reference to `__gxx_personality_v0'" and g++

If g++ still gives error Try using:

g++ file.c -lstdc++

Look at this post: What is __gxx_personality_v0 for?

Make sure -lstdc++ is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.

Get value of Span Text

You need to change your code as below:

<html>
<body>

<span id="span_Id">Click the button to display the content.</span>

<button onclick="displayDate()">Click Me</button>

<script>
function displayDate() {
   var span_Text = document.getElementById("span_Id").innerText;
   alert (span_Text);
}
</script>
</body>
</html>

Proper indentation for Python multiline strings

It depends on how you want the text to display. If you want it all to be left-aligned then either format it as in the first snippet or iterate through the lines left-trimming all the space.

How to convert comma separated string into numeric array in javascript

just you need to use couple of methods for this, that's it!

var strVale = "130,235,342,124";
var resultArray = strVale.split(',').map(function(strVale){return Number(strVale);});

the output will be the array of numbers.

XSS filtering function in PHP

htmlspecialchars() is perfectly adequate for filtering user input that is displayed in html forms.

How To Show And Hide Input Fields Based On Radio Button Selection

Using the visibility property only affects the visibility of the elements on the page; they will still be there in the page layout. To completely remove the elements from the page, use the display property.

display:none // for hiding
display:block // for showing

Make sure to change your css file to use display instead of visibility too.

As for the javascript (this is not jQuery), make sure you hide the options by default when the page loads:

<script type="text/javascript">
    window.onload = function() {
        document.getElementById('ifYes').style.display = 'none';
    }

    function yesnoCheck() {
        if (document.getElementById('yesCheck').checked) {
            document.getElementById('ifYes').style.display = 'block';
        } 
        else {
            document.getElementById('ifYes').style.display = 'none';
        }
    }

</script>

If you haven't done so already, I would recommend taking a look at jQuery. jQuery code is much clearer and easier to write and understand.

http://www.w3schools.com/jquery/default.asp

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

Check if an apt-get package is installed and then install it if it's not on Linux

which <command>
if [ $? == 1 ]; then
    <pkg-manager> -y install <command>
fi

How to match any non white space character except a particular one?

On my system: CentOS 5

I can use \s outside of collections but have to use [:space:] inside of collections. In fact I can use [:space:] only inside collections. So to match a single space using this I have to use [[:space:]] Which is really strange.

echo a b cX | sed -r "s/(a\sb[[:space:]]c[^[:space:]])/Result: \1/"

Result: a b cX
  • first space I match with \s
  • second space I match alternatively with [[:space:]]
  • the X I match with "all but no space" [^[:space:]]

These two will not work:

a[:space:]b  instead use a\sb or a[[:space:]]b

a[^\s]b      instead use a[^[:space:]]b

Python slice first and last element in list

Utilize the packing/unpacking operator to pack the middle of the list into a single variable:

>>> l = ['1', 'B', '3', 'D', '5', 'F']
>>> first, *middle, last = l
>>> first
'1'
>>> middle
['B', '3', 'D', '5']
>>> last
'F'
>>> 

Or, if you want to discard the middle:

>>> l = ['1', 'B', '3', 'D', '5', 'F']
>>> first, *_, last = l
>>> first
'1'
>>> last
'F'
>>> 

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

For me I switched a call for my collection view header where I was registering the nib to registering the class. That fixed it.

How does the getView() method work when creating your own custom adapter?

  1. Layout inflator inflates/adds external XML to your current view.

  2. getView() is called numerous times including when scrolled. So if it already has view inflated we don't wanna do it again since inflating is a costly process.. thats why we check if its null and then inflate it.

  3. The parent view is single cell of your List..

How do I set ANDROID_SDK_HOME environment variable?

Copy your SDK path and assign it to the environment variable ANDROID_SDK_ROOT

Refer pic below:

enter image description here

Open File in Another Directory (Python)

import os
import os.path
import shutil

You find your current directory:

d = os.getcwd() #Gets the current working directory

Then you change one directory up:

os.chdir("..") #Go up one directory from working directory

Then you can get a tupple/list of all the directories, for one directory up:

o = [os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] # Gets all directories in the folder as a tuple

Then you can search the tuple for the directory you want and open the file in that directory:

for item in o:
    if os.path.exists(item + '\\testfile.txt'):
    file = item + '\\testfile.txt'

Then you can do stuf with the full file path 'file'

ERROR 1049 (42000): Unknown database

blog_development doesn't exist

You can see this in sql by the 0 rows affected message

create it in mysql with

mysql> create database blog_development

However as you are using rails you should get used to using

$ rake db:create

to do the same task. It will use your database.yml file settings, which should include something like:

development:
  adapter: mysql2
  database: blog_development
  pool: 5

Also become familiar with:

$ rake db:migrate  # Run the database migration
$ rake db:seed     # Run thew seeds file create statements
$ rake db:drop     # Drop the database

JPA Hibernate One-to-One relationship

Try this

@Entity

@Table(name="tblperson")

public class Person {

public int id;

public OtherInfo otherInfo;
@Id //Here Id is autogenerated
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}

@OneToOne(cascade = CascadeType.ALL,targetEntity=OtherInfo.class)
@JoinColumn(name="otherInfo_id") //there should be a column otherInfo_id in Person
public OtherInfo getOtherInfo() {
    return otherInfo;
}
public void setOtherInfo(OtherInfo otherInfo) {
    this.otherInfo= otherInfo;
}
rest of attributes ...
}


@Entity

@Table(name="tblotherInfo")

public class OtherInfo {

private int id;

private Person person;

@Id

@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}

  @OneToOne(mappedBy="OtherInfo",targetEntity=Person.class)   
public College getPerson() {
    return person;
}
public void setPerson(Person person) {
    this.person = person;
}    
 rest of attributes ...
}

const to Non-const Conversion in C++

void SomeClass::changeASettingAndCallAFunction() const {
    someSetting = 0; //Can't do this
    someFunctionThatUsesTheSetting();
}

Another solution is to call said function in-between making edits to variables that the const function uses. This idea was what solved my problem being as I was not inclined to change the signature of the function and had to use the "changeASettingAndCallAFunction" method as a mediator:

When you call the function you can first make edits to the setting before the call, or (if you aren't inclined to mess with the invoking place) perhaps call the function where you need the change to the variable to be propagated (like in my case).

void SomeClass::someFunctionThatUsesTheSetting() const {
     //We really don't want to touch this functions implementation
     ClassUsesSetting* classUsesSetting = ClassUsesSetting::PropagateAcrossClass(someSetting);
     /*
         Do important stuff
     */
}

void SomeClass::changeASettingAndCallAFunction() const {
     someFunctionThatUsesTheSetting();
     /*
         Have to do this
     */
}

void SomeClass::nonConstInvoker(){
    someSetting = 0;
    changeASettingAndCallAFunction();
}

Now, when some reference to "someFunctionThatUsesTheSetting" is invoked, it will invoke with the change to someSetting.

Cannot download Docker images behind a proxy

On Ubuntu you need to set the http_proxy for the Docker daemon, not the client process. This is done in /etc/default/docker (see here).

How do you post to an iframe?

An iframe is used to embed another document inside a html page.

If the form is to be submitted to an iframe within the form page, then it can be easily acheived using the target attribute of the tag.

Set the target attribute of the form to the name of the iframe tag.

<form action="action" method="post" target="output_frame">
    <!-- input elements here --> 
</form>
<iframe name="output_frame" src="" id="output_frame" width="XX" height="YY">
</iframe>           

Advanced iframe target use
This property can also be used to produce an ajax like experience, especially in cases like file upload, in which case where it becomes mandatory to submit the form, in order to upload the files

The iframe can be set to a width and height of 0, and the form can be submitted with the target set to the iframe, and a loading dialog opened before submitting the form. So, it mocks a ajax control as the control still remains on the input form jsp, with the loading dialog open.

Exmaple

<script>
$( "#uploadDialog" ).dialog({ autoOpen: false, modal: true, closeOnEscape: false,                 
            open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); } });

function startUpload()
{            
    $("#uploadDialog").dialog("open");
}

function stopUpload()
{            
    $("#uploadDialog").dialog("close");
}
</script>

<div id="uploadDialog" title="Please Wait!!!">
            <center>
            <img src="/imagePath/loading.gif" width="100" height="100"/>
            <br/>
            Loading Details...
            </center>
 </div>

<FORM  ENCTYPE="multipart/form-data" ACTION="Action" METHOD="POST" target="upload_target" onsubmit="startUpload()"> 
<!-- input file elements here--> 
</FORM>

<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;" onload="stopUpload()">   
        </iframe>

npm - how to show the latest version of a package

The npm view <pkg> version prints the last version by release date. That might very well be an hotfix release for a older stable branch at times.

The solution is to list all versions and fetch the last one by version number

$ npm view <pkg> versions --json | jq -r '.[-1]'

Or with awk instead of jq:

$ npm view <pkg> --json  | awk '/"$/{print gensub("[ \"]", "", "G")}'

How to Display Selected Item in Bootstrap Button Dropdown Title

you need to use add class open in <div class="btn-group open">

and in li add class="active"

Python name 'os' is not defined

Just add:

import os

in the beginning, before:

from settings import PROJECT_ROOT

This will import the python's module os, which apparently is used later in the code of your module without being imported.

Django TemplateDoesNotExist?

I'm embarrassed to admit this, but the problem for me was that a template had been specified as ….hml instead of ….html. Watch out!

PHP - If variable is not empty, echo some html code

i hope this will work too, try using"is_null"

<?php 
$web = the_field('website');
if (!is_null($web)) {
?>

....html code here

<?php
} else { 
    echo "Niente";
}
?>

http://php.net/manual/en/function.is-null.php

hope that suits you..

How to open a new tab using Selenium WebDriver

Check this complete example to understand how to open multiple tabs and switch between the tabs and at the end close all tabs.

public class Tabs {

    WebDriver driver;

    Robot rb;

    @BeforeTest
    public void setup() throws Exception {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Anuja.AnujaPC\\Downloads\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.get("http://qaautomated.com");
    }

    @Test
    public void openTab() {
        // Open tab 2 using CTRL + T keys.
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

        // Open URL In 2nd tab.
        driver.get("http://www.qaautomated.com/p/contact.html");

        // Call switchToTab() method to switch to the first tab
        switchToTab();

        // Call switchToTab() method to switch to the second tab.
        switchToTab();
    }

    public void switchToTab() {
        // Switching between tabs using CTRL + tab keys.
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");

        // Switch to current selected tab's content.
        driver.switchTo().defaultContent();
    }

    @AfterTest
    public void closeTabs() throws AWTException {
        // Used Robot class to perform ALT + SPACE + 'c' keypress event.
        rb = new Robot();
        rb.keyPress(KeyEvent.VK_ALT);
        rb.keyPress(KeyEvent.VK_SPACE);
        rb.keyPress(KeyEvent.VK_C);
    }

}

This example is given by this web page.

MSOnline can't be imported on PowerShell (Connect-MsolService error)

After hours of searching and trying I found out that on a x64 server the MSOnline modules must be installed for x64, and some programs that need to run them are using the x86 PS version, so they will never find it.

[SOLUTION] What I did to solve the issue was:

Copy the folders called MSOnline and MSOnline Extended from the source

C:\Windows\System32\WindowsPowerShell\v1.0\Modules\

to the folder

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\

And then in PS run the Import-Module MSOnline, and it will automatically get the module :D

running a command as a super user from a python script

I tried all the solutions, but did not work. Wanted to run long running tasks with Celery but for these I needed to run sudo chown command with subprocess.call().

This is what worked for me:

To add safe environment variables, in command line, type:

export MY_SUDO_PASS="user_password_here"

To test if it's working type:

echo $MY_SUDO_PASS
 > user_password_here

To run it at system startup add it to the end of this file:

nano ~/.bashrc  

#.bashrc
...
existing_content:

  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi
...

export MY_SUDO_PASS="user_password_here"

You can add all your environment variables passwords, usernames, host, etc here later.

If your variables are ready you can run:

To update:

echo $MY_SUDO_PASS | sudo -S apt-get update

Or to install Midnight Commander

echo $MY_SUDO_PASS | sudo -S apt-get install mc

To start Midnight Commander with sudo

echo $MY_SUDO_PASS | sudo -S mc

Or from python shell (or Django/Celery), to change directory ownership recursively:

python
>> import subprocess
>> subprocess.call('echo $MY_SUDO_PASS | sudo -S chown -R username_here /home/username_here/folder_to_change_ownership_recursivley', shell=True)

Hope it helps.

How to correctly get image from 'Resources' folder in NetBeans

This was a pain, using netBeans IDE 7.2.

  1. You need to remember that Netbeans cleans up the Build folder whenever you rebuild, so
  2. Add a resource folder to the src folder:

    • (project)
      • src
        • project package folder (contains .java files)
        • resources (whatever name you want)
        • images (optional subfolders)
  3. After the clean/build this structure is propogated into the Build folder:

    • (project)
      • build
        • classes
          • project package folder (contains generated .class files)
          • resources (your resources)
          • images (your optional subfolders)

To access the resources:

dlabel = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("resources/images/logo.png")));

and:

if (common.readFile(getClass().getResourceAsStream("/resources/allwise.ini"), buf).equals("OK")) {

worked for me. Note that in one case there is a leading "/" and in the other there isn't. So the root of the path to the resources is the "classes" folder within the build folder.

Double click on the executable jar file in the dist folder. The path to the resources still works.

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

Undo working copy modifications of one file in Git?

You can use

git checkout -- file

You can do it without the -- (as suggested by nimrodm), but if the filename looks like a branch or tag (or other revision identifier), it may get confused, so using -- is best.

You can also check out a particular version of a file:

git checkout v1.2.3 -- file         # tag v1.2.3
git checkout stable -- file         # stable branch
git checkout origin/master -- file  # upstream master
git checkout HEAD -- file           # the version from the most recent commit
git checkout HEAD^ -- file          # the version before the most recent commit

SQL LIKE condition to check for integer?

Tested on PostgreSQL 9.5 :

-- only digits

select * from books where title ~ '^[0-9]*$';

or,

select * from books where title SIMILAR TO '[0-9]*';

-- start with digit

select * from books where title ~ '^[0-9]+';

How to empty the content of a div

If your div looks like this:

<div id="MyDiv">content in here</div>

Then this Javascript:

document.getElementById("MyDiv").innerHTML = "";

will make it look like this:

<div id="MyDiv"></div>

What is the difference between atan and atan2 in C++?

std::atan2 allows calculating the arctangent of all four quadrants. std::atan only allows calculating from quadrants 1 and 4.

ssh: The authenticity of host 'hostname' can't be established

The best way to go about this is to use 'BatchMode' in addition to 'StrictHostKeyChecking'. This way, your script will accept a new hostname and write it to the known_hosts file, but won't require yes/no intervention.

ssh -o BatchMode=yes -o StrictHostKeyChecking=no [email protected] "uptime"

CMake unable to determine linker language with C++

By default the JNI Native folder is named as jni . Renaming it to cpp fixed the issue

ConfigurationManager.AppSettings - How to modify and save?

Remember that ConfigurationManager uses only one app.config - one that is in startup project.

If you put some app.config to a solution A and make a reference to it from another solution B then if you run B, app.config from A will be ignored.

So for example unit test project should have their own app.config.

What's the difference between & and && in MATLAB?

The single ampersand & is the logical AND operator. The double ampersand && is again a logical AND operator that employs short-circuiting behaviour. Short-circuiting just means the second operand (right hand side) is evaluated only when the result is not fully determined by the first operand (left hand side)

A & B (A and B are evaluated)

A && B (B is only evaluated if A is true)

How can I check if the array of objects have duplicate property values?

//checking duplicate elements in an array
var arr=[1,3,4,6,8,9,1,3,4,7];
var hp=new Map();
console.log(arr.sort());
var freq=0;
for(var i=1;i<arr.length;i++){
// console.log(arr[i-1]+" "+arr[i]);
if(arr[i]==arr[i-1]){
freq++;

}
else{
hp.set(arr[i-1],freq+1);
freq=0;
}
}
console.log(hp);

Undefined reference to 'vtable for xxx'

One or more of your .cpp files is not being linked in, or some non-inline functions in some class are not defined. In particular, takeaway::textualGame()'s implementation can't be found. Note that you've defined a textualGame() at toplevel, but this is distinct from a takeaway::textualGame() implementation - probably you just forgot the takeaway:: there.

What the error means is that the linker can't find the "vtable" for a class - every class with virtual functions has a "vtable" data structure associated with it. In GCC, this vtable is generated in the same .cpp file as the first listed non-inline member of the class; if there's no non-inline members, it will be generated wherever you instantiate the class, I believe. So you're probably failing to link the .cpp file with that first-listed non-inline member, or never defining that member in the first place.

ImportError: No module named PytQt5

This probably means that python doesn't know where PyQt5 is located. To check, go into the interactive terminal and type:

import sys
print sys.path

What you probably need to do is add the directory that contains the PyQt5 module to your PYTHONPATH environment variable. If you use bash, here's how:

Type the following into your shell, and add it to the end of the file ~/.bashrc

export PYTHONPATH=/path/to/PyQt5/directory:$PYTHONPATH

where /path/to/PyQt5/directory is the path to the folder where the PyQt5 library is located.

best way to get the key of a key/value javascript object

The easiest way is to just use Underscore.js:

keys

_.keys(object) Retrieve all the names of the object's properties.

_.keys({one : 1, two : 2, three : 3}); => ["one", "two", "three"]

Yes, you need an extra library, but it's so easy!

How to edit incorrect commit message in Mercurial?

Rollback-and-reapply is realy simple solution, but it can help only with the last commit. Mercurial Queues is much more powerful thing (note that you need to enable Mercurial Queues Extension in order to use "hg q*" commands).

What are some resources for getting started in operating system development?

Already answer, but when I took Operating Systems in college we started with an early linux kernel and added simplistic modern features (basic file systems, virtual memory, multitasking, mutexes). Good fun. You get to skip some of the REALLY crazy low level assembly only stuff for mucking w/ protected mode and page tables while still learned some of the guts.

http://kerneltrap.org/node/14002 http://kerneltrap.org/files/linux-0.01.tar.bz2

jquery ui Dialog: cannot call methods on dialog prior to initialization

So you use this:

var theDialog = $("#divDialog").dialog(opt);
theDialog.dialog("open");

and if you open a MVC Partial View in Dialog, you can create in index a hidden button and JQUERY click event:

$("#YourButton").click(function()
{
   theDialog.dialog("open");
   OR
   theDialog.dialog("close");
});

then inside partial view html you call button trigger click like:

$("#YouButton").trigger("click")

see ya.

How to Detect Browser Window /Tab Close Event?

my solution is similar to the solution given by Server Themes. Do check it once:

localStorage.setItem("validNavigation", false);
$(document).on('keypress', function (e) {
    if (e.keyCode == 116) {
        localStorage.setItem("validNavigation", true);
    }
});

// Attach the event click for all links in the page
$(document).on("click", "a", function () {
    localStorage.setItem("validNavigation", true);
});

// Attach the event submit for all forms in the page
$(document).on("submit", "form", function () {
    localStorage.setItem("validNavigation", true);
});

// Attach the event click for all inputs in the page
$(document).bind("click", "input[type=submit]", function () {
    localStorage.setItem("validNavigation", true);
});

$(document).bind("click", "button[type=submit]", function () {
    localStorage.setItem("validNavigation", true);
});
window.onbeforeunload = function (event) {

    if (localStorage.getItem("validNavigation") === "false") {
        event.returnValue = "Write something clever here..";
        console.log("Test success!");
        localStorage.setItem("validNavigation", false);
    }
};

If you put the breakpoints correctly on the browser page, the if condition will be true only when the browser is about to be closed or the tab is about to be closed.

Check this link for reference: https://www.oodlestechnologies.com/blogs/Capture-Browser-Or-Tab-Close-Event-Jquery-Javascript/

Programmatically Check an Item in Checkboxlist where text is equal to what I want

//Multiple selection:

          private void clbsec(CheckedListBox clb, string text)
          {
              for (int i = 0; i < clb.Items.Count; i++)
              {
                  if(text == clb.Items[i].ToString())
                  {
                      clb.SetItemChecked(i, true);
                  }
              }
          }

using ==>

clbsec(checkedListBox1,"michael");

or 

clbsec(checkedListBox1,textBox1.Text);

or

clbsec(checkedListBox1,dataGridView1.CurrentCell.Value.toString());

What is android:weightSum in android, and how does it work?

One thing which seems like no one else mentioned: let's say you have a vertical LinearLayout, so in order for the weights in layout/element/view inside it to work 100% properly - all of them must have layout_height property (which must exist in your xml file) set to 0dp. Seems like any other value would mess things up in some cases.

Uninstall all installed gems, in OSX?

I did that not too long ago (same poster-child RVM switcher situation):

gem list | cut -d" " -f1 | sudo xargs gem uninstall -Iax

Takes the list of all gems (incl. version stuff), cuts it to keep only the gem name, then uninstalls all versions of such gems.

The sudo is only useful if you had gems installed system-wide, and should not be included unless necessary.

Prevent BODY from scrolling when a modal is opened

For those wondering how to get the scroll event for the bootstrap 3 modal:

$(".modal").scroll(function() {
    console.log("scrolling!);
});

How to send a message to a particular client with socket.io

You can refer to socket.io rooms. When you handshaked socket - you can join him to named room, for instance "user.#{userid}".

After that, you can send private message to any client by convenient name, for instance:

io.sockets.in('user.125').emit('new_message', {text: "Hello world"})

In operation above we send "new_message" to user "125".

thanks.

What's the right way to create a date in Java?

The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:

DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);

Vbscript list all PDF files in folder and subfolders

You'll want to use the GetExtensionName method on the FileSystemObject object.

Set x = CreateObject("scripting.filesystemobject")
WScript.Echo x.GetExtensionName("foo.pdf")

In your example, try using this

For Each objFile in colFiles
    If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
        Wscript.Echo objFile.Name
    End If
Next

The transaction manager has disabled its support for remote/network transactions

In my scenario, the exception was being thrown because I was trying to create a new connection instance within a TransactionScope on an already existing connection:

Example:

void someFunction()
{
    using (var db = new DBContext(GetConnectionString()))
    {
        using (var transaction = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
        {
            someOtherFunction(); // This function opens a new connection within this transaction, causing the exception.
        }
    }
}

void someOtherFunction()
{
    using (var db = new DBContext(GetConnectionString()))
    {
        db.Whatever // <- Exception.
    }
}

How can I write a regex which matches non greedy?

The ? operand makes match non-greedy. E.g. .* is greedy while .*? isn't. So you can use something like <img.*?> to match the whole tag. Or <img[^>]*>.

But remember that the whole set of HTML can't be actually parsed with regular expressions.

List of IP addresses/hostnames from local network in Python

For OSX (and Linux), a simple solution is to use either os.popen or os.system and run the arp -a command.

For example:

devices = []
for device in os.popen('arp -a'): devices.append(device)

This will give you a list of the devices on your local network.

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

In my case, I got this while overloading

ostream & operator << (ostream &out, const MyClass &obj)

and forgot to return out. In other systems this just generates a warning, but on macos it also generated an error (although it seems to print correctly).

The error was resolved by adding the correct return value. In my case, adding the -mmacosx-version-min flag had no effect.

Why can't I see the "Report Data" window when creating reports?

Open report in Report designer

Go to View menu -> Report data

Generate a dummy-variable

If you want to get K dummy variables, instead of K-1, try:

dummies = table(1:length(year),as.factor(year))  

Best,

How to get number of entries in a Lua table?

There's one way, but it might be disappointing: use an additional variable (or one of the table's field) for storing the count, and increase it every time you make an insertion.

count = 0
tbl = {}

tbl["test"] = 47
count = count + 1

tbl[1] = 48
count = count + 1

print(count)   -- prints "2"

There's no other way, the # operator will only work on array-like tables with consecutive keys.

Notepad++: Multiple words search in a file (may be in different lines)?

If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.

Go to SearchFind in Files (Ctrl+Shift+F for the keyboard addicted) and enter:

  • Find What = (cat|town)

  • Filters = *.txt

  • Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

  • Search mode = Regular Expression

Best way to convert strings to symbols in hash

ruby-1.9.2-p180 :001 > h = {'aaa' => 1, 'bbb' => 2}
 => {"aaa"=>1, "bbb"=>2} 
ruby-1.9.2-p180 :002 > Hash[h.map{|a| [a.first.to_sym, a.last]}]
 => {:aaa=>1, :bbb=>2}

SOAP request to WebService with java

When the WSDL is available, it is just two steps you need to follow to invoke that web service.

Step 1: Generate the client side source from a WSDL2Java tool

Step 2: Invoke the operation using:

YourService service = new YourServiceLocator();
Stub stub = service.getYourStub();
stub.operation();

If you look further, you will notice that the Stub class is used to invoke the service deployed at the remote location as a web service. When invoking that, your client actually generates the SOAP request and communicates. Similarly the web service sends the response as a SOAP. With the help of a tool like Wireshark, you can view the SOAP messages exchanged.

However since you have requested more explanation on the basics, I recommend you to refer here and write a web service with it's client to learn it further.

How to lookup JNDI resources on WebLogic?

java is the root JNDI namespace for resources. What the original snippet of code means is that the container the application was initially deployed in did not apply any additional namespaces to the JNDI context you retrieved (as an example, Tomcat automatically adds all resources to the namespace comp/env, so you would have to do dataSource = (javax.sql.DataSource) context.lookup("java:comp/env/jdbc/myDataSource"); if the resource reference name is jdbc/myDataSource).

To avoid having to change your legacy code I think if you register the datasource with the name myDataSource (remove the jdbc/) you should be fine. Let me know if that works.

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

Html code as IFRAME source rather than a URL

I have a page it loads an HTML body from MYSQL I want to present that code in a frame so it renders it self independent of the rest of the page and in the confines of that specific bordering.

An object with a unencoded dataUri might have also fit your need if it was only to load a portion of data text:

The HTML <object> element represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin.

_x000D_
_x000D_
body {display:flex;min-height:25em;}
p {margin:auto;}
object {margin:0 auto;background:lightgray;}
_x000D_
<p>here My uploaded content: </p>
<object data='data:text/html,
  <style>

.table {
  display: table;
  text-align:center;
  width:100%;
  height:100%;
}

.table > * {
  display: table-row;
}

.table > main {
  display: table-cell;
  height: 100%;
  vertical-align: middle;
}
</style>


<div class="table">
  <header>
    <h1>Title</h1>
    <p>subTitle</p>
  </header>

  <main>
    <p>Collection</p>
    <p>Version</p>
    <p>Id</p>
  </main>

  <footer>
    <p>Edition</p>
  </footer>'>

</object>
_x000D_
_x000D_
_x000D_

But keeping your Iframe idea, You could also load your HTML inside your iframe tag and set it as the srcdoc value.You should not have to mind about quotes nor turning it into a dataUri but only mind to fire onload once.

The HTML Inline Frame element (<iframe>) represents a nested browsing context, embedding another HTML page into the current one.

Both iframe below will render the same, one require extra javascript.

example loading a full document :

_x000D_
_x000D_
body {
  display: flex;
  min-height: 25em;
}

p {
  margin: auto;
}

iframe {
  margin: 0 auto;
  min-height: 100%;
  background:lightgray;
}
_x000D_
<p>here my uploaded contents =>:</p>
  <iframe srcdoc='<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <style>
html, body {
  height: 100%;
  margin:0;
}

body.table {
  display: table;
  text-align:center;
  width:100%;
}

.table > * {
  display: table-row;
}

.table > main {
  display: table-cell;
  height: 100%;
  vertical-align: middle;
}
</style>
</head>

<body class="table">
  <header>
    <h1>title</h1>
    <p>injected via <code>srcdoc</code></p>
  </header>

  <main>
    <p>Collection</p>
    <p>Version</p>
    <p>Id</p>
  </main>

  <footer>
    <p>Edition</p>
  </footer>
</body>
</html>'>

</iframe>

  <iframe onload="this.setAttribute('srcdoc', this.innerHTML);this.setAttribute('onload','')">
    <!-- below html loaded -->
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>
      <title>Test</title>
      <style>
        html,
        body {
          height: 100%;
          margin: 0;
          overflow:auto;
        }
        
        body.table {
          display: table;
          text-align: center;
          width: 100%;
        }
        
        .table>* {
          display: table-row;
        }
        
        .table>main {
          display: table-cell;
          height: 100%;
          vertical-align: middle;
        }
      </style>
    </head>

    <body class="table">
      <header>
        <h1>Title</h1>
        <p>Injected from <code>innerHTML</code></p>
      </header>

      <main>
        <p>Collection</p>
        <p>Version</p>
        <p>Id</p>
      </main>

      <footer>
        <p>Edition</p>
      </footer>
    </body>

    </html>
    </iframe>
_x000D_
_x000D_
_x000D_

ExecutorService that interrupts tasks after a timeout

Using John W answer I created an implementation that correctly begin the timeout when the task starts its execution. I even write a unit test for it :)

However, it does not suit my needs since some IO operations do not interrupt when Future.cancel() is called (ie when Thread.interrupt() is called). Some examples of IO operation that may not be interrupted when Thread.interrupt() is called are Socket.connect and Socket.read (and I suspect most of IO operation implemented in java.io). All IO operations in java.nio should be interruptible when Thread.interrupt() is called. For example, that is the case for SocketChannel.open and SocketChannel.read.

Anyway if anyone is interested, I created a gist for a thread pool executor that allows tasks to timeout (if they are using interruptible operations...): https://gist.github.com/amanteaux/64c54a913c1ae34ad7b86db109cbc0bf

Fastest way to tell if two files have the same contents in Unix/Linux?

Because I suck and don't have enough reputation points I can't add this tidbit in as a comment.

But, if you are going to use the cmp command (and don't need/want to be verbose) you can just grab the exit status. Per the cmp man page:

If a FILE is '-' or missing, read standard input. Exit status is 0 if inputs are the same, 1 if different, 2 if trouble.

So, you could do something like:

STATUS="$(cmp --silent $FILE1 $FILE2; echo $?)"  # "$?" gives exit status for each comparison

if [[ $STATUS -ne 0 ]]; then  # if status isn't equal to 0, then execute code
    DO A COMMAND ON $FILE1
else
    DO SOMETHING ELSE
fi

EDIT: Thanks for the comments everyone! I updated the test syntax here. However, I would suggest you use Vasili's answer if you are looking for something similar to this answer in readability, style, and syntax.

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use a ComboBox with its ComboBoxStyle (appears as DropDownStyle in later versions) set to DropDownList. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx

Is <img> element block level or inline level?

For almost all purposes think of them as an inline element with a width set. Basically you are free to dictate how you would like images to display using CSS. I generally set a few image classes like so:

img.center {display:block;margin:0 auto;}

img.left {float:left;margin-right:10px;}

img.right  {float:right;margin-left:10px;}

img.border  {border:1px solid #333;}

How do I fix a Git detached head?

This works for me, It will assign a new branch for detached head :

git checkout new_branch_name detached_head_garbage_name

Parse large JSON file in Nodejs

I solved this problem using the split npm module. Pipe your stream into split, and it will "Break up a stream and reassemble it so that each line is a chunk".

Sample code:

var fs = require('fs')
  , split = require('split')
  ;

var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});
var lineStream = stream.pipe(split());
linestream.on('data', function(chunk) {
    var json = JSON.parse(chunk);           
    // ...
});

How to add and get Header values in WebApi

For .NET Core:

string Token = Request.Headers["Custom"];

Or

var re = Request;
var headers = re.Headers;
string token = string.Empty;
StringValues x = default(StringValues);
if (headers.ContainsKey("Custom"))
{
   var m = headers.TryGetValue("Custom", out x);
}

Increase bootstrap dropdown menu width

Usually we have the need to control the width of the dropdown menu; specially that's essential when the dropdown menu holds a form, e.g. login form --- then the dropdown menu and its items should be wide enough for ease of inputing username/email and password.

Besides, when the screen is smaller than 768px or when the window (containing the dropdown menu) is zoomed down to smaller than 768px, Bootstrap 3 responsively scales the dropdown menu to the whole width of the screen/window. We need to keep this reponsive action.

Hence, the following css class could do that:

@media (min-width: 768px) {
    .dropdown-menu {
        width: 300px !important;  /* change the number to whatever that you need */
    }
}

(I had used it in my web app.)

Is there a Google Sheets formula to put the name of the sheet into a cell?

An old thread, but a useful one... so here's some additional code.

First, in response to Craig's point about the regex being overly greedy and failing for sheet names containing a single quote, this should do the trick (replace 'SHEETNAME'!A1 with your own sheet & cell reference):

=IF(TODAY()=TODAY(), SUBSTITUTE(REGEXREPLACE(CELL("address",'SHEETNAME'!A1),"'?(.+?)'?!\$.*","$1"),"''","'", ""), "")

It uses a lazy match (the ".+?") to find a character string (squotes included) that may or may not be enclosed by squotes but is definitely terminated by bang dollar ("!$") followed by any number of characters. Google Sheets actually protects squotes within a sheet name by appending another squote (as in ''), so the SUBSTITUTE is needed to reduce these back to single squotes.

The formula also allows for sheet names that contain bangs ("!"), but will fail for names using bang dollars ("!$") - if you really need to make your sheet names to look like full absolute cell references then put a separating character between the bang and the dollar (such as a space).

Note that it will only work correctly when pointed at a different sheet from the one that the formula resides! This is because CELL("address" returns just the cell reference (not the sheet name) when used on the same sheet. If you need a sheet to show its own name then put the formula in a cell on another sheet, point it at your target sheet, and then reference the formula cell from the target sheet. I often have a "Meta" sheet in my workbooks to hold settings, common values, database matching criteria, etc so that's also where I put this formula.

As others have said many times above, Google Sheets will only notice changes to the sheet name if you set the workbook's recalculation to "On change and every minute" which you can find on the File|Settings|Calculation menu. It can take up to a whole minute for the change to be picked up.


Secondly, if like me you happen to need an inter-operable formula that works on both Google Sheets and Excel (which for older versions at least doesn't have the REGEXREPLACE function), try:

=IF(IFERROR(INFO("release"), 0)=0, IF(TODAY()=TODAY(), SUBSTITUTE(REGEXREPLACE(CELL("address",'SHEETNAME'!A1),"'?(.+?)'?!\$.*","$1"),"''","'", ""), ""), MID(CELL("filename",'SHEETNAME'!A1),FIND("]",CELL("filename",'SHEETNAME'!A1))+1,255))

This uses INFO("release") to determine which platform we are on... Excel returns a number >0 whereas Google Sheets does not implement the INFO function and generates an error which the formula traps into a 0 and uses for numerical comparison. The Google code branch is as above.

For clarity and completeness, this is the Excel-only version (which does correctly return the name of the sheet it resides on):

=MID(CELL("filename",'SHEETNAME'!A1),FIND("]",CELL("filename",'SHEETNAME'!A1))+1,255)

It looks for the "]" filename terminator in the output of CELL("filename" and extracts the sheet name from the remaining part of the string using the MID function. Excel doesn't allow sheet names to contain "]" so this works for all possible sheet names. In the inter-operable version, Excel is happy to be fed a call to the non-existent REGEXREPLACE function because it never gets to execute the Google code branch.

Get UserDetails object from Security Context in Spring MVC controller

If you already know for sure that the user is logged in (in your example if /index.html is protected):

UserDetails userDetails =
 (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

To first check if the user is logged in, check that the current Authentication is not a AnonymousAuthenticationToken.

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
        // userDetails = auth.getPrincipal()
}

How to set background color of a button in Java GUI?

You may or may not have to use setOpaque method to ensure that the colors show up by passing true to the method.

How to change text and background color?

You can use the function system.

system("color *background**foreground*");

For background and foreground, type in a number from 0 - 9 or a letter from A - F.

For example:

system("color A1");
std::cout<<"hi"<<std::endl;

That would display the letters "hi" with a green background and blue text.

To see all the color choices, just type in:

system("color %");

to see what number or letter represents what color.

How can I extract the folder path from file path in Python?

Here is the code:

import os
existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
wkspFldr = os.path.dirname(existGDBPath)
print wkspFldr # T:\Data\DBDesign

Why do we need middleware for async flow in Redux?

To Answer the question:

Why can't the container component call the async API, and then dispatch the actions?

I would say for at least two reasons:

The first reason is the separation of concerns, it's not the job of the action creator to call the api and get data back, you have to have to pass two argument to your action creator function, the action type and a payload.

The second reason is because the redux store is waiting for a plain object with mandatory action type and optionally a payload (but here you have to pass the payload too).

The action creator should be a plain object like below:

function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
}

And the job of Redux-Thunk midleware to dispache the result of your api call to the appropriate action.

.htaccess - how to force "www." in a generic way?

this worked like magic for me

RewriteCond %{HTTP_HOST} ^sitename.com [NC] RewriteRule ^(.*)$ https://www.sitename.com/$1 [L,R=301,NC]

How to create unit tests easily in eclipse

Any unit test you could create by just pressing a button would not be worth anything. How is the tool to know what parameters to pass your method and what to expect back? Unless I'm misunderstanding your expectations.

Close to that is something like FitNesse, where you can set up tests, then separately you set up a wiki page with your test data, and it runs the tests with that data, publishing the results as red/greens.

If you would be happy to make test writing much faster, I would suggest Mockito, a mocking framework that lets you very easily mock the classes around the one you're testing, so there's less setup/teardown, and you know you're really testing that one class instead of a dependent of it.

Web API Put Request generates an Http 405 Method Not Allowed error

You can remove webdav module manually from GUI for the particular in IIS.
1) Goto the IIs.
2) Goto the respective site.
3) Open "Handler Mappings"
4) Scroll downn and select WebDav module. Right click on it and delete it.

Note: this will also update your web.config of the web app.

Filtering JSON array using jQuery grep()

_x000D_
_x000D_
var data = {_x000D_
  "items": [{_x000D_
    "id": 1,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 2,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 3,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 4,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 5,_x000D_
    "category": "cat1"_x000D_
  }]_x000D_
};_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1" && element.id === 3;_x000D_
}, false);_x000D_
console.log(returnedData);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1";_x000D_
}, true);_x000D_
console.log(returnedOppositeData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>
_x000D_
_x000D_
_x000D_

The $.grep() method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.

npm command to uninstall or prune unused packages in Node.js

Note: Recent npm versions do this automatically when package-locks are enabled, so this is not necessary except for removing development packages with the --production flag.


Run npm prune to remove modules not listed in package.json.

From npm help prune:

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified, this command will remove the packages specified in your devDependencies.

Using If/Else on a data frame

Try this

frame$twohouses <- ifelse(frame$data>1, 2, 1)
 frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
6     2         2
7     3         2
8     1         1
9     4         2
10    3         2
11    2         2
12    4         2
13    0         1
14    1         1
15    2         2
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

How do I get a list of locked users in an Oracle database?

select username,
       account_status 
  from dba_users 
 where lock_date is not null;

This will actually give you the list of locked users.

How can I get phone serial number (IMEI)

Use below code for IMEI:

TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String imei= tm.getDeviceId();

jquery change class name

In the event that you already have a class and need to alternate between classes as oppose to add a class, you can chain toggle events:

$('li.multi').click(function(e) {
    $(this).toggleClass('opened').toggleClass('multi-opened');
});

How to find Google's IP address?

On Windows, open command prompt and type tracert google.com and press enter, or on Linux, open terminal and type nslookup google.com and press enter:

Server:     127.0.1.1
Address:    127.0.1.1#53

Non-authoritative answer:

Name:   google.com
Address: 74.125.236.199
Name:   google.com
Address: 74.125.236.201
Name:   google.com
Address: 74.125.236.194
Name:   google.com
Address: 74.125.236.198
Name:   google.com
Address: 74.125.236.206
Name:   google.com
Address: 74.125.236.193
Name:   google.com
Address: 74.125.236.196
Name:   google.com
Address: 74.125.236.192
Name:   google.com
Address: 74.125.236.197
Name:   google.com
Address: 74.125.236.195
Name:   google.com
Address: 74.125.236.200

Comparing floating point number to zero

You are correct with your observation.

If x == 0.0, then abs(x) * epsilon is zero and you're testing whether abs(y) <= 0.0.

If y == 0.0 then you're testing abs(x) <= abs(x) * epsilon which means either epsilon >= 1 (it isn't) or x == 0.0.

So either is_equal(val, 0.0) or is_equal(0.0, val) would be pointless, and you could just say val == 0.0. If you want to only accept exactly +0.0 and -0.0.

The FAQ's recommendation in this case is of limited utility. There is no "one size fits all" floating-point comparison. You have to think about the semantics of your variables, the acceptable range of values, and the magnitude of error introduced by your computations. Even the FAQ mentions a caveat, saying this function is not usually a problem "when the magnitudes of x and y are significantly larger than epsilon, but your mileage may vary".

How do I get the path to the current script with Node.js?

If you are using pkg to package your app, you'll find useful this expression:

appDirectory = require('path').dirname(process.pkg ? process.execPath : (require.main ? require.main.filename : process.argv[0]));
  • process.pkg tells if the app has been packaged by pkg.

  • process.execPath holds the full path of the executable, which is /usr/bin/node or similar for direct invocations of scripts (node test.js), or the packaged app.

  • require.main.filename holds the full path of the main script, but it's empty when Node runs in interactive mode.

  • __dirname holds the full path of the current script, so I'm not using it (although it may be what OP asks; then better use appDirectory = process.pkg ? require('path').dirname(process.execPath) : (__dirname || require('path').dirname(process.argv[0])); noting that in interactive mode __dirname is empty.

  • For interactive mode, use either process.argv[0] to get the path to the Node executable or process.cwd() to get the current directory.

How can I make a DateTimePicker display an empty string?

Listen , Make Following changes in your code if you want to show empty datetimepicker and get null when no date is selected by user, else save date.

  1. Set datetimepicker FORMAT property to custom.
  2. set CUSTOM FORMAT property to empty string " ".
  3. set its TAG to 0 by default.
  4. Register Event for datetimepicker VALUECHANGED.

Now real work starts

if user will interact with datetimepicker its VALUECHANGED event will be called and there set its TAG property to 1.

Final Step

Now when saving, check if its TAG is zero, then save NULL date else if TAG is 1 then pick and save Datetime picker value.

It Works like a charm.

Now if you want its value be changed back to empty by user interaction, then add checkbox and show text "Clear" with this checkbox. if user wants to clear date, simply again set its CUSTOM FORMAT property to empty string " ", and set its TAG back to 0. Thats it..

What is the use of adding a null key or value to a HashMap in Java?

Here's my only-somewhat-contrived example of a case where the null key can be useful:

public class Timer {
    private static final Logger LOG = Logger.getLogger(Timer.class);
    private static final Map<String, Long> START_TIMES = new HashMap<String, Long>();

    public static synchronized void start() {
        long now = System.currentTimeMillis();
        if (START_TIMES.containsKey(null)) {
            LOG.warn("Anonymous timer was started twice without being stopped; previous timer has run for " + (now - START_TIMES.get(null).longValue()) +"ms"); 
        }
        START_TIMES.put(null, now);
    }

    public static synchronized long stop() {
        if (! START_TIMES.containsKey(null)) {
            return 0;
        }

        return printTimer("Anonymous", START_TIMES.remove(null), System.currentTimeMillis());
    }

    public static synchronized void start(String name) {
        long now = System.currentTimeMillis();
        if (START_TIMES.containsKey(name)) {
            LOG.warn(name + " timer was started twice without being stopped; previous timer has run for " + (now - START_TIMES.get(name).longValue()) +"ms"); 
        }
        START_TIMES.put(name, now);
    }

    public static synchronized long stop(String name) {
        if (! START_TIMES.containsKey(name)) {
            return 0;
        }

        return printTimer(name, START_TIMES.remove(name), System.currentTimeMillis());
    }

    private static long printTimer(String name, long start, long end) {
        LOG.info(name + " timer ran for " + (end - start) + "ms");
        return end - start;
    }
}

How to prevent scrollbar from repositioning web page?

Simply setting the width of your container element like this will do the trick

width: 100vw;

This will make that element ignore the scrollbar and it works with background color or images.

How to get the total number of rows of a GROUP BY query?

Here is the solution for you

$sql="SELECT count(*) FROM [tablename] WHERE key == ? ";
$sth = $this->db->prepare($sql);
$sth->execute(array($key));
$rows = $sth->fetch(PDO::FETCH_NUM);
echo $rows[0];

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

Instead of casting the model in the RenderPartial call, and since you're using razor, you can modify the first line in your view from

@model dynamic

to

@model YourNamespace.YourModelType

This has the advantage of working on every @Html.Partial call you have in the view, and also gives you intellisense for the properties.

JavaScript require() on client side

I've been using browserify for that. It also lets me integrate Node.js modules into my client-side code.

I blogged about it here: Add node.js/CommonJS style require() to client-side JavaScript with browserify

Converting string to numeric

As csgillespie said. stringsAsFactors is default on TRUE, which converts any text to a factor. So even after deleting the text, you still have a factor in your dataframe.

Now regarding the conversion, there's a more optimal way to do so. So I put it here as a reference :

> x <- factor(sample(4:8,10,replace=T))
> x
 [1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
 [1] 6 4 8 6 7 6 8 5 8 4

To show it works.

The timings :

> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
   user  system elapsed 
   0.11    0.00    0.11 
> system.time(as.numeric(levels(x))[x])
   user  system elapsed 
      0       0       0 

It's a big improvement, but not always a bottleneck. It gets important however if you have a big dataframe and a lot of columns to convert.

How to program a fractal?

Another excellent fractal to learn is the Sierpinski Triangle Fractal.

Basically, draw three corners of a triangle (an equilateral is preferred, but any triangle will work), then start a point P at one of those corners. Move P halfway to any of the 3 corners at random, and draw a point there. Again move P halfway towards any random corner, draw, and repeat.

You'd think the random motion would create a random result, but it really doesn't.

Reference: http://en.wikipedia.org/wiki/Sierpinski_triangle

How to change target build on Android project?

Well I agree with Ryan Conrad on how to do it in eclipse, have you ensured you have changed your manifest.xml?

 <uses-sdk android:minSdkVersion="3" />
 <uses-sdk android:targetSdkVersion="8" />

Difference between datetime and timestamp in sqlserver?

According to the documentation, timestamp is a synonym for rowversion - it's automatically generated and guaranteed1 to be unique. datetime isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.


1 Assuming you use it properly, of course. See comments.

Array of PHP Objects

Another intuitive solution could be:

class Post
{
    public $title;
    public $date;
}

$posts = array();

$posts[0] = new Post();
$posts[0]->title = 'post sample 1';
$posts[0]->date = '1/1/2021';

$posts[1] = new Post();
$posts[1]->title = 'post sample 2';
$posts[1]->date = '2/2/2021';

foreach ($posts as $post) {
  echo 'Post Title:' . $post->title . ' Post Date:' . $post->date . "\n";
}

Understanding Fragment's setRetainInstance(boolean)

setRetainInstance(boolean) is useful when you want to have some component which is not tied to Activity lifecycle. This technique is used for example by rxloader to "handle Android's activity lifecyle for rxjava's Observable" (which I've found here).

When to use MongoDB or other document oriented database systems?

Note that Mongo essentially stores JSON. If your app is dealing with a lot of JS Objects (with nesting) and you want to persist these objects then there is a very strong argument for using Mongo. It makes your DAL and MVC layers ultra thin, because they are not un-packaging all the JS object properties and trying to force-fit them into a structure (schema) that they don't naturally fit into.

We have a system that has several complex JS Objects at its heart, and we love Mongo because we can persist everything really, really easily. Our objects are also rather amorphous and unstructured, and Mongo soaks up that complication without blinking. We have a custom reporting layer that deciphers the amorphous data for human consumption, and that wasn't that difficult to develop.

How to import Angular Material in project?

The MaterialModule was deprecated in the beta3 version with the goal that developers should only import into their applications what they are going to use and thus improve the bundle size.

The developers have now 2 options:

  • Create a custom MyMaterialModule which imports/exports the components that your application requires and can be imported by other (feature) modules in your application.
  • Import directly the individual material modules that a module requires into it.

Take the following as example (extracted from material page)

First approach:

import {MdButtonModule, MdCheckboxModule} from '@angular/material';

@NgModule({
  imports: [MdButtonModule, MdCheckboxModule],
  exports: [MdButtonModule, MdCheckboxModule],
})
export class MyOwnCustomMaterialModule { }

Then you can import this module into any of yours.

Second approach:

import {MdButtonModule, MdCheckboxModule} from '@angular/material';

@NgModule({
  ...
  imports: [MdButtonModule, MdCheckboxModule],
  ...
})
export class PizzaPartyAppModule { }

Now you can use the respective material components in all the components declared in PizzaPartyAppModule

It is worth mentioning the following:

  • With the latest version of material, you need to import BrowserAnimationsModule into your main module if you want the animations to work
  • With the latest version developers now need to add @angular/cdk to their package.json (material dependency)
  • Import the material modules always after BrowserModule, as stated by the docs:

Whichever approach you use, be sure to import the Angular Material modules after Angular's BrowserModule, as the import order matters for NgModules.

Request format is unrecognized for URL unexpectedly ending in

Make sure you disable custom errors. This can mask the original problem in your code:

change

<customErrors defaultRedirect="~/Error" mode="On">

to

<customErrors defaultRedirect="~/Error" mode="Off">

Tar archiving that takes input from a list of files

Some versions of tar, for example, the default versions on HP-UX (I tested 11.11 and 11.31), do not include a command line option to specify a file list, so a decent work-around is to do this:

tar cvf allfiles.tar $(cat mylist.txt)

What is the difference between a database and a data warehouse?

A Data Warehousing (DW) is process for collecting and managing data from varied sources to provide meaningful business insights. A Data warehouse is typically used to connect and analyze business data from heterogeneous sources. The data warehouse is the core of the BI system which is built for data analysis and reporting.

Is it a good idea to index datetime field in mysql?

Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

In my case checking the check-box

"Copy project into workspace"

did the trick.

jquery: change the URL address without redirecting?

You cannot really change the whole URL in the location bar without redirecting (think of the security issues!).

However you can change the hash part (whats after the #) and read that: location.hash

ps. prevent the default onclick redirect of a link by something like:

$("#link").bind("click",function(e){
  doRedirectFunction();
  e.preventDefault();
})

How to set the environmental variable LD_LIBRARY_PATH in linux

You should add more details about your distribution, for example under Ubuntu the right way to do this is to add a custom .conf file to /etc/ld.so.conf.d, for example

sudo gedit /etc/ld.so.conf.d/randomLibs.conf

inside the file you are supposed to write the complete path to the directory that contains all the libraries that you wish to add to the system, for example

/home/linux/myLocalLibs

remember to add only the path to the dir, not the full path for the file, all the libs inside that path will be automatically indexed.

Save and run sudo ldconfig to update the system with this libs.

UITapGestureRecognizer - single tap and double tap

Some view have there own double tap recognizers built in (MKMapView being an example). To get around this you will need to implement UIGestureRecognizerDelegate method shouldRecognizeSimultaneouslyWithGestureRecognizer and return YES:

First implement your double and single recognizers:

// setup gesture recognizers
UITapGestureRecognizer* singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                action:@selector(mapViewTapped:)];
singleTapRecognizer.delegate = self;
singleTapRecognizer.numberOfTapsRequired = 1;


UITapGestureRecognizer* doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                      action:@selector(mapViewDoubleTapped:)];
doubleTapRecognizer.delegate = self;    // this allows
doubleTapRecognizer.numberOfTapsRequired = 2;
[singleTapRecognizer requireGestureRecognizerToFail:doubleTapRecognizer];

And then implement:

#pragma mark UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer
*)otherGestureRecognizer {  return YES; }

matplotlib does not show my drawings although I call pyplot.show()

If I set my backend to template in ~/.matplotlib/matplotlibrc, then I can reproduce your symptoms:

~/.matplotlib/matplotlibrc:

# backend      : GtkAgg
backend      : template

Note that the file matplotlibrc may not be in directory ~/.matplotlib/. In this case, the following code shows where it is:

>>> import matplotlib
>>> matplotlib.matplotlib_fname()

In [1]: import matplotlib.pyplot as p

In [2]: p.plot(range(20),range(20))
Out[2]: [<matplotlib.lines.Line2D object at 0xa64932c>]

In [3]: p.show()

If you edit ~/.matplotlib/matplotlibrc and change the backend to something like GtkAgg, you should see a plot. You can list all the backends available on your machine with

import matplotlib.rcsetup as rcsetup
print(rcsetup.all_backends)

It should return a list like:

['GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'MacOSX', 'QtAgg', 'Qt4Agg',
'TkAgg', 'WX', 'WXAgg', 'CocoaAgg', 'agg', 'cairo', 'emf', 'gdk', 'pdf',
'ps', 'svg', 'template']

Reference:

Converting a pointer into an integer

I came across this question while studying the source code of SQLite.

In the sqliteInt.h, there is a paragraph of code defined a macro convert between integer and pointer. The author made a very good statement first pointing out it should be a compiler dependent problem and then implemented the solution to account for most of the popular compilers out there.

#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
#else                          /* Generates a warning - but it always works     */
# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
# define SQLITE_PTR_TO_INT(X)  ((int)(X))
#endif

And here is a quote of the comment for more details:

/*
** The following macros are used to cast pointers to integers and
** integers to pointers.  The way you do this varies from one compiler
** to the next, so we have developed the following set of #if statements
** to generate appropriate macros for a wide range of compilers.
**
** The correct "ANSI" way to do this is to use the intptr_t type.
** Unfortunately, that typedef is not available on all compilers, or
** if it is available, it requires an #include of specific headers
** that vary from one machine to the next.
**
** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
** So we have to define the macros in different ways depending on the
** compiler.
*/

Credit goes to the committers.