Programs & Examples On #Infrastructure

Why is it not advisable to have the database and web server on the same machine?

Database licences are not cheep and are often charged per CPU, therefore by separating out your web-servers you can reduce the cost of your database licences.

E.g if you have 1 server doing both web and database that contains 8 CPUs you will have to pay for an 8 cpu licence. However if you have two servers each with 4 CPUs and runs the database on one server you will only have to pay for a 4 cpu licences

ImportError: numpy.core.multiarray failed to import

pip install numpy==1.19.3

this did the job for me.

Best practices for catching and re-throwing .NET exceptions

If you throw a new exception with the initial exception you will preserve the initial stack trace too..

try{
} 
catch(Exception ex){
     throw new MoreDescriptiveException("here is what was happening", ex);
}

How to move the cursor word by word in the OS X Terminal

Here's how you can do it

By default, the Terminal has these shortcuts to move (left and right) word-by-word:

  • esc+B (left)
  • esc+F (right)

You can configure alt+ and to generate those sequences for you:

  • Open Terminal preferences (cmd+,);
  • At Settings tab, select Keyboard and double-click ? ? if it's there, or add it if it's not.
  • Set the modifier as desired, and type the shortcut key in the box: esc+B, generating the text \033b (you can't type this text manually).
  • Repeat for word-right (esc+F becomes \033f)

Alternatively, you can refer to this blog post over at textmate:

http://blog.macromates.com/2006/word-movement-in-terminal/

Add a property to a JavaScript object using a variable as the name?

There are two different notations to access object properties

  • Dot notation: myObj.prop1
  • Bracket notation: myObj["prop1"]

Dot notation is fast and easy but you must use the actual property name explicitly. No substitution, variables, etc.

Bracket notation is open ended. It uses a string but you can produce the string using any legal js code. You may specify the string as literal (though in this case dot notation would read easier) or use a variable or calculate in some way.

So, these all set the myObj property named prop1 to the value Hello:

// quick easy-on-the-eye dot notation
myObj.prop1 = "Hello";

// brackets+literal
myObj["prop1"] = "Hello";

// using a variable
var x = "prop1"; 
myObj[x] = "Hello";                     

// calculate the accessor string in some weird way
var numList = [0,1,2];
myObj[ "prop" + numList[1] ] = "Hello";     

Pitfalls:

myObj.[xxxx] = "Hello";      // wrong: mixed notations, syntax fail
myObj[prop1] = "Hello";      // wrong: this expects a variable called prop1

tl;dnr: If you want to compute or reference the key you must use bracket notation. If you are using the key explicitly, then use dot notation for simple clear code.

Note: there are some other good and correct answers but I personally found them a bit brief coming from a low familiarity with JS on-the-fly quirkiness. This might be useful to some people.

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

If you have a standard code signing certificate, some time will be needed for your application to build trust. Microsoft affirms that an Extended Validation (EV) Code Signing Certificate allows us to skip this period of trust-building. According to Microsoft, extended validation certificates allow the developer to immediately establish a reputation with SmartScreen. Otherwise, the users will see a warning like "Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.", with the two buttons: "Run anyway" and "Don't run".

Another Microsoft resource states the following (quote): "Although not required, programs signed by an EV code signing certificate can immediately establish a reputation with SmartScreen reputation services even if no prior reputation exists for that file or publisher. EV code signing certificates also have a unique identifier which makes it easier to maintain reputation across certificate renewals."

My experience is as follows. Since 2005, we have been using regular (non-EV) code signing certificates to sign .MSI, .EXE and .DLL files with time stamps, and there has never been a problem with SmartScreen until 2018, when there was just one case when it took 3 days for a beta version of our application to build trust since we have released it to beta testers, and it was in the middle of certificate validity period. I don't know what SmartScreen might not like in that specific version of our application, but there have been no SmartScreen complaints since then. Therefore, if your certificate is a non-EV, it is a signed application (such as an .MSI file) that will build trust over time, not a certificate. For example, a certificate can be issued a few months ago and used to sign many files, but for each signed file you publish, it may take a few days for SmartScreen to stop complaining about the file after publishing, as was in our case in 2018.

As a conclusion, to avoid the warning completely, i.e. prevent it from happening even suddenly, you need an Extended Validation (EV) code signing certificate.

Random number c++ in some range

Use the rand function:

http://www.cplusplus.com/reference/clibrary/cstdlib/rand/

Quote:

A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:

( value % 100 ) is in the range 0 to 99
( value % 100 + 1 ) is in the range 1 to 100
( value % 30 + 1985 ) is in the range 1985 to 2014

Completely Remove MySQL Ubuntu 14.04 LTS

I experienced a similar issue on Ubuntu 14.04 LTS after a MySQL update.

I started getting error: "Fatal error: Can't open and lock privilege tables: Incorrect file format 'user'" in /var/log/mysql/error.log

MySQL could not start.

I resolved it by removing the following directory: /var/lib/mysql/mysql

sudo rm -rf /var/lib/mysql/mysql

This leaves your other DB related files in place, only removing the mysql related files.

After running these:

sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean

Then reinstalling mysql:

sudo apt-get install mysql-server

It worked perfectly.

MySQL: how to get the difference between two timestamps in seconds

You could use the TIMEDIFF() and the TIME_TO_SEC() functions as follows:

SELECT TIME_TO_SEC(TIMEDIFF('2010-08-20 12:01:00', '2010-08-20 12:00:00')) diff;
+------+
| diff |
+------+
|   60 |
+------+
1 row in set (0.00 sec)

You could also use the UNIX_TIMESTAMP() function as @Amber suggested in an other answer:

SELECT UNIX_TIMESTAMP('2010-08-20 12:01:00') - 
       UNIX_TIMESTAMP('2010-08-20 12:00:00') diff;
+------+
| diff |
+------+
|   60 |
+------+
1 row in set (0.00 sec)

If you are using the TIMESTAMP data type, I guess that the UNIX_TIMESTAMP() solution would be slightly faster, since TIMESTAMP values are already stored as an integer representing the number of seconds since the epoch (Source). Quoting the docs:

When UNIX_TIMESTAMP() is used on a TIMESTAMP column, the function returns the internal timestamp value directly, with no implicit “string-to-Unix-timestamp” conversion.

Keep in mind that TIMEDIFF() return data type of TIME. TIME values may range from '-838:59:59' to '838:59:59' (roughly 34.96 days)

What is best way to start and stop hadoop ecosystem, with command line?

start-all.sh & stop-all.sh : Used to start and stop hadoop daemons all at once. Issuing it on the master machine will start/stop the daemons on all the nodes of a cluster. Deprecated as you have already noticed.

start-dfs.sh, stop-dfs.sh and start-yarn.sh, stop-yarn.sh : Same as above but start/stop HDFS and YARN daemons separately on all the nodes from the master machine. It is advisable to use these commands now over start-all.sh & stop-all.sh

hadoop-daemon.sh namenode/datanode and yarn-deamon.sh resourcemanager : To start individual daemons on an individual machine manually. You need to go to a particular node and issue these commands.

Use case : Suppose you have added a new DN to your cluster and you need to start the DN daemon only on this machine,

bin/hadoop-daemon.sh start datanode

Note : You should have ssh enabled if you want to start all the daemons on all the nodes from one machine.

Hope this answers your query.

How to alter a column's data type in a PostgreSQL table?

See documentation here: http://www.postgresql.org/docs/current/interactive/sql-altertable.html

ALTER TABLE tbl_name ALTER COLUMN col_name TYPE varchar (11);

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

Combine Regexp?

If a string must not contain @, every character must be another character than @:

/^[^@]*$/

This will match any string of any length that does not contain @.

Another possible solution would be to invert the boolean result of /@/.

Why does the C++ STL not provide any "tree" containers?

"I want to store a hierarchy of objects as a tree"

C++11 has come and gone and they still didn't see a need to provide a std::tree, although the idea did come up (see here). Maybe the reason they haven't added this is that it is trivially easy to build your own on top of the existing containers. For example...

template< typename T >
struct tree_node
   {
   T t;
   std::vector<tree_node> children;
   };

A simple traversal would use recursion...

template< typename T >
void tree_node<T>::walk_depth_first() const
   {
   cout<<t;
   for ( auto & n: children ) n.walk_depth_first();
   }

If you want to maintain a hierarchy and you want it to work with STL algorithms, then things may get complicated. You could build your own iterators and achieve some compatibility, however many of the algorithms simply don't make any sense for a hierarchy (anything that changes the order of a range, for example). Even defining a range within a hierarchy could be a messy business.

How to get first N number of elements from an array

I believe what you're looking for is:

// ...inside the render() function

var size = 3;
var items = list.slice(0, size).map(i => {
    return <myview item={i} key={i.id} />
}

return (
  <div>
    {items}
  </div>   
)

How can I call controller/view helper methods from the console in Ruby on Rails?

If the method is the POST method then:

app.post 'controller/action?parameter1=value1&parameter2=value2'

(Here parameters will be as per your applicability.)

Else if it is the GET method then:

app.get 'controller/action'

Add a string of text into an input field when user clicks a button

this will do it with just javascript - you can also put the function in a .js file and call it with onclick

//button
<div onclick="
   document.forms['name_of_the_form']['name_of_the_input'].value += 'text you want to add to it'"
>button</div>

Eclipse executable launcher error: Unable to locate companion shared library

I meet this issue after copy a eclipse installation to another pc.I find the eclipse installation auto created the .p2 directory on my c:\Users\xx.p2, and --launcher.library refer to here.So it doesn't exist on my another pc.
My resolution is to reinstall eclipse:
a)Double click eclipse-inst-win64.exe
b)Click to change to advanced mode.
c)Uncheck the Bundle Pool
d)Finish your installation and copy again.
Everything will work well.

Apache default VirtualHost

The NameVirtualHost option would be a good option.

Adding backslashes without escaping [Python]

printing a list can also cause this problem (im new in python, so it confused me a bit too):

>>>myList = ['\\']
>>>print myList
['\\']
>>>print ''.join(myList)
\ 

similarly:

>>>myList = ['\&']
>>>print myList
['\\&']
>>>print ''.join(myList)
\&

Can I store images in MySQL

Yes, you can store images in the database, but it's not advisable in my opinion, and it's not general practice.

A general practice is to store images in directories on the file system and store references to the images in the database. e.g. path to the image,the image name, etc.. Or alternatively, you may even store images on a content delivery network (CDN) or numerous hosts across some great expanse of physical territory, and store references to access those resources in the database.

Images can get quite large, greater than 1MB. And so storing images in a database can potentially put unnecessary load on your database and the network between your database and your web server if they're on different hosts.

I've worked at startups, mid-size companies and large technology companies with 400K+ employees. In my 13 years of professional experience, I've never seen anyone store images in a database. I say this to support the statement it is an uncommon practice.

How to append binary data to a buffer in node.js

This is to help anyone who comes here looking for a solution that wants a pure approach. I would recommend understanding this problem because it can happen in lots of different places not just with a JS Buffer object. By understanding why the problem exists and how to solve it you will improve your ability to solve other problems in the future since this one is so fundamental.

For those of us that have to deal with these problems in other languages it is quite natural to devise a solution, but there are people who may not realize how to abstract away the complexities and implement a generally efficient dynamic buffer. The code below may have potential to be optimized further.

I have left the read method unimplemented to keep the example small in size.

The realloc function in C (or any language dealing with intrinsic allocations) does not guarantee that the allocation will be expanded in size with out moving the existing data - although sometimes it is possible. Therefore most applications when needing to store a unknown amount of data will use a method like below and not constantly reallocate, unless the reallocation is very infrequent. This is essentially how most file systems handle writing data to a file. The file system simply allocates another node and keeps all the nodes linked together, and when you read from it the complexity is abstracted away so that the file/buffer appears to be a single contiguous buffer.

For those of you who wish to understand the difficulty in just simply providing a high performance dynamic buffer you only need to view the code below, and also do some research on memory heap algorithms and how the memory heap works for programs.

Most languages will provide a fixed size buffer for performance reasons, and then provide another version that is dynamic in size. Some language systems opt for a third-party system where they keep the core functionality minimal (core distribution) and encourage developers to create libraries to solve additional or higher level problems. This is why you may question why a language does not provide some functionality. This small core functionality allows costs to be reduced in maintaining and enhancing the language, however you end up having to write your own implementations or depending on a third-party.

var Buffer_A1 = function (chunk_size) {
    this.buffer_list = [];
    this.total_size = 0;
    this.cur_size = 0;
    this.cur_buffer = [];
    this.chunk_size = chunk_size || 4096;

    this.buffer_list.push(new Buffer(this.chunk_size));
};

Buffer_A1.prototype.writeByteArrayLimited = function (data, offset, length) {
    var can_write = length > (this.chunk_size - this.cur_size) ? (this.chunk_size - this.cur_size) : length;

    var lastbuf = this.buffer_list.length - 1;

    for (var x = 0; x < can_write; ++x) {
        this.buffer_list[lastbuf][this.cur_size + x] = data[x + offset];
    }

    this.cur_size += can_write;
    this.total_size += can_write;

    if (this.cur_size == this.chunk_size) {
        this.buffer_list.push(new Buffer(this.chunk_size));
        this.cur_size = 0;
    }

    return can_write;
};

/*
    The `data` parameter can be anything that is array like. It just must
    support indexing and a length and produce an acceptable value to be
    used with Buffer.
*/
Buffer_A1.prototype.writeByteArray = function (data, offset, length) {
    offset = offset == undefined ? 0 : offset;
    length = length == undefined ? data.length : length;

    var rem = length;
    while (rem > 0) {
        rem -= this.writeByteArrayLimited(data, length - rem, rem);
    }
};

Buffer_A1.prototype.readByteArray = function (data, offset, length) {
    /*
        If you really wanted to implement some read functionality
        then you would have to deal with unaligned reads which could
        span two buffers.
    */
};

Buffer_A1.prototype.getSingleBuffer = function () {
    var obuf = new Buffer(this.total_size);
    var cur_off = 0;
    var x;

    for (x = 0; x < this.buffer_list.length - 1; ++x) {
        this.buffer_list[x].copy(obuf, cur_off);
        cur_off += this.buffer_list[x].length;
    }

    this.buffer_list[x].copy(obuf, cur_off, 0, this.cur_size);

    return obuf;
};

How to add a list item to an existing unordered list?

$("#content ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');

Here is some feedback regarding Code Readability (shameless plug for a blog). http://coderob.wordpress.com/2012/02/02/code-readability

Consider separating the declaration of your new elements from the action of adding them to your UL.. It would look something like this:

var tabSpan = $('<span/>', {
    html: 'Message Center'
});
var messageCenterAnchor = $('<a/>', {
    href='/user/messages',
    html: tabSpan
});
var newListItem = $('<li/>', {
    html: messageCenterAnchor,
    "id": "myIDGoesHere"
});    // NOTE: you have to put quotes around "id" for IE..

$("content ul").append(newListItem);

Happy coding :)

Produce a random number in a range using C#

You can try

Random r = new Random();
int rInt = r.Next(0, 100); //for ints
int range = 100;
double rDouble = r.NextDouble()* range; //for doubles

Have a look at

Random Class, Random.Next Method (Int32, Int32) and Random.NextDouble Method

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

I ran into this problem myself today, and found a really nifty plugin that will save you the hassle of trying to manually allow cleartext traffic in Android 9+ for your Apache Cordova application. Simply install cordova-plugin-cleartext, and the plugin should take care of all the behind the scenes Android stuff for you.

$ cordova plugin add cordova-plugin-cleartext
$ cordova prepare
$ cordova run android

How to get all selected values of a multiple select box?

You Can try this script

     <!DOCTYPE html>
    <html>
    <script>
    function getMultipleSelectedValue()
    {
      var x=document.getElementById("alpha");
      for (var i = 0; i < x.options.length; i++) {
         if(x.options[i].selected ==true){
              alert(x.options[i].value);
          }
      }
    }
    </script>
    </head>
    <body>
    <select multiple="multiple" id="alpha">
      <option value="a">A</option>
      <option value="b">B</option>
      <option value="c">C</option>
      <option value="d">D</option>
    </select>
    <input type="button" value="Submit" onclick="getMultipleSelectedValue()"/>
    </body>
    </html>

Can you run GUI applications in a Docker container?

OSX (10.13.6, high sierra)

Similar to @Nick's answer, but his solution did not work for me.

First install socat by doing brew install socat, and install XQuartz (https://www.xquartz.org/)

Then followed these steps here (http://fabiorehm.com/blog/2014/09/11/running-gui-apps-with-docker/) in the comments section:

1. in one mac terminal i started:

socat TCP-LISTEN:6000,reuseaddr,fork UNIX-CLIENT:\"$DISPLAY\"

2. and in another mac terminal I ran:

docker run -ti --rm \
-e DISPLAY=$(ipconfig getifaddr en0):0 \
-v /tmp/.X11-unix:/tmp/.X11-unix \
firefox

I was also able to launch CLion from my debian docker container too.

Get environment value in controller

You can not access the environment variable like this.

Inside the .env file you write

IMAP_HOSTNAME_TEST=imap.gmail.com  // I am okay with this

Next, inside the config folder there is a file, mail.php. You may use this file to code. As you are working with mail functionality. You might use another file as well.

return [

//..... other declarations
'imap_hostname_test' => env('IMAP_HOSTNAME_TEST'),
// You are hiding the value inside the configuration as well

];

You can call the variable from a controller using 'config(. Whatever file you are using inside config folder. You need to use that file name (without extension) + '.' + 'variable name' + ')'. In the current case you can call the variable as follows.

$hostname = config('mail.imap_hostname_test');

Since you declare the variable inside mail.php and the variable name is imap_hostname_test, you need to call it like this. If you declare this variable inside app.php then you should call

$hostname = config('app.imap_hostname_test');

How to view UTF-8 Characters in VIM or Gvim

this work for me and do not need change any config file

vim --cmd "set encoding=utf8" --cmd "set fileencoding=utf8" fileToOpen

javascript getting my textbox to display a variable

You're on the right track with using document.getElementById() as you have done for your first two text boxes. Use something like document.getElementById("textbox3") to retrieve the element. Then you can just set its value property: document.getElementById("textbox3").value = answer;

For the "Your answer is: --", I'd recommend wrapping the "--" in a <span/> (e.g. <span id="answerDisplay">--</span>). Then use document.getElementById("answerDisplay").textContent = answer; to display it.

if, elif, else statement issues in Bash

[ is a command (or a builtin in some shells). It must be separated by whitespace from the preceding statement:

elif [

How do I find the duplicates in a list and create another list with them?

Using Set Function eg:-

arr=[1,4,2,5,2,3,4,1,4,5,2,3]
arr2=list(set(arr))
print(arr2)

Output:- [1, 2, 3, 4, 5]

  1. Remove Duplicates using array

eg:-

arr=[1,4,2,5,2,3,4,1,4,5,2,3]
arr3=[]
for i in arr:
    if(i not in arr3):
     arr3.append(i)
print(arr3)

Output:-

[1, 4, 2, 5, 3]

  1. Using Lambda Function

eg:-

rem_duplicate_func=lambda arr:set(arr)
print(rem_duplicate_func(arr))

Output:-

{1, 2, 3, 4, 5}

  1. Remove Duplicate Values from dictionary

eg:-

dict1={
    'car':["Ford","Toyota","Ford","Toyota"],
    'brand':["Mustang","Ranz","Mustang","Ranz"] } dict2={} for key,value in dict1.items():
    dict2[key]=set(value) print(dict2)

Output:-

{'car': {'Toyota', 'Ford'}, 'brand': {'Ranz', 'Mustang'}}

  1. Symmetric difference- Remove duplicate elements

eg:-

set1={1,2,4,5}
set2={2,1,5,7}
rem_dup_ele=set1.symmetric_difference(set2)
print(rem_dup_ele)

Output:-

{4, 7}

php how to go one level up on dirname(__FILE__)

You can use realpath to remove unnessesary part:

// One level up
echo str_replace(realpath(dirname(__FILE__) . '/..'), '', realpath(dirname(__FILE__)));

// Two levels etc.
echo str_replace(realpath(dirname(__FILE__) . '/../..'), '', realpath(dirname(__FILE__)));

On windows also replace \ with / if need that in URL.

How to remove unused imports in Intellij IDEA on commit?

In Mac IntelliJ IDEA, the command is Cmd + Option + O

For some older versions it is apparently Ctrl + Option + O.

(Letter O not Zero 0) on the latest version 2019.x

In Git, how do I figure out what my current revision is?

There are many ways git log -1 is the easiest and most common, I think

How can I print to the same line?

You could print the backspace character '\b' as many times as necessary to delete the line before printing the updated progress bar.

Video auto play is not working in Safari and Chrome desktop browser

The best fix I could get was adding this code just after the </video>

<script>
    document.getElementById('vid').play();
</script>

...not pretty but somehow works.

UPDATE Recently many browsers can only autoplay the videos with sound off, so you'll need to add muted attribute to the video tag too

<video autoplay muted>
...
</video>

Can you use @Autowired with static fields?

Generally, setting static field by object instance is a bad practice.

to avoid optional issues you can add synchronized definition, and set it only if private static Logger logger;

@Autowired
public synchronized void setLogger(Logger logger)
{
    if (MyClass.logger == null)
    {
        MyClass.logger = logger;
    }
}

:

Rerouting stdin and stdout from C

This is the most readily available, handy and useful way to do

freopen("dir","r",stdin);

How to check whether a string contains a substring in JavaScript?

Another alternative is KMP (Knuth–Morris–Pratt).

The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst-case of O(n·m) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.

Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:

// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.

_x000D_
_x000D_
function kmpSearch(pattern, text) {_x000D_
  if (pattern.length == 0)_x000D_
    return 0; // Immediate match_x000D_
_x000D_
  // Compute longest suffix-prefix table_x000D_
  var lsp = [0]; // Base case_x000D_
  for (var i = 1; i < pattern.length; i++) {_x000D_
    var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP_x000D_
    while (j > 0 && pattern.charAt(i) != pattern.charAt(j))_x000D_
      j = lsp[j - 1];_x000D_
    if (pattern.charAt(i) == pattern.charAt(j))_x000D_
      j++;_x000D_
    lsp.push(j);_x000D_
  }_x000D_
_x000D_
  // Walk through text string_x000D_
  var j = 0; // Number of chars matched in pattern_x000D_
  for (var i = 0; i < text.length; i++) {_x000D_
    while (j > 0 && text.charAt(i) != pattern.charAt(j))_x000D_
      j = lsp[j - 1]; // Fall back in the pattern_x000D_
    if (text.charAt(i) == pattern.charAt(j)) {_x000D_
      j++; // Next char matched, increment position_x000D_
      if (j == pattern.length)_x000D_
        return i - (j - 1);_x000D_
    }_x000D_
  }_x000D_
  return -1; // Not found_x000D_
}_x000D_
_x000D_
console.log(kmpSearch('ays', 'haystack') != -1) // true_x000D_
console.log(kmpSearch('asdf', 'haystack') != -1) // false
_x000D_
_x000D_
_x000D_

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

even adding a return statement brings up this exception, for which only solution is this code:

if(!response.isCommitted())
// Place another redirection

How to edit HTML input value colour?

Maybe something like this (just add your style):

<input type="text" 
       size="35" 
       value="Job Title e.g. Assistant Manager" 
       style="background-color:white; 
              border: solid 1px #6E6E6E;
              height: 30px; 
              font-size:18px; 
              vertical-align:9px;color:#bbb" 
        onfocus="if(this.value == 'Job Title e.g. Assistant Manager') {
                    this.value = '';
                    this.style.color='#000';
                 }" />

<input type="text" 
       name="searchterm" size="35" 
       style="background-color:white; 
              border: solid 1px #6E6E6E;
              height: 30px; 
              font-size:18px; 
              vertical-align:9px" />

UPDATE: Since placeholder attribute is very well supported on all major browsers, there is no need to do anything manually. Its possible to achieve the same thing with this:

<input type="text" 
       size="35" 
       placeholder="Job Title e.g. Assistant Manager" />

Pandas - replacing column values

Yes, you are using it incorrectly, Series.replace() is not inplace operation by default, it returns the replaced dataframe/series, you need to assign it back to your dataFrame/Series for its effect to occur. Or if you need to do it inplace, you need to specify the inplace keyword argument as True Example -

data['sex'].replace(0, 'Female',inplace=True)
data['sex'].replace(1, 'Male',inplace=True)

Also, you can combine the above into a single replace function call by using list for both to_replace argument as well as value argument , Example -

data['sex'].replace([0,1],['Female','Male'],inplace=True)

Example/Demo -

In [10]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

In [11]: data['sex'].replace([0,1],['Female','Male'],inplace=True)

In [12]: data
Out[12]:
      sex  split
0    Male      0
1  Female      1
2    Male      0
3  Female      1

You can also use a dictionary, Example -

In [15]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

In [16]: data['sex'].replace({0:'Female',1:'Male'},inplace=True)

In [17]: data
Out[17]:
      sex  split
0    Male      0
1  Female      1
2    Male      0
3  Female      1

Ansible: deploy on multiple hosts in the same time

By default Ansible will attempt to run on all hosts in parallel. See these Ansible docs for details. You can also use the serial parameter to limit the number of parallel hosts you want to be processed at any given time, so if you want to have a playbook run on just one host at a time you can specify serial:1, etc.

Ansible is designed so that each task will be run on all hosts before continuing on to the next task. So if you have 3 tasks it will ensure task 1 runs on all your hosts first, then task 2 is run, then task 3 is run. See this section of the Ansible docs for more details on this.

How to execute a raw update sql with dynamic binding in rails

Sometime would be better use name of parent class instead name of table:

# Refers to the current class
self.class.unscoped.where(self.class.primary_key => id).update_all(created _at: timestamp)

For example "Person" base class, subclasses (and database tables) "Client" and "Seller" Instead using:

Client.where(self.class.primary_key => id).update_all(created _at: timestamp)
Seller.where(self.class.primary_key => id).update_all(created _at: timestamp)

You can use object of base class by this way:

person.class.unscoped.where(self.class.primary_key => id).update_all(created _at: timestamp)

How to restore to a different database in sql server?

It is actually a bit simpler than restoring to the same server. Basically, you just walk through the "Restore Database" options. Here is a tutorial for you:

http://www.techrepublic.com/blog/window-on-windows/how-do-i-restore-a-sql-server-database-to-a-new-server/454

Especially since this is a non-production restore, you can feel comfortable just trying it out without worrying about the details too much. Just put your SQL files where you want them on your new server and give it whatever name you want and you are good to go.

How to set the JSTL variable value in javascript?

<script ...
  function(){
   var someJsVar = "<c:out value='${someJstLVarFromBackend}'/>";

  }
</script>

This works even if you dont have a hidden/non-hidden input field set somewhere in the jsp.

Processing $http response in service

As far as caching the response in service is concerned , here's another version that seems more straight forward than what I've seen so far:

App.factory('dataStorage', function($http) {
     var dataStorage;//storage for cache

     return (function() {
         // if dataStorage exists returned cached version
        return dataStorage = dataStorage || $http({
      url: 'your.json',
      method: 'GET',
      cache: true
    }).then(function (response) {

              console.log('if storage don\'t exist : ' + response);

              return response;
            });

    })();

});

this service will return either the cached data or $http.get;

 dataStorage.then(function(data) {
     $scope.data = data;
 },function(e){
    console.log('err: ' + e);
 });

Dynamic Web Module 3.0 -- 3.1

I had similar troubles in eclipse and the only way to fix it for me was to

  • Remove the web module
  • Apply
  • Change the module version
  • Add the module
  • Configure (Further configuration available link at the bottom of the dialog)
  • Apply

Just make sure you configure the web module before applying it as by default it will look for your web files in /WebContent/ and this is not what Maven project structure should be.

EDIT:

Here is a second way in case nothing else helps

  • Exit eclipse, go to your project in the file system, then to .settings folder.
  • Open the org.eclipse.wst.common.project.facet.core.xml , make backup, and remove the web module entry.
  • You can also modify the web module version there, but again, no guarantees.

How can I read SMS messages from the device programmatically in Android?

This post is a little bit old, but here is another easy solution for getting data related to SMS content provider in Android:

Use this lib: https://github.com/EverythingMe/easy-content-providers

  • Get all SMS:

    TelephonyProvider telephonyProvider = new TelephonyProvider(context);
    List<Sms> smses = telephonyProvider.getSms(Filter.ALL).getList();
    

    Each Sms has all fields, so you can get any info you need:
    address, body, receivedDate, type(INBOX, SENT, DRAFT, ..), threadId, ...

  • Gel all MMS:

    List<Mms> mmses = telephonyProvider.getMms(Filter.ALL).getList();
    
  • Gel all Thread:

    List<Thread> threads = telephonyProvider.getThreads().getList();
    
  • Gel all Conversation:

    List<Conversation> conversations = telephonyProvider.getConversations().getList();
    

It works with List or Cursor and there is a sample app to see how it looks and works.

In fact, there is a support for all Android content providers like: Contacts, Call logs, Calendar, ... Full doc with all options: https://github.com/EverythingMe/easy-content-providers/wiki/Android-providers

Hope it also helped :)

#pragma once vs include guards?

I don't think it will make a significant difference in compile time but #pragma once is very well supported across compilers but not actually part of the standard. The preprocessor may be a little faster with it as it is more simple to understand your exact intent.

#pragma once is less prone to making mistakes and it is less code to type.

To speed up compile time more just forward declare instead of including in .h files when you can.

I prefer to use #pragma once.

See this wikipedia article about the possibility of using both.

Unit testing with Spring Security

Personally I would just use Powermock along with Mockito or Easymock to mock the static SecurityContextHolder.getSecurityContext() in your unit/integration test e.g.

@RunWith(PowerMockRunner.class)
@PrepareForTest(SecurityContextHolder.class)
public class YourTestCase {

    @Mock SecurityContext mockSecurityContext;

    @Test
    public void testMethodThatCallsStaticMethod() {
        // Set mock behaviour/expectations on the mockSecurityContext
        when(mockSecurityContext.getAuthentication()).thenReturn(...)
        ...
        // Tell mockito to use Powermock to mock the SecurityContextHolder
        PowerMockito.mockStatic(SecurityContextHolder.class);

        // use Mockito to set up your expectation on SecurityContextHolder.getSecurityContext()
        Mockito.when(SecurityContextHolder.getSecurityContext()).thenReturn(mockSecurityContext);
        ...
    }
}

Admittedly there is quite a bit of boiler plate code here i.e. mock an Authentication object, mock a SecurityContext to return the Authentication and finally mock the SecurityContextHolder to get the SecurityContext, however its very flexible and allows you to unit test for scenarios like null Authentication objects etc. without having to change your (non test) code

Add an index (numeric ID) column to large data frame

If your data.frame is a data.table, you can use special symbol .I:

data[, ID := .I]

How do I list the symbols in a .so file

For Android .so files, the NDK toolchain comes with the required tools mentioned in the other answers: readelf, objdump and nm.

C++: Print out enum value as text

Using map:

#include <iostream>
#include <map>
#include <string>

enum Errors {ErrorA=0, ErrorB, ErrorC};

std::ostream& operator<<(std::ostream& out, const Errors value){
    static std::map<Errors, std::string> strings;
    if (strings.size() == 0){
#define INSERT_ELEMENT(p) strings[p] = #p
        INSERT_ELEMENT(ErrorA);     
        INSERT_ELEMENT(ErrorB);     
        INSERT_ELEMENT(ErrorC);             
#undef INSERT_ELEMENT
    }   

    return out << strings[value];
}

int main(int argc, char** argv){
    std::cout << ErrorA << std::endl << ErrorB << std::endl << ErrorC << std::endl;
    return 0;   
}

Using array of structures with linear search:

#include <iostream>
#include <string>

enum Errors {ErrorA=0, ErrorB, ErrorC};

std::ostream& operator<<(std::ostream& out, const Errors value){
#define MAPENTRY(p) {p, #p}
    const struct MapEntry{
        Errors value;
        const char* str;
    } entries[] = {
        MAPENTRY(ErrorA),
        MAPENTRY(ErrorB),
        MAPENTRY(ErrorC),
        {ErrorA, 0}//doesn't matter what is used instead of ErrorA here...
    };
#undef MAPENTRY
    const char* s = 0;
    for (const MapEntry* i = entries; i->str; i++){
        if (i->value == value){
            s = i->str;
            break;
        }
    }

    return out << s;
}

int main(int argc, char** argv){
    std::cout << ErrorA << std::endl << ErrorB << std::endl << ErrorC << std::endl;
    return 0;   
}

Using switch/case:

#include <iostream>
#include <string>

enum Errors {ErrorA=0, ErrorB, ErrorC};

std::ostream& operator<<(std::ostream& out, const Errors value){
    const char* s = 0;
#define PROCESS_VAL(p) case(p): s = #p; break;
    switch(value){
        PROCESS_VAL(ErrorA);     
        PROCESS_VAL(ErrorB);     
        PROCESS_VAL(ErrorC);
    }
#undef PROCESS_VAL

    return out << s;
}

int main(int argc, char** argv){
    std::cout << ErrorA << std::endl << ErrorB << std::endl << ErrorC << std::endl;
    return 0;   
}

Properties private set;

Maybe I'm misunderstanding, but if you want truly readonly Ids why not use an actual readonly field?

public class Person
{
   public Person(int id)
   {
      m_id = id;
   }

   readonly int m_id;
   public int Id { get { return m_id; } }
}

SQL Server Configuration Manager not found

On windows 10 Control Panel?Administrative Tools?Computer Management

Win 10 SQL configuration manager

jQuery's .click - pass parameters to user function

For thoroughness, I came across another solution which was part of the functionality introduced in version 1.4.3 of the jQuery click event handler.

It allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the .click() function as the first parameter, followed by the event handler function.

Here's some code to illustrate what I mean:

// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);

// in your function, just grab the event object and go crazy...
function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);
}

I know it's late in the game for this question, but the previous answers led me to this solution, so I hope it helps someone sometime!

Initializing an Array of Structs in C#

I'd use a static constructor on the class that sets the value of a static readonly array.

public class SomeClass
{
   public readonly MyStruct[] myArray;

   public static SomeClass()
   {
      myArray = { {"foo", "bar"},
                  {"boo", "far"}};
   }
}

How can a Javascript object refer to values in itself?

You can't refer to a property of an object before you have initialized that object; use an external variable.

var key1 = "it";
var obj = {
  key1 : key1,
  key2 : key1 + " works!"
};

Also, this is not a "JSON object"; it is a Javascript object. JSON is a method of representing an object with a string (which happens to be valid Javascript code).

ResultSet exception - before start of result set

It's better if you create a class that has all the query methods, inclusively, in a different package, so instead of typing all the process in every class, you just call the method from that class.

What is the difference between XML and XSD?

Actually the XSD is XML itself. Its purpose is to validate the structure of another XML document. The XSD is not mandatory for any XML, but it assures that the XML could be used for some particular purposes. The XML is only containing data in suitable format and structure.

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

Use the following extensions and just pass the action like:

_frmx.PerformSafely(() => _frmx.Show());
_frmx.PerformSafely(() => _frmx.Location = new Point(x,y));

Extension class:

public static class CrossThreadExtensions
{
    public static void PerformSafely(this Control target, Action action)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action);
        }
        else
        {
            action();
        }
    }

    public static void PerformSafely<T1>(this Control target, Action<T1> action,T1 parameter)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action, parameter);
        }
        else
        {
            action(parameter);
        }
    }

    public static void PerformSafely<T1,T2>(this Control target, Action<T1,T2> action, T1 p1,T2 p2)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action, p1,p2);
        }
        else
        {
            action(p1,p2);
        }
    }
}

What is the right way to debug in iPython notebook?

Just type import pdb in jupyter notebook, and then use this cheatsheet to debug. It's very convenient.

c --> continue, s --> step, b 12 --> set break point at line 12 and so on.

Some useful links: Python Official Document on pdb, Python pdb debugger examples for better understanding how to use the debugger commands.

Some useful screenshots: enter image description hereenter image description here

How to merge multiple lists into one list in python?

import itertools
ab = itertools.chain(['it'], ['was'], ['annoying'])
list(ab)

Just another method....

Call of overloaded function is ambiguous

Cast the value so the compiler knows which function to call:

p.setval(static_cast<const char *>( 0 ));

Note, that you have a segmentation fault in your code after you get it to compile (depending on which function you really wanted to call).

How do I make WRAP_CONTENT work on a RecyclerView

Update your view with null value instead of parent viewgroup in Adapter viewholder onCreateViewHolder method.

@Override
public AdapterItemSku.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = inflator.inflate(R.layout.layout_item, null, false);
    return new MyViewHolder(view);
}

Authenticate Jenkins CI for Github private repository

Another option is to use GitHub personal access tokens:

  • Go to https://github.com/settings/tokens/new
  • Add repo scope
  • In Jenkins, add a GitHub source
  • Use Repository HTTPS URL
  • Add the HTTPS URL of the git repo (not the SSH one, eg. https://github.com/my-username/my-project.git)
  • Add credential
    • Kind: Username with Password
    • Username: the GitHub username
    • Password: the personal access token you created on GitHub
    • ID: something like github-token-for-my-username

I tested this on Jenkins ver. 2.222.1 and Jenkins GitHub plugin 1.29.5 with a private GitHub repo.

'setInterval' vs 'setTimeout'

setInterval()

setInterval is a time interval based code execution method that has the native ability to repeatedly run specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().

if you want to loop code for animations or clocks Then use setInterval.

function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);

setTimeout()

setTimeout is a time based code execution method that will execute script only one time when the interval is reached, and not repeat again unless you gear it to loop the script by nesting the setTimeout object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().

function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);

if you want something to happen one time after some seconds Then use setTimeout... because it only executes one time when the interval is reached.

How to delete a remote tag?

If you have a tag created starting with the # character, e.g. #ST002, you might find that u are unable to delete using normal patterns. i.e.

git tag -d #STOO2

Will not delete the tag, but wrapping it in a String Literal like so

git tag -d "#ST002" or git tag -d '#ST002'

That will get it deleted. Hoping it will help someone who made the mistake of using # to write tag names.

How do I tell if an object is a Promise?

I use this function as a universal solution:

function isPromise(value) {
  return value && value.then && typeof value.then === 'function';
}

How to get a cross-origin resource sharing (CORS) post request working

I finally stumbled upon this link "A CORS POST request works from plain javascript, but why not with jQuery?" that notes that jQuery 1.5.1 adds the

 Access-Control-Request-Headers: x-requested-with

header to all CORS requests. jQuery 1.5.2 does not do this. Also, according to the same question, setting a server response header of

Access-Control-Allow-Headers: *

does not allow the response to continue. You need to ensure the response header specifically includes the required headers. ie:

Access-Control-Allow-Headers: x-requested-with 

How to make an HTTP request + basic auth in Swift

my solution works as follows:

import UIKit


class LoginViewController: UIViewController, NSURLConnectionDataDelegate {

  @IBOutlet var usernameTextField: UITextField
  @IBOutlet var passwordTextField: UITextField

  @IBAction func login(sender: AnyObject) {
    var url = NSURL(string: "YOUR_URL")
    var request = NSURLRequest(URL: url)
    var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)

  }

  func connection(connection:NSURLConnection!, willSendRequestForAuthenticationChallenge challenge:NSURLAuthenticationChallenge!) {

    if challenge.previousFailureCount > 1 {

    } else {
        let creds = NSURLCredential(user: usernameTextField.text, password: passwordTextField.text, persistence: NSURLCredentialPersistence.None)
        challenge.sender.useCredential(creds, forAuthenticationChallenge: challenge)

    }

}

  func connection(connection:NSURLConnection!, didReceiveResponse response: NSURLResponse) {
    let status = (response as NSHTTPURLResponse).statusCode
    println("status code is \(status)")
    // 200? Yeah authentication was successful
  }


  override func viewDidLoad() {
    super.viewDidLoad()

  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

  }  
}

You can use this class as the implementation of a ViewController. Connect your fields to the IBOutlet annotated vars and your Button to the IBAction annotated function.

Explanation: In function login you create your request with NSURL, NSURLRequest and NSURLConnection. Essential here is the delegate which references to this class (self). For receiving the delegates calls you need to

  • Add the protocol NSURLConnectionDataDelegate to the class
  • Implement the protocols' function "connection:willSendRequestForAuthenticationChallenge" This is used for adding the credentials to the request
  • Implement the protocols' function "connection:didReceiveResponse" This will check the http response status code

Why am I getting "IndentationError: expected an indented block"?

As the error message indicates, you have an indentation error. It is probably caused by a mix of tabs and spaces.

how to use a like with a join in sql?

If this is something you'll need to do often...then you may want to denormalize the relationship between tables A and B.

For example, on insert to table B, you could write zero or more entries to a juncion table mapping B to A based on partial mapping. Similarly, changes to either table could update this association.

This all depends on how frequently tables A and B are modified. If they are fairly static, then taking a hit on INSERT is less painful then repeated hits on SELECT.

Rotating videos with FFmpeg

If you don't want to re-encode your video AND your player can handle rotation metadata you can just change the rotation in the metadata using ffmpeg:

ffmpeg -i input.m4v -map_metadata 0 -metadata:s:v rotate="90" -codec copy output.m4v

How to get client IP address in Laravel 5+

For Laravel 5 you can use the Request object. Just call its ip() method, something like:

$request->ip();

Copy Paste in Bash on Ubuntu on Windows

Alternate solution over here, my windows home version Windows Subsystem Linux terminal doesn't have the property to use Shift+Ctrl (C|V)

Use an actual linux terminal![enter image description here]1

  • Install an X-server in Windows (like X-Ming)
  • sudo apt install <your_favorite_terminal>
  • export DISPLAY=:0
  • fire your terminal app, I tested with xfce4-terminal and gnome-terminal

windows #ubuntu #development

How to set a default Value of a UIPickerView

TL:DR version:

//Objective-C
[self.picker selectRow:2 inComponent:0 animated:YES];
//Swift
picker.selectRow(2, inComponent:0, animated:true)

Either you didn't set your picker to select the row (which you say you seem to have done but anyhow):

- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated

OR you didn't use the the following method to get the selected item from your picker

- (NSInteger)selectedRowInComponent:(NSInteger)component

This will get the selected row as Integer from your picker and do as you please with it. This should do the trick for yah. Good luck.

Anyhow read the ref: https://developer.apple.com/documentation/uikit/uipickerview


EDIT:

An example of manually setting and getting of a selected row in a UIPickerView:

the .h file:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
{
    UIPickerView *picker;
    NSMutableArray *source;
}

@property (nonatomic,retain) UIPickerView *picker;
@property (nonatomic,retain) NSMutableArray *source;

-(void)pressed;

@end

the .m file:

#import "ViewController.h"

@interface ViewController ()

@end
@implementation ViewController

@synthesize picker;
@synthesize source;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.view.backgroundColor = [UIColor yellowColor];

    self.source = [[NSMutableArray alloc] initWithObjects:@"EU", @"USA", @"ASIA", nil];

    UIButton *pressme = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 280, 80)];
    [pressme setTitle:@"Press me!!!" forState:UIControlStateNormal];
    pressme.backgroundColor = [UIColor lightGrayColor];
    [pressme addTarget:self action:@selector(pressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pressme];

    self.picker = [[UIPickerView alloc] initWithFrame:CGRectMake(20, 110, 280, 300)];
    self.picker.delegate = self;
    self.picker.dataSource = self;
    [self.view addSubview:self.picker];

    //This is how you manually SET(!!) a selection!
    [self.picker selectRow:2 inComponent:0 animated:YES];
}

//logs the current selection of the picker manually
-(void)pressed
{
    //This is how you manually GET(!!) a selection
    int row = [self.picker selectedRowInComponent:0];

    NSLog(@"%@", [source objectAtIndex:row]);
}

- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
    return [source count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
    return [source objectAtIndex:row];
}

#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
      inComponent:(NSInteger)component
{
//    NSLog(@"%@", [source objectAtIndex:row]);
}

@end

EDIT for Swift solution (Source: Dan Beaulieu's answer)

Define an Outlet:

@IBOutlet weak var pickerView: UIPickerView!  // for example

Then in your viewWillAppear or your viewDidLoad, for example, you can use the following:

pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)

If you inspect the Swift 2.0 framework you'll see .selectRow defined as:

func selectRow(row: Int, inComponent component: Int, animated: Bool) 

option clicking .selectRow in Xcode displays the following:

Why does C++ compilation take so long?

Some reasons are:

1) C++ grammar is more complex than C# or Java and takes more time to parse.

2) (More important) C++ compiler produces machine code and does all optimizations during compilation. C# and Java go just half way and leave these steps to JIT.

JVM property -Dfile.encoding=UTF8 or UTF-8?

This is not a direct answer, but very useful if you don't have access to how java starts: you can set the environment variable JAVA_TOOLS_OPTIONS to -Dfile.encoding="UTF-8" and every time the jvm starts it will pick up that option.

Conversion failed when converting date and/or time from character string while inserting datetime

I'm Tried this and it's working with me :

SELECT CONVERT(date, yourDate ,104)

Error in MySQL when setting default value for DATE or DATETIME

Config syntax issue

On some versions of MYSQL (tested 5.7.*) under *nix systems you should use this syntax:

[mysqld]

sql-mode="NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_ENGINE_SUBSTITUTION"

These won't work:

dash no quotes

sql-mode=NO_ENGINE_SUBSTITUTION

underscore no quotes

sql_mode=NO_ENGINE_SUBSTITUTION

underscore and quotes

sql_mode="NO_ENGINE_SUBSTITUTION"

A more complete review of config values and sql-mode:

How to setup permanent Sql Mode flags

Ring Buffer in Java

Since Guava 15.0 (released September 2013) there's EvictingQueue:

A non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full. An evicting queue must be configured with a maximum size. Each time an element is added to a full queue, the queue automatically removes its head element. This is different from conventional bounded queues, which either block or reject new elements when full.

This class is not thread-safe, and does not accept null elements.

Example use:

EvictingQueue<String> queue = EvictingQueue.create(2);
queue.add("a");
queue.add("b");
queue.add("c");
queue.add("d");
System.out.print(queue); //outputs [c, d]

'POCO' definition

To add the the other answers, the POxx terms all appear to stem from POTS (Plain old telephone services).

The POX, used to define simple (plain old) XML, rather than the complex multi-layered stuff associated with REST, SOAP etc, was a useful, and vaguely amusing, term. PO(insert language of choice)O terms have rather worn the joke thin.

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

What does "The APR based Apache Tomcat Native library was not found" mean?

I just went through this and configured it with the following:

Ubuntu 16.04

Tomcat 8.5.9

Apache2.4.25

APR 1.5.2

Tomcat-native 1.2.10

Java 8

These are the steps i used based on the older posts here:

Install package

sudo apt-get update
sudo apt-get install libtcnative-1

Verify these packages are installed

sudo apt-get install make 
sudo apt-get install gcc
sudo apt-get install openssl

Install package

sudo apt-get install libssl-dev

Install and compile Apache APR

cd /opt/tomcat/bin
sudo wget http://apache.mirror.anlx.net//apr/apr-1.5.2.tar.gz
sudo tar -xzvf apr-1.5.2.tar.gz
cd apr-1.5.2
sudo ./configure
sudo make
sudo make install

verify installation

cd /usr/local/apr/lib/
ls 

you should see the compiled file as

libapr-1.la

Download and install Tomcat Native source package

cd /opt/tomcat/bin
sudo wget https://archive.apache.org/dist/tomcat/tomcat-connectors/native/1.2.10/source/tomcat-native-1.2.10-src.tar.gz
sudo tar -xzvf tomcat-native-1.2.10-src.tar.gz
cd tomcat-native-1.2.10-src/native

verify JAVA_HOME

sudo pico ~/.bashrc
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
source ~/.bashrc
sudo ./configure --with-apr=/usr/local/apr --with-java-home=$JAVA_HOME
sudo make
sudo make install

Edit the /opt/tomcat/bin/setenv.sh file with following line:

sudo pico /opt/tomcat/bin/setenv.sh
export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:/usr/local/apr/lib'

restart tomcat

sudo service tomcat restart

Validate date in dd/mm/yyyy format using JQuery Validate

This will also checks in leap year. This is pure regex, so it's faster than any lib (also faster than moment.js). But if you gonna use a lot of dates in ur code, I do recommend to use moment.js

var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;

console.log(dateRegex.test('21/01/1986'));

enter image description here

http://regexper.com/....

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

args should be tuple.

eg:

args = ('A','B')

args = ('A',) # in case of single

How to find largest objects in a SQL Server database?

You may also use the following code:

USE AdventureWork
GO
CREATE TABLE #GetLargest 
(
  table_name    sysname ,
  row_count     INT,
  reserved_size VARCHAR(50),
  data_size     VARCHAR(50),
  index_size    VARCHAR(50),
  unused_size   VARCHAR(50)
)

SET NOCOUNT ON

INSERT #GetLargest

EXEC sp_msforeachtable 'sp_spaceused ''?'''

SELECT 
  a.table_name,
  a.row_count,
  COUNT(*) AS col_count,
  a.data_size
  FROM #GetLargest a
     INNER JOIN information_schema.columns b
     ON a.table_name collate database_default
     = b.table_name collate database_default
       GROUP BY a.table_name, a.row_count, a.data_size
       ORDER BY CAST(REPLACE(a.data_size, ' KB', '') AS integer) DESC

DROP TABLE #GetLargest

Changing cursor to waiting in javascript/jquery

I found that the only way to get the cursor to effectively reset its style back to what it had prior to being changed to the wait style was to set the original style in a style sheet or in style tags at the start of the page, set the class of the object in question to the name of the style. Then after your wait period, you set the cursor style back to an empty string, NOT "default" and it reverts back to its original value as set in your style tags or style sheet. Setting it to "default" after the wait period only changes the cursor style for every element to the style called "default" which is a pointer. It doesn't change it back to its former value.

There are two conditions to make this work. First you must set the style in a style sheet or in the header of the page with style tags, NOT as an inline style and second is to reset its style by setting the wait style back to an empty string.

Get the closest number out of an array

ES5 Version:

_x000D_
_x000D_
var counts = [4, 9, 15, 6, 2],_x000D_
  goal = 5;_x000D_
_x000D_
var closest = counts.reduce(function(prev, curr) {_x000D_
  return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);_x000D_
});_x000D_
_x000D_
console.log(closest);
_x000D_
_x000D_
_x000D_

Creating SVG elements dynamically with javascript inside HTML

Change

var svg   = document.documentElement;

to

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");

so that you create a SVG element.

For the link to be an hyperlink, simply add a href attribute :

h.setAttributeNS(null, 'href', 'http://www.google.com');

Demonstration

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

Assuming you've used home-brew to install and upgrade Postgres, you can perform the following steps.

  1. Stop current Postgres server:

    launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

  2. Initialize a new 10.1 database:

    initdb /usr/local/var/postgres10.1 -E utf8

  3. run pg_upgrade (note: change bin version if you're upgrading from something other than below):

    pg_upgrade -v \
        -d /usr/local/var/postgres \
        -D /usr/local/var/postgres10.1 \
        -b /usr/local/Cellar/postgresql/9.6.5/bin/ \
        -B /usr/local/Cellar/postgresql/10.1/bin/
    

    -v to enable verbose internal logging

    -d the old database cluster configuration directory

    -D the new database cluster configuration directory

    -b the old PostgreSQL executable directory

    -B the new PostgreSQL executable directory

  4. Move new data into place:

    cd /usr/local/var
    mv postgres postgres9.6
    mv postgres10.1 postgres
    
  5. Restart Postgres:

    launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

  6. Check /usr/local/var/postgres/server.log for details and to make sure the new server started properly.

  7. Finally, re-install the rails pg gem

    gem uninstall pg
    gem install pg
    

I suggest you take some time to read the PostgreSQL documentation to understand exactly what you're doing in the above steps to minimize frustrations.

Jquery Ajax beforeSend and success,error & complete

It's actually much easier with jQuery's promise API:

$.ajax(
            type: "GET",
            url: requestURL,
        ).then((success) =>
            console.dir(success)
        ).failure((failureResponse) =>
            console.dir(failureResponse)
        )

Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:

$.ajax(
            type: "GET",
            url: @get("url") + "logout",
            beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
        ).failure((response) -> console.log "Request was unauthorized" if response.status is 401

Get most recent row for given ID

Select [insert your fields here]
from tablename 
where signin = (select max(signin) from tablename where ID = 1)

Read line by line in bash script

What you have is piping the text "cat test" into the loop.

You just want:

cat test | \
while read CMD; do
    echo $CMD
done

Task<> does not contain a definition for 'GetAwaiter'

Just experienced this in a method that executes a linq query.

public async Task<Foo> GetSomething()
{
    return await (from foo in Foos
                  select foo).FirstOrDefault();
}

Needed to use .FirstOrDefaultAsync() instead. N00b mistake.

How to align checkboxes and their labels consistently cross-browsers

With an input type checkbox wrapped inside the label and floated to the left like so:

<label for="id" class="checkbox">
    <input type="checkbox" id="id">
    <span>The Label</span>
</label>

this worked for me:

label.checkbox {
    display: block;
}
.checkbox input {
    float: left;
    height: 18px;
    vertical-align: middle;
}
.checkbox span {
    float: left;
    line-height: 18px;
    margin: 0 0 0 20px;
}

Make sure the height of the is identical to the line-height of the (blocklevel) .

Argument Exception "Item with Same Key has already been added"

To illustrate the problem you are having, let's look at some code...

Dictionary<string, string> test = new Dictionary<string, string>();

test.Add("Key1", "Value1");  // Works fine
test.Add("Key2", "Value2");  // Works fine
test.Add("Key1", "Value3");  // Fails because of duplicate key

The reason that a dictionary has a key/value pair is a feature so you can do this...

var myString = test["Key2"];  // myString is now Value2.

If Dictionary had 2 Key2's, it wouldn't know which one to return, so it limits you to a unique key.

PreparedStatement with list of parameters in a IN clause

You can't replace ? in your query with an arbitrary number of values. Each ? is a placeholder for a single value only. To support an arbitrary number of values, you'll have to dynamically build a string containing ?, ?, ?, ... , ? with the number of question marks being the same as the number of values you want in your in clause.

Build fails with "Command failed with a nonzero exit code"

When you stop building a project when the compiler is in the middle of something "important", this error could appear. In that case, building the project again and letting it finish normally makes this error disappear.

Remove the newline character in a list read from a file

str.strip() returns a string with leading+trailing whitespace removed, .lstrip and .rstrip for only leading and trailing respectively.

grades.append(lists[i].rstrip('\n').split(','))

How do you beta test an iphone app?

In 2014 along with iOS 8 and XCode 6 apple introduced Beta Testing of iOS App using iTunes Connect.

You can upload your build to iTunes connect and invite testers using their mail id's. You can invite up to 2000 external testers using just their email address. And they can install the beta app through TestFlight

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

When I set up Django development environment for PyCharm in Mac OS X Mountain Lion with python, mysql, sequel pro application I got error same as owner of this thread. However, my answer for them who is running python-mysqldb under Mac OS Mountain Lion x86_x64 (MySql and Python also should be same architecture) and already tried everything like pip and etc. In order fix this problem do following steps:

  1. Download MySql for Python from here
  2. Untar downloaded file. In terminal window do following: tar xvfz downloade.tar.
  3. cd /to untared directory
  4. Run sudo python setup.py install
  5. If you get error something like this: "Environment Error: /usr/local/bin/mysql_config not found" then try to add path ass follows: "export PATH=$PATH:/usr/local/mysql/bin". But id did not helped to me and I found another solution. In the end of command execution error output which looks like this:

    File "/path_to_file/MySQL-python-1.2.4b4/setup_posix.py", line 25, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,))

  6. Open setup_posix.py with vim and go to line 25 (In your case it can be different unless if it is same version).

  7. Line 25 should look like this after your editing unless your mysql have symbolic link like follows '/usr/local/mysql/bin/':

    f = popen("%s --%s" % ('/usr/local/mysql/bin/mysql_config', what))

  8. After this I got another error as following:

    django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.8-intel.egg/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib Referenced from: /Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.8-intel.egg/_mysql.so Reason: image not found

  9. Finally I did following in console:

    sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

Currently everything works fine. So I hope it will be helpful for somebody who uses Mac. :)

How do I validate a date in rails?

Active Record gives you _before_type_cast attributes which contain the raw attribute data before typecasting. This can be useful for returning error messages with pre-typecast values or just doing validations that aren't possible after typecast.

I would shy away from Daniel Von Fange's suggestion of overriding the accessor, because doing validation in an accessor changes the accessor contract slightly. Active Record has a feature explicitly for this situation. Use it.

JPA EntityManager: Why use persist() over merge()?

JPA is indisputably a great simplification in the domain of enterprise applications built on the Java platform. As a developer who had to cope up with the intricacies of the old entity beans in J2EE I see the inclusion of JPA among the Java EE specifications as a big leap forward. However, while delving deeper into the JPA details I find things that are not so easy. In this article I deal with comparison of the EntityManager’s merge and persist methods whose overlapping behavior may cause confusion not only to a newbie. Furthermore I propose a generalization that sees both methods as special cases of a more general method combine.

Persisting entities

In contrast to the merge method the persist method is pretty straightforward and intuitive. The most common scenario of the persist method's usage can be summed up as follows:

"A newly created instance of the entity class is passed to the persist method. After this method returns, the entity is managed and planned for insertion into the database. It may happen at or before the transaction commits or when the flush method is called. If the entity references another entity through a relationship marked with the PERSIST cascade strategy this procedure is applied to it also."

enter image description here

The specification goes more into details, however, remembering them is not crucial as these details cover more or less exotic situations only.

Merging entities

In comparison to persist, the description of the merge's behavior is not so simple. There is no main scenario, as it is in the case of persist, and a programmer must remember all scenarios in order to write a correct code. It seems to me that the JPA designers wanted to have some method whose primary concern would be handling detached entities (as the opposite to the persist method that deals with newly created entities primarily.) The merge method's major task is to transfer the state from an unmanaged entity (passed as the argument) to its managed counterpart within the persistence context. This task, however, divides further into several scenarios which worsen the intelligibility of the overall method's behavior.

Instead of repeating paragraphs from the JPA specification I have prepared a flow diagram that schematically depicts the behaviour of the merge method:

enter image description here

So, when should I use persist and when merge?

persist

  • You want the method always creates a new entity and never updates an entity. Otherwise, the method throws an exception as a consequence of primary key uniqueness violation.
  • Batch processes, handling entities in a stateful manner (see Gateway pattern).
  • Performance optimization

merge

  • You want the method either inserts or updates an entity in the database.
  • You want to handle entities in a stateless manner (data transfer objects in services)
  • You want to insert a new entity that may have a reference to another entity that may but may not be created yet (relationship must be marked MERGE). For example, inserting a new photo with a reference to either a new or a preexisting album.

What is Unicode, UTF-8, UTF-16?

Why unicode? Because ASCII has just 127 characters. Those from 128 to 255 differ in different countries, that's why there are codepages. So they said lets have up to 1114111 characters. So how do you store the highest codepoint? You'll need to store it using 21 bits, so you'll use a DWORD having 32 bits with 11 bits wasted. So if you use a DWORD to store a unicode character, it is the easiest way because the value in your DWORD matches exactly the codepoint. But DWORD arrays are of course larger than WORD arrays and of course even larger than BYTE arrays. That's why there is not only utf-32, but also utf-16. But utf-16 means a WORD stream, and a WORD has 16 bits so how can the highest codepoint 1114111 fit into a WORD? It cannot! So they put everyything higher than 65535 into a DWORD which they call a surrogate-pair. Such surrogate-pair are two WORDS and can get detected by looking at the first 6 bits. So what about utf-8? It is a byte array or byte stream, but how can the highest codepoint 1114111 fit into a byte? It cannot! Okay, so they put in also a DWORD right? Or possibly a WORD, right? Almost right! They invented utf-8 sequences which means that every codepoint higher than 127 must get encoded into a 2-byte, 3-byte or 4-byte sequence. Wow! But how can we detect such sequences? Well, everything up to 127 is ASCII and is a single byte. What starts with 110 is a two-byte sequence, what starts with 1110 is a three-byte sequence and what starts with 11110 is a four-byte sequence. The remaining bits of these so called "startbytes" belong to the codepoint. Now depending on the sequence, following bytes must follow. A following byte starts with 10, the remaining bits are 6 bits of payload bits and belong to the codepoint. Concatenate the payload bits of the startbyte and the following byte/s and you'll have the codepoint. That's all the magic of utf-8.

Truncate (not round off) decimal numbers in javascript

Here is what I use:

var t = 1;
for (var i = 0; i < decimalPrecision; i++)
    t = t * 10;

var f = parseFloat(value);
return (Math.floor(f * t)) / t;

How to execute powershell commands from a batch file?

untested.cmd

;@echo off
;Findstr -rbv ; %0 | powershell -c - 
;goto:sCode

set-location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
set-location ZoneMap\Domains
new-item TESTSERVERNAME
set-location TESTSERVERNAME
new-itemproperty . -Name http -Value 2 -Type DWORD

;:sCode 
;echo done
;pause & goto :eof

What is the LDF file in SQL Server?

ldf saves the log of the db, certainly doesn't saves any real data, but is very important for the proper function of the database.

You can however change the log model to the database to simple so this log does not grow too fast.

Check this for example.

Check here for reference.

Incrementing a variable inside a Bash loop

while read -r country _; do
  if [[ $country = 'US' ]]; then
    ((USCOUNTER++))
    echo "US counter $USCOUNTER"
  fi
done < "$FILE"

Main differences between SOAP and RESTful web services in Java

  • REST stands for representational state transfer whereas SOAP stands for Simple Object Access Protocol.

  • SOAP defines its own security where as REST inherits security from the underlying transport.

  • SOAP does not support error handling, but REST has built-in error handling.

  • REST is lightweight and does not require XML parsing. REST can be consumed by any client, even a web browser with Ajax and JavaScript. REST consumes less bandwidth, it does not require a SOAP header for every message.

    • REST is useful over any protocol which provide a URI. Ignore point 5 for REST as mentioned below in the picture.

SOAP vs. REST

Is 'bool' a basic datatype in C++?

C is meant to be a step above assembly language. The C if-statement is really just syntactical sugar for "branch-if-zero", so the idea of booleans as an independent datatype was a foreign concept at the time. (1)

Even now, C/C++ booleans are usually little more than an alias for a single byte data type. As such, it's really more of a purposing label than an independent datatype.

(1) Of course, modern compilers are a bit more advanced in their handling of if statements. This is from the standpoint of C as a new language.

How to write multiple conditions of if-statement in Robot Framework

The below code worked fine:

Run Keyword if    '${value1}' \ \ == \ \ '${cost1}' \ and \ \ '${value2}' \ \ == \ \ 'cost2'    LOG    HELLO

How to format a date using ng-model?

I'm using jquery datepicker to select date. My directive read date and convert it to json date format (in milliseconds) store in ng-model data while display formatted date.and reverse if ng-model have json date (in millisecond) my formatter display in my format as jquery datepicker.

Html Code:

<input type="text" jqdatepicker  ng-model="course.launchDate" required readonly />

Angular Directive:

myModule.directive('jqdatepicker', function ($filter) {
    return {
        restrict: 'A',
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker({
                dateFormat: 'dd/mm/yy',
                onSelect: function (date) {   
                    var ar=date.split("/");
                    date=new Date(ar[2]+"-"+ar[1]+"-"+ar[0]);
                    ngModelCtrl.$setViewValue(date.getTime());            
                    scope.$apply();
                }
            });
            ngModelCtrl.$formatters.unshift(function(v) {
            return $filter('date')(v,'dd/MM/yyyy'); 
            });

        }
    };
});

Set folder for classpath

If you are using Java 6 or higher you can use wildcards of this form:

java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp

If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:

java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp

There is nothing like lib\*\* or lib\** wildcard for the kind of job you want to be done.

What's the difference between Unicode and UTF-8?

There's a lot of misunderstanding being displayed here. Unicode isn't an encoding, but the Unicode standard is devoted primarily to encoding anyway.

ISO 10646 is the international character set you (probably) care about. It defines a mapping between a set of named characters (e.g., "Latin Capital Letter A" or "Greek small letter alpha") and a set of code points (a number assigned to each -- for example, 61 hexadecimal and 3B1 hexadecimal for those two respectively; for Unicode code points, the standard notation would be U+0061 and U+03B1).

At one time, Unicode defined its own character set, more or less as a competitor to ISO 10646. That was a 16-bit character set, but it was not UTF-16; it was known as UCS-2. It included a rather controversial technique to try to keep the number of necessary characters to a minimum (Han Unification -- basically treating Chinese, Japanese and Korean characters that were quite a bit alike as being the same character).

Since then, the Unicode consortium has tacitly admitted that that wasn't going to work, and now concentrate primarily on ways to encode the ISO 10646 character set. The primary methods are UTF-8, UTF-16 and UCS-4 (aka UTF-32). Those (except for UTF-8) also have LE (little endian) and BE (big-endian) variants.

By itself, "Unicode" could refer to almost any of the above (though we can probably eliminate the others that it shows explicitly, such as UTF-8). Unqualified use of "Unicode" probably happens the most often on Windows, where it will almost certainly refer to UTF-16. Early versions of Windows NT adopted Unicode when UCS-2 was current. After UCS-2 was declared obsolete (around Win2k, if memory serves), they switched to UTF-16, which is the most similar to UCS-2 (in fact, it's identical for characters in the "basic multilingual plane", which covers a lot, including all the characters for most Western European languages).

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

How to use Visual Studio C++ Compiler?

You may be forgetting something. Before #include <iostream>, write #include <stdafx.h> and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."

Php header location redirect not working

Pekka answered my question in the comments. He didn't post an answer, so I am now. Use the exit() method after the header redirect. For some reason the rest of the code of the page continues to execute after the header() method redirect. When the rest of the code executes, the echo statement is outputted to the page. And you can't redirect using the header function after you output to the page. To avoid rest of the code from executing, use exit(). Thanks Pekka.

UPDATE: When using the web browser Internet Explorer, I have noticed that $_POST['cancel'] is not reliable. I am not exactly sure why this is, but I suspect IE posts additional variables on a form submit, specifically the variable 'cancel' is posted. I solved this by using a variable name other than 'cancel'. The combination of using exit() and a unique variable name is working for me.

How to make a input field readonly with JavaScript?

Try This :

document.getElementById(<element_ID>).readOnly=true;

curl Failed to connect to localhost port 80

Since you have a ::1 localhost line in your hosts file, it would seem that curl is attempting to use IPv6 to contact your local web server.

Since the web server is not listening on IPv6, the connection fails.

You could try to use the --ipv4 option to curl, which should force an IPv4 connection when both are available.

How do I find out which keystore was used to sign an app?

You can use Java 7's Key and Certificate Management Tool keytool to check the signature of a keystore or an APK without extracting any files.

Signature of an APK or AAB

# APK file
keytool -printcert -jarfile app.apk

# AAB file
keytool -printcert -jarfile app.aab

The output will reveal the signature owner/issuer and MD5, SHA1 and SHA256 fingerprints of the APK file app.apk or AAB file app.aab.

(Note that the -jarfile argument was introduced in Java 7; see the documentation for more details.)

Signature of a keystore

keytool -list -v -keystore release.jks

The output will reveal the aliases (entries) in the keystore file release.jks, with the certificate fingerprints (MD5, SHA1 and SHA256).

If the SHA1 fingerprints between the APK and the keystore match, then you can rest assured that that app is signed with the key.

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

Just delete /etc/ImageMagick/policy.xml file. E.g.

rm /etc/<ImageMagick_PATH>/policy.xml

For ImageMagick 6, it's:

sudo rm /etc/ImageMagick-6/policy.xml

XPath: difference between dot and text()

enter image description here The XPath text() function locates elements within a text node while dot (.) locate elements inside or outside a text node. In the image description screenshot, the XPath text() function will only locate Success in DOM Example 2. It will not find success in DOM Example 1 because it's located between the tags.

In addition, the text() function will not find success in DOM Example 3 because success does not have a direct relationship to the element . Here's a video demo explaining the difference between text() and dot (.) https://youtu.be/oi2Q7-0ZIBg

Can you Run Xcode in Linux?

I really wanted to comment, not answer. But just to be precise, OSX is not based on BSD, it is an evolution of NeXTStep. The NeXTStep OS utilizes the Mach kernel developed by CMU. It was originally designed as a MicroKernel, but due to performance constraints, they eventually decided they needed to include the Unix portion of the API into the kernel itself and so a BSD-compatible "server" (originally intended to process requests for BSD-compatible kernel messages) was moved into the kernel, making it a Monolithic kernel. It may be BSD compatible in the programming API, but it is NOT BSD.

The rest of the OS involved ObjectiveC (under arrangements between Stepstone and Richard Stallman of GNU/GCC) with a GUI based on a technology called "Display Postscript" ... sort of like an X Server, but with postscript commands. OS X changed Display Postscript to Display PDF, and increased the general hardware requirements 1000 fold (NeXT could run in 8-16MB, now you need GB).

Due to the close marriage of GCC and Objective C and NeXT, your best bet at running XCode natively under Linux would be to do a port (if you can get ahold of the source - good luck) utilizing the GNUStep libraries. Originally designed for NextStep and then OpenStep compatibility, I've heard they are now more-or-less Cocoa compatible, but I've not played with any of it in almost 2 decades. Of course that only gets you as far as ObjC, not Swift, and I don't know if Apple is going to OpenSource it.

Line continue character in C#

@"string here
that is long you mean"

But be careful, because

@"string here
           and space before this text
     means the space is also a part of the string"

It also escapes things in the string

@"c:\\folder" // c:\\folder
@"c:\folder" // c:\folder
"c:\\folder" // c:\folder

Related

How can I count the number of matches for a regex?

Use the below code to find the count of number of matches that the regex finds in your input

        Pattern p = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL);// "regex" here indicates your predefined regex.
        Matcher m = p.matcher(pattern); // "pattern" indicates your string to match the pattern against with
        boolean b = m.matches();
        if(b)
        count++;
        while (m.find())
        count++;

This is a generalized code not specific one though, tailor it to suit your need

Please feel free to correct me if there is any mistake.

SELECT where row value contains string MySQL

This should work:

SELECT * FROM Accounts WHERE Username LIKE '%$query%'

C#: what is the easiest way to subtract time?

Hi if you are going to subtract only Integer value from DateTime then you have to write code like this

DateTime.Now.AddHours(-2)

Here I am subtracting 2 hours from the current date and time

no match for ‘operator<<’ in ‘std::operator

You need to overload operator << for mystruct class

Something like :-

friend ostream& operator << (ostream& os, const mystruct& m)
{
    os << m.m_a <<" " << m.m_b << endl;
    return os ;
}

See here

Nested jQuery.each() - continue/break

There is no clean way to do this and like @Nick mentioned above it might just be easier to use the old school way of loops as then you can control this. But if you want to stick with what you got there is one way you could handle this. I'm sure I will get some heat for this one. But...

One way you could do what you want without an if statement is to raise an error and wrap your loop with a try/catch block:

try{
$(sentences).each(function() {
    var s = this;
    alert(s);
    $(words).each(function(i) {
        if (s.indexOf(this) > -1)
        {
            alert('found ' + this);
            throw "Exit Error";
        }
    });
});
}
catch (e)
{
    alert(e)
}

Ok, let the thrashing begin.

Jquery click not working with ipad

I know this was asked a long time ago but I found an answer while searching for this exact question.

There are two solutions.

You can either set an empty onlick attribute on the html element:

<div class="clickElement" onclick=""></div>

Or you can add it in css by setting the pointer cursor:

.clickElement { cursor:pointer }

The problem is that on ipad, the first click on a non-anchor element registers as a hover. This is not really a bug, because it helps with sites that have hover-menus that haven't been tablet/mobile optimised. Setting the cursor or adding an empty onclick attribute tells the browser that the element is indeed a clickable area.

(via http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working)

How do I run Google Chrome as root?

I tried this with Kali linux, Debian, CentOs 7,And Ubuntu

(Permanent Method)

  1. Edit the file with any text editor (I used Leafpad) Run this code your terminal leafpad/opt/google/chrome/google-chrome

  2. (Normally its end line) find exec -a "$0" "$HERE/chrome" "$@" or exec -a "$0" "$HERE/chrome" "$PROFILE_DIRECTORY_FLAG" \ "$@"

  3. change as exec -a "$0" "$HERE/chrome" "$@" --no-sandbox --user-data-dir

(Just Simple Method)

Run This command in your terminal

$ google-chrome --no-sandbox --user-data-dir

Or

$ google-chrome-stable --no-sandbox --user-data-dir

Encoding an image file with base64

Borrowing from what Ivo van der Wijk and gnibbler have developed earlier, this is a dynamic solution

import cStringIO
import PIL.Image

image_data = None

def imagetopy(image, output_file):
    with open(image, 'rb') as fin:
        image_data = fin.read()

    with open(output_file, 'w') as fout:
        fout.write('image_data = '+ repr(image_data))

def pytoimage(pyfile):
    pymodule = __import__(pyfile)
    img = PIL.Image.open(cStringIO.StringIO(pymodule.image_data))
    img.show()

if __name__ == '__main__':
    imagetopy('spot.png', 'wishes.py')
    pytoimage('wishes')

You can then decide to compile the output image file with Cython to make it cool. With this method, you can bundle all your graphics into one module.

Cannot enqueue Handshake after invoking quit

According to:

TL;DR You need to establish a new connection by calling the createConnection method after every disconnection.

and

Note: If you're serving web requests, then you shouldn't be ending connections on every request. Just create a connection on server startup and use the connection/client object to query all the time. You can listen on the error event to handle server disconnection and for reconnecting purposes. Full code here.


From:

It says:

Server disconnects

You may lose the connection to a MySQL server due to network problems, the server timing you out, or the server crashing. All of these events are considered fatal errors, and will have the err.code = 'PROTOCOL_CONNECTION_LOST'. See the Error Handling section for more information.

The best way to handle such unexpected disconnects is shown below:

function handleDisconnect(connection) {
  connection.on('error', function(err) {
    if (!err.fatal) {
      return;
    }

    if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
      throw err;
    }

    console.log('Re-connecting lost connection: ' + err.stack);

    connection = mysql.createConnection(connection.config);
    handleDisconnect(connection);
    connection.connect();
  });
}

handleDisconnect(connection);

As you can see in the example above, re-connecting a connection is done by establishing a new connection. Once terminated, an existing connection object cannot be re-connected by design.

With Pool, disconnected connections will be removed from the pool freeing up space for a new connection to be created on the next getConnection call.


I have tweaked the function such that every time a connection is needed, an initializer function adds the handlers automatically:

function initializeConnection(config) {
    function addDisconnectHandler(connection) {
        connection.on("error", function (error) {
            if (error instanceof Error) {
                if (error.code === "PROTOCOL_CONNECTION_LOST") {
                    console.error(error.stack);
                    console.log("Lost connection. Reconnecting...");

                    initializeConnection(connection.config);
                } else if (error.fatal) {
                    throw error;
                }
            }
        });
    }

    var connection = mysql.createConnection(config);

    // Add handlers.
    addDisconnectHandler(connection);

    connection.connect();
    return connection;
}

Initializing a connection:

var connection = initializeConnection({
    host: "localhost",
    user: "user",
    password: "password"
});

Minor suggestion: This may not apply to everyone but I did run into a minor issue relating to scope. If the OP feels this edit was unnecessary then he/she can choose to remove it. For me, I had to change a line in initializeConnection, which was var connection = mysql.createConnection(config); to simply just

connection = mysql.createConnection(config);

The reason being that if connection is a global variable in your program, then the issue before was that you were making a new connection variable when handling an error signal. But in my nodejs code, I kept using the same global connection variable to run queries on, so the new connection would be lost in the local scope of the initalizeConnection method. But in the modification, it ensures that the global connection variable is reset This may be relevant if you're experiencing an issue known as

Cannot enqueue Query after fatal error

after trying to perform a query after losing connection and then successfully reconnecting. This may have been a typo by the OP, but I just wanted to clarify.

Questions every good .NET developer should be able to answer?

This might not be what you want to hear, but I would recommend not focusing on narrow technologies, but on general programming and problem solving skills. Solid developers can learn whatever you want them to do quickly.

I, for instance, am not a Compact Framework guy, so I might fail your interview if you went that direction. But if I needed to use it I could do some research and jump right in.

Joel's book, Smart and Gets Things Done, has great advice for hiring devs and there are large juicy sections about the kinds of questions to ask. I highly recommend it.

Ajax post request in laravel 5 return error 500 (Internal Server Error)

While this question exists for a while, but no accepted answer is given I'd like to point you towards the solution. Because you're sending with ajax, and presumably still use the CSRF middleware, you need to provide an additional header with your request.

Add a meta-tag to each page (or master layout): <meta name="csrf-token" content="{{ csrf_token() }}">

And add to your javascript-file (or section within the page):

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});

See https://laravel.com/docs/master/csrf#csrf-x-csrf-token for more details.

How to get json response using system.net.webrequest in c#?

You need to explicitly ask for the content type.

Add this line:

 request.ContentType = "application/json; charset=utf-8";
At the appropriate place

How to extract text from an existing docx file using python-docx

It seems that there is no official solution for this problem, but there is a workaround posted here https://github.com/savoirfairelinux/python-docx/commit/afd9fef6b2636c196761e5ed34eb05908e582649

just update this file "...\site-packages\docx\oxml_init_.py"

# add
import re
import sys

# add
def remove_hyperlink_tags(xml):
    if (sys.version_info > (3, 0)):
        xml = xml.decode('utf-8')
    xml = xml.replace('</w:hyperlink>', '')
    xml = re.sub('<w:hyperlink[^>]*>', '', xml)
    if (sys.version_info > (3, 0)):
        xml = xml.encode('utf-8')
    return xml
    
# update
def parse_xml(xml):
    """
    Return root lxml element obtained by parsing XML character string in
    *xml*, which can be either a Python 2.x string or unicode. The custom
    parser is used, so custom element classes are produced for elements in
    *xml* that have them.
    """
    root_element = etree.fromstring(remove_hyperlink_tags(xml), oxml_parser)
    return root_element

and of course don't forget to mention in the documentation that use are changing the official library

Viewing all defined variables

In my Python 2.7 interpreter, the same whos command that exists in MATLAB exists in Python. It shows the same details as the MATLAB analog (variable name, type, and value/data).

Note that in the Python interpreter, whos lists all variables in the "interactive namespace".

jQuery UI dialog positioning

a bit late but you can do this now by using $j(object).offset().left and .top accordingly.

JavaScript: Global variables after Ajax requests

It seems that your problem is simply a concurrency issue. The post function takes a callback argument to tell you when the post has been finished. You cannot make the alert in global scope like this and expect that the post has already been finished. You have to move it to the callback function.

Make error: missing separator

As indicated in the online manual, the most common cause for that error is that lines are indented with spaces when make expects tab characters.

Correct

target: 
\tcmd

where \t is TAB (U+0009)

Wrong

target:
....cmd

where each . represents a SPACE (U+0020).

How to embed a Google Drive folder in a website

For business/Gsuite apps or whatever they call them, you can specify the domain (had problem with 500 errors with the original answer when logged into multiple Google accounts).

<iframe 
  src="https://drive.google.com/a/YOUR_COMPANY_DOMAIN/embeddedfolderview?id=FOLDER-ID" 
  style="width:100%; height:600px; border:0;"
>
</iframe>

How to empty a char array?

You can use the following instruction:

strcpy_s(members, "");

How do I print bold text in Python?

This depends if you're using linux/unix:

>>> start = "\033[1m"
>>> end = "\033[0;0m"
>>> print "The" + start + "text" + end + " is bold."
The text is bold.

The word text should be bold.

"Unorderable types: int() < str()"

Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.

SQL Server - INNER JOIN WITH DISTINCT

I think you actually provided a good start for the correct answer right in your question (you just need the correct syntax). I had this exact same problem, and putting DISTINCT in a sub-query was indeed less costly than what other answers here have proposed.

select a.FirstName, a.LastName, v.District
from AddTbl a 
inner join (select distinct LastName, District 
    from ValTbl) v
   on a.LastName = v.LastName
order by Firstname   

How to wait for async method to complete?

Best Solution to wait AsynMethod till complete the task is

var result = Task.Run(async() => await yourAsyncMethod()).Result;

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

What is the purpose of the return statement?

Difference between "return" and "print" can also be found in the following example:

RETURN:

def bigger(a, b):
    if a > b:
        return a
    elif a <b:
        return b
    else:
        return a

The above code will give correct results for all inputs.

PRINT:

def bigger(a, b):
    if a > b:
        print a
    elif a <b:
        print b
    else:
        print a

NOTE: This will fail for many test cases.

ERROR:

----  

FAILURE: Test case input: 3, 8.

            Expected result: 8  

FAILURE: Test case input: 4, 3.

            Expected result: 4  

FAILURE: Test case input: 3, 3.

            Expected result: 3  

You passed 0 out of 3 test cases

Can I limit the length of an array in JavaScript?

You need to actually use the shortened array after you remove items from it. You are ignoring the shortened array.

You convert the cookie into an array. You reduce the length of the array and then you never use that shortened array. Instead, you just use the old cookie (the unshortened one).

You should convert the shortened array back to a string with .join(",") and then use it for the new cookie instead of using old_cookie which is not shortened.

You may also not be using .splice() correctly, but I don't know exactly what your objective is for shortening the array. You can read about the exact function of .splice() here.

Add Bootstrap Glyphicon to Input Box

You should be able to do this with existing bootstrap classes and a little custom styling.

<form>
    <div class="input-prepend">
        <span class="add-on">
            <i class="icon-user"></i>
        </span>
        <input class="span2" id="prependedInput" type="text" placeholder="Username" style="background-color: #eeeeee;border-left: #eeeeee;">
    </div>         

Edit The icon is referenced via the icon-user class. This answer was written at the time of Bootstrap version 2. You can see the reference on the following page: http://getbootstrap.com/2.3.2/base-css.html#images

jQuery select element in parent window

You can also use,

parent.jQuery("#testdiv").attr("style", content from form);

How can I commit a single file using SVN over a network?

cd myapp/trunk
svn commit -m "commit message" page1.html

For more information, see:

svn commit --help

I also recommend this free book, if you're just getting started with Subversion.

How to launch Safari and open URL from iOS app

Swift Syntax:

UIApplication.sharedApplication().openURL(NSURL(string:"http://www.reddit.com/")!)

New Swift Syntax for iOS 9.3 and earlier

As of some new version of Swift (possibly swift 2?), UIApplication.sharedApplication() is now UIApplication.shared (making better use of computed properties I'm guessing). Additionally URL is no longer implicitly convertible to NSURL, must be explicitly converted with as!

UIApplication.sharedApplication.openURL(NSURL(string:"http://www.reddit.com/") as! URL)

New Swift Syntax as of iOS 10.0

The openURL method has been deprecated and replaced with a more versatile method which takes an options object and an asynchronous completion handler as of iOS 10.0

UIApplication.shared.open(NSURL(string:"http://www.reddit.com/")! as URL)

How do I rotate text in css?

In your case, it's the best to use rotate option from transform property as mentioned before. There is also writing-mode property and it works like rotate(90deg) so in your case, it should be rotated after it's applied. Even it's not the right solution in this case but you should be aware of this property.

Example:

writing-mode:vertical-rl;

More about transform: https://kolosek.com/css-transform/

More about writing-mode: https://css-tricks.com/almanac/properties/w/writing-mode/

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

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

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

Decoding UTF-8 strings in Python

It's an encoding error - so if it's a unicode string, this ought to fix it:

text.encode("windows-1252").decode("utf-8")

If it's a plain string, you'll need an extra step:

text.decode("utf-8").encode("windows-1252").decode("utf-8")

Both of these will give you a unicode string.

By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:

>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}

How to set adaptive learning rate for GradientDescentOptimizer?

First of all, tf.train.GradientDescentOptimizer is designed to use a constant learning rate for all variables in all steps. TensorFlow also provides out-of-the-box adaptive optimizers including the tf.train.AdagradOptimizer and the tf.train.AdamOptimizer, and these can be used as drop-in replacements.

However, if you want to control the learning rate with otherwise-vanilla gradient descent, you can take advantage of the fact that the learning_rate argument to the tf.train.GradientDescentOptimizer constructor can be a Tensor object. This allows you to compute a different value for the learning rate in each step, for example:

learning_rate = tf.placeholder(tf.float32, shape=[])
# ...
train_step = tf.train.GradientDescentOptimizer(
    learning_rate=learning_rate).minimize(mse)

sess = tf.Session()

# Feed different values for learning rate to each training step.
sess.run(train_step, feed_dict={learning_rate: 0.1})
sess.run(train_step, feed_dict={learning_rate: 0.1})
sess.run(train_step, feed_dict={learning_rate: 0.01})
sess.run(train_step, feed_dict={learning_rate: 0.01})

Alternatively, you could create a scalar tf.Variable that holds the learning rate, and assign it each time you want to change the learning rate.

Add more than one parameter in Twig path

You can pass as many arguments as you want, separating them by commas:

{{ path('_files_manage', {project: project.id, user: user.id}) }}

Total memory used by Python process?

On unix, you can use the ps tool to monitor it:

$ ps u -p 1347 | awk '{sum=sum+$6}; END {print sum/1024}'

where 1347 is some process id. Also, the result is in MB.

Laravel Eloquent limit and offset

Laravel 8 (This is worked for the version 7.16)

$art->products->skip($offset*$limit)->take($limit)->all();

https://laravel.com/docs/8.x/collections#method-take

How to select an element by classname using jqLite?

Essentially, and as-noted by @kevin-b:

// find('#id')
angular.element(document.querySelector('#id'))

//find('.classname'), assumes you already have the starting elem to search from
angular.element(elem.querySelector('.classname'))

Note: If you're looking to do this from your controllers you may want to have a look at the "Using Controllers Correctly" section in the developers guide and refactor your presentation logic into appropriate directives (such as <a2b ...>).

Insert into C# with SQLCommand

public class customer
{
    public void InsertCustomer(string name,int age,string address)
    {
        // create and open a connection object
        using(SqlConnection Con=DbConnection.GetDbConnection())
        {
            // 1. create a command object identifying the stored procedure
            SqlCommand cmd = new SqlCommand("spInsertCustomerData",Con);

            // 2. set the command object so it knows to execute a stored procedure
            cmd.CommandType = CommandType.StoredProcedure;

            SqlParameter paramName = new SqlParameter();
            paramName.ParameterName = "@nvcname";
            paramName.Value = name;
            cmd.Parameters.Add(paramName);

            SqlParameter paramAge = new SqlParameter();
            paramAge.ParameterName = "@inage";
            paramAge.Value = age;
            cmd.Parameters.Add(paramAge);

            SqlParameter paramAddress = new SqlParameter();
            paramAddress.ParameterName = "@nvcaddress";
            paramAddress.Value = address;
            cmd.Parameters.Add(paramAddress);

            cmd.ExecuteNonQuery();
        }
    }
}

Removing X-Powered-By

I think that is controlled by the expose_php setting in PHP.ini:

expose_php = off

Decides whether PHP may expose the fact that it is installed on the server (e.g. by adding its signature to the Web server header). It is no security threat in any way, but it makes it possible to determine whether you use PHP on your server or not.

There is no direct security risk, but as David C notes, exposing an outdated (and possibly vulnerable) version of PHP may be an invitation for people to try and attack it.

Import and insert sql.gz file into database with putty

For an oneliner, on linux or cygwin, you need to do public key authentication on the host, otherwise ssh will be asking for password.


gunzip -c numbers.sql.gz | ssh user@host mysql --user=user_name --password=your_password db_name

Or do port forwarding and connect to the remote mysql using a "local" connection:

ssh -L some_port:host:local_mysql_port user@host

then do the mysql connection on your local machine to localhost:some_port.

The port forwarding will work from putty too, with the similar -L option or you can configure it from the settings panel, somewhere down on the tree.

How do you push a tag to a remote repository using Git?

You can push all local tags by simply git push --tags command.

$ git tag                         # see tag lists
$ git push origin <tag-name>      # push a single tag
$ git push --tags                 # push all local tags 

How to access JSON decoded array in PHP

$data = json_decode(...);
$firstId = $data[0]["id"];
$secondSeatNo = $data[1]["seat_no"];

Just like this :)

Filtering Pandas Dataframe using OR statement

From the docs:

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing

Try:

alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]

Oracle ORA-12154: TNS: Could not resolve service name Error?

@Warren and @DCookie have covered the solution, one thing to emphasise is the use of tnsping. You can use this to prove your TNSNames is correct before attempting to connect.

Once you have set up tnsnames correctly you could use ODBC or try TOra which will use your native oracle connection. TOra or something similar (TOAD, SQL*Plus etc) will prove invaluable in debugging and improving your SQL.

Last but not least when you eventually connect with ASP.net remember that you can use the Oracle data connection libraries. See Oracle.com for a host of resources.

Is it worth using Python's re.compile?

According to the Python documentation:

The sequence

prog = re.compile(pattern)
result = prog.match(string)

is equivalent to

result = re.match(pattern, string)

but using re.compile() and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program.

So my conclusion is, if you are going to match the same pattern for many different texts, you better precompile it.

How to make div appear in front of another?

In order an element to appear in front of another you have to give higher z-index to the front element, and lower z-index to the back element, also you should indicate position: absolute/fixed...

Example:

<div style="z-index:100; position: fixed;">Hello</div>
<div style="z-index: -1;">World</div>

Open a URL without using a browser from a batch file

You can use the HH command to open any website.

hh <http://url>

For example,

hh http://shuvankar.com

Though it will not open the website in the browser, but this will open the website in an HTML help window.

Location for session files in Apache/PHP

Non of the above worked for me using the IUS repo for CentOS 7 with PHP 7.2:

php -v
> PHP 7.2.30 (cli) (built: Apr 19 2020 00:32:29) ( NTS )

php -r 'echo session_save_path(), "\n";
> 

php -r 'echo sys_get_temp_dir(), "\n";'
> /tmp

However, sessions weren't saved in the /tmp folder, but in the /var/lib/php/mod_php/session/ folder:

ls /var/lib/php/mod_php/session/
> sess_3cebqoq314pcnc2jgqiu840h0k  sess_ck5dtaerol28fpctj6nutbn6fn  sess_i24lgt2v2l58op5kfmj1k6qb3h  sess_nek5q1alop8fkt84gliie91703
> sess_9ff74f4q5ihccnv6com2a8409t  sess_dvrt9fmfuolr8bqt9efdpcbj0d  sess_igdaksn26hm1s5nfvtjfb53pl7  sess_tgf5b7gkgno8kuvl966l9ce7nn

Python: access class property from string

  • getattr(x, 'y') is equivalent to x.y
  • setattr(x, 'y', v) is equivalent to x.y = v
  • delattr(x, 'y') is equivalent to del x.y

How to style the <option> with only CSS?

I've played around with select items before and without overriding the functionality with JavaScript, I don't think it's possible in Chrome. Whether you use a plugin or write your own code, CSS only is a no go for Chrome/Safari and as you said, Firefox is better at dealing with it.

convert htaccess to nginx

Online tools to translate Apache .htaccess to Nginx rewrite tools include:

Note that these tools will convert to equivalent rewrite expressions using if statements, but they should be converted to try_files. See:

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

I liked Addison Klinke's post the most, as being the simplest, but used Wojciech Moszczynsk’s suggestion for filtering and charting, but extended the filter to avoid absolute values, so given a large correlation matrix, filter it, chart it, and then flatten it:

Created, Filtered and Charted

dfCorr = df.corr()
filteredDf = dfCorr[((dfCorr >= .5) | (dfCorr <= -.5)) & (dfCorr !=1.000)]
plt.figure(figsize=(30,10))
sn.heatmap(filteredDf, annot=True, cmap="Reds")
plt.show()

filtered heat map

Function

In the end, I created a small function to create the correlation matrix, filter it, and then flatten it. As an idea, it could easily be extended, e.g., asymmetric upper and lower bounds, etc.

def corrFilter(x: pd.DataFrame, bound: float):
    xCorr = x.corr()
    xFiltered = xCorr[((xCorr >= bound) | (xCorr <= -bound)) & (xCorr !=1.000)]
    xFlattened = xFiltered.unstack().sort_values().drop_duplicates()
    return xFlattened

corrFilter(df, .7)

enter image description here

How to uninstall an older PHP version from centOS7

Subscribing to the IUS Community Project Repository

cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:

sudo bash setup-ius.sh

Upgrading mod_php with Apache

This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.

Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.

sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.

sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:

sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:

systemctl status httpd

How to programmatically set the ForeColor of a label to its default?

For example summer :

lblSummer.foreColor = color.Yellow;

Parse (split) a string in C++ using string delimiter (standard C++)

Since this is the top-rated Stack Overflow Google search result for C++ split string or similar, I'll post a complete, copy/paste runnable example that shows both methods.

splitString uses stringstream (probably the better and easier option in most cases)

splitString2 uses find and substr (a more manual approach)

// SplitString.cpp

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

// function prototypes
std::vector<std::string> splitString(const std::string& str, char delim);
std::vector<std::string> splitString2(const std::string& str, char delim);
std::string getSubstring(const std::string& str, int leftIdx, int rightIdx);


int main(void)
{
  // Test cases - all will pass
  
  std::string str = "ab,cd,ef";
  //std::string str = "abcdef";
  //std::string str = "";
  //std::string str = ",cd,ef";
  //std::string str = "ab,cd,";   // behavior of splitString and splitString2 is different for this final case only, if this case matters to you choose which one you need as applicable
  
  
  std::vector<std::string> tokens = splitString(str, ',');
  
  std::cout << "tokens: " << "\n";
  
  if (tokens.empty())
  {
    std::cout << "(tokens is empty)" << "\n";
  }
  else
  {
    for (auto& token : tokens)
    {
      if (token == "") std::cout << "(empty string)" << "\n";
      else std::cout << token << "\n";
    }
  }
    
  return 0;
}

std::vector<std::string> splitString(const std::string& str, char delim)
{
  std::vector<std::string> tokens;
  
  if (str == "") return tokens;
  
  std::string currentToken;
  
  std::stringstream ss(str);
  
  while (std::getline(ss, currentToken, delim))
  {
    tokens.push_back(currentToken);
  }
  
  return tokens;
}

std::vector<std::string> splitString2(const std::string& str, char delim)
{
  std::vector<std::string> tokens;
  
  if (str == "") return tokens;
  
  int leftIdx = 0;
  
  int delimIdx = str.find(delim);
  
  int rightIdx;
  
  while (delimIdx != std::string::npos)
  {
    rightIdx = delimIdx - 1;
    
    std::string token = getSubstring(str, leftIdx, rightIdx);
    tokens.push_back(token);
    
    // prep for next time around
    leftIdx = delimIdx + 1;
    
    delimIdx = str.find(delim, delimIdx + 1);
  }
  
  rightIdx = str.size() - 1;
  
  std::string token = getSubstring(str, leftIdx, rightIdx);
  tokens.push_back(token);
  
  return tokens;
}

std::string getSubstring(const std::string& str, int leftIdx, int rightIdx)
{
  return str.substr(leftIdx, rightIdx - leftIdx + 1);
}

CSS - How to Style a Selected Radio Buttons Label?

_x000D_
_x000D_
.radio-toolbar input[type="radio"] {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.radio-toolbar label {_x000D_
  display: inline-block;_x000D_
  background-color: #ddd;_x000D_
  padding: 4px 11px;_x000D_
  font-family: Arial;_x000D_
  font-size: 16px;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.radio-toolbar input[type="radio"]:checked+label {_x000D_
  background-color: #bbb;_x000D_
}
_x000D_
<div class="radio-toolbar">_x000D_
  <input type="radio" id="radio1" name="radios" value="all" checked>_x000D_
  <label for="radio1">All</label>_x000D_
_x000D_
  <input type="radio" id="radio2" name="radios" value="false">_x000D_
  <label for="radio2">Open</label>_x000D_
_x000D_
  <input type="radio" id="radio3" name="radios" value="true">_x000D_
  <label for="radio3">Archived</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

First of all, you probably want to add the name attribute on the radio buttons. Otherwise, they are not part of the same group, and multiple radio buttons can be checked.

Also, since I placed the labels as siblings (of the radio buttons), I had to use the id and for attributes to associate them together.

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

It's because the tab is a naming container aswell... your update should be update="Search:insTable:display" What you can do aswell is just place your dialog outside the form and still inside the tab then it would be: update="Search:display"

How can I send and receive WebSocket messages on the server side?

Note: This is some explanation and pseudocode as to how to implement a very trivial server that can handle incoming and outcoming WebSocket messages as per the definitive framing format. It does not include the handshaking process. Furthermore, this answer has been made for educational purposes; it is not a full-featured implementation.

Specification (RFC 6455)


Sending messages

(In other words, server → browser)

The frames you're sending need to be formatted according to the WebSocket framing format. For sending messages, this format is as follows:

  • one byte which contains the type of data (and some additional info which is out of scope for a trivial server)
  • one byte which contains the length
  • either two or eight bytes if the length does not fit in the second byte (the second byte is then a code saying how many bytes are used for the length)
  • the actual (raw) data

The first byte will be 1000 0001 (or 129) for a text frame.

The second byte has its first bit set to 0 because we're not encoding the data (encoding from server to client is not mandatory).

It is necessary to determine the length of the raw data so as to send the length bytes correctly:

  • if 0 <= length <= 125, you don't need additional bytes
  • if 126 <= length <= 65535, you need two additional bytes and the second byte is 126
  • if length >= 65536, you need eight additional bytes, and the second byte is 127

The length has to be sliced into separate bytes, which means you'll need to bit-shift to the right (with an amount of eight bits), and then only retain the last eight bits by doing AND 1111 1111 (which is 255).

After the length byte(s) comes the raw data.

This leads to the following pseudocode:

bytesFormatted[0] = 129

indexStartRawData = -1 // it doesn't matter what value is
                       // set here - it will be set now:

if bytesRaw.length <= 125
    bytesFormatted[1] = bytesRaw.length

    indexStartRawData = 2

else if bytesRaw.length >= 126 and bytesRaw.length <= 65535
    bytesFormatted[1] = 126
    bytesFormatted[2] = ( bytesRaw.length >> 8 ) AND 255
    bytesFormatted[3] = ( bytesRaw.length      ) AND 255

    indexStartRawData = 4

else
    bytesFormatted[1] = 127
    bytesFormatted[2] = ( bytesRaw.length >> 56 ) AND 255
    bytesFormatted[3] = ( bytesRaw.length >> 48 ) AND 255
    bytesFormatted[4] = ( bytesRaw.length >> 40 ) AND 255
    bytesFormatted[5] = ( bytesRaw.length >> 32 ) AND 255
    bytesFormatted[6] = ( bytesRaw.length >> 24 ) AND 255
    bytesFormatted[7] = ( bytesRaw.length >> 16 ) AND 255
    bytesFormatted[8] = ( bytesRaw.length >>  8 ) AND 255
    bytesFormatted[9] = ( bytesRaw.length       ) AND 255

    indexStartRawData = 10

// put raw data at the correct index
bytesFormatted.put(bytesRaw, indexStartRawData)


// now send bytesFormatted (e.g. write it to the socket stream)

Receiving messages

(In other words, browser → server)

The frames you obtain are in the following format:

  • one byte which contains the type of data
  • one byte which contains the length
  • either two or eight additional bytes if the length did not fit in the second byte
  • four bytes which are the masks (= decoding keys)
  • the actual data

The first byte usually does not matter - if you're just sending text you are only using the text type. It will be 1000 0001 (or 129) in that case.

The second byte and the additional two or eight bytes need some parsing, because you need to know how many bytes are used for the length (you need to know where the real data starts). The length itself is usually not necessary since you have the data already.

The first bit of the second byte is always 1 which means the data is masked (= encoded). Messages from the client to the server are always masked. You need to remove that first bit by doing secondByte AND 0111 1111. There are two cases in which the resulting byte does not represent the length because it did not fit in the second byte:

  • a second byte of 0111 1110, or 126, means the following two bytes are used for the length
  • a second byte of 0111 1111, or 127, means the following eight bytes are used for the length

The four mask bytes are used for decoding the actual data that has been sent. The algorithm for decoding is as follows:

decodedByte = encodedByte XOR masks[encodedByteIndex MOD 4]

where encodedByte is the original byte in the data, encodedByteIndex is the index (offset) of the byte counting from the first byte of the real data, which has index 0. masks is an array containing of the four mask bytes.

This leads to the following pseudocode for decoding:

secondByte = bytes[1]

length = secondByte AND 127 // may not be the actual length in the two special cases

indexFirstMask = 2          // if not a special case

if length == 126            // if a special case, change indexFirstMask
    indexFirstMask = 4

else if length == 127       // ditto
    indexFirstMask = 10

masks = bytes.slice(indexFirstMask, 4) // four bytes starting from indexFirstMask

indexFirstDataByte = indexFirstMask + 4 // four bytes further

decoded = new array

decoded.length = bytes.length - indexFirstDataByte // length of real data

for i = indexFirstDataByte, j = 0; i < bytes.length; i++, j++
    decoded[j] = bytes[i] XOR masks[j MOD 4]


// now use "decoded" to interpret the received data

What is WebKit and how is it related to CSS?

A common problem I have ran into as a website designer is that alot of people use IE6+. No big deal usually, except in CSS I have to add multiple rendering syntax' to parse each request, per browser. It would be very nice if there was a universal rendering setup for CSS that IE can read as easily as Chrome/FF/Opera and webkit. The problem with IE is that if I do NOT use ALL the proper CSS styles and rendering, than my websites look and work great using every browser except IE. This can make for an unhappy, die-hard IE customer.

Example is this: Let us say I need a 1px, grey border with a border-radius of 10%. For Chrome and others, I use the webkit property. Now, for IE, I have to add seperate CSS styles using the simple old CSS values of "border: 1px solid #E5E5E5" and "border-radius: 10%". A positive outcome is not always guaranteed over all IE browser versions, but for the most part this method works fine for me and many others.

github changes not staged for commit

I was having the same problem. I ended up going into the subdirectory that was "not staged for commit" and adding, committing and pushing from there. after that, went up one level to master directory and was able to push correctly.

What is Parse/parsing?

From dictionary.reference.com:

Computers. to analyze (a string of characters) in order to associate groups of characters with the syntactic units of the underlying grammar.

The context of the definition is the translation of program text or a language in the general sense into its component parts with respect to a defined grammar -- turning program text into code. In the context of a particular language keyword, though, it generally means to convert the string value of a fundamental data type into an internal representation of that data type. For example, the string "10" becomes the number (integer) 10.

ReSharper "Cannot resolve symbol" even when project builds

Resharper -> Options Caches -> Store solution caches in: (Change folder to another one).

Or try to manually clean up R# cache folder

Remove Object from Array using JavaScript

There seems to be an error in your array syntax so assuming you mean an array as opposed to an object, Array.splice is your friend here:

someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
someArray.splice(1,1)

How do I exit the Vim editor?

Vim has three modes of operation: Input mode, Command mode & Ex mode.

Input mode - everything that you type, all keystrokes are echoed on the screen.

Command mode or Escape mode - everything that you type in this mode is interpreted as a command.

Ex mode - this is another editor, ex. It is a line editor. It works per line or based on a range of lines. In this mode, a : appears at the bottom of the screen. This is the ex editor.

In order to exit Vim, you can exit while you are in either the ex mode or in the command mode. You cannot exit Vim when you are in input mode.

Exiting from ex mode

  1. You need to be sure that you are in the Command mode. To do that, simply press the Esc key.

  2. Go to the ex mode by pressing the : key

  3. Use any of the following combinations in ex mode to exit:

    :q - quit :q! - quit without saving :wq - save & quit or write & quit :wq! - same as wq, but force write in case file permissions are readonly :x - write & quit :qa - quit all. useful when multiple files are opened like: vim abc.txt xyz.txt

Exiting from command mode

  1. Press the escape key. You probably have done this already if you are in command mode.

  2. Press capital ZZ (shift zz) - save & exit

  3. Press capital ZQ (shift zq) - exit without saving.

Jenkins Slave port number for firewall

I have a similar scenario, and had no problem connecting after setting the JNLP port as you describe, and adding a single firewall rule allowing a connection on the server using that port. Granted it is a randomly selected client port going to a known server port (a host:ANY -> server:1 rule is needed).

From my reading of the source code, I don't see a way to set the local port to use when making the request from the slave. It's unfortunate, it would be a nice feature to have.

Alternatives:

Use a simple proxy on your client that listens on port N and then does forward all data to the actual Jenkins server on the remote host using a constant local port. Connect your slave to this local proxy instead of the real Jenkins server.

Create a custom Jenkins slave build that allows an option to specify the local port to use.

Remember also if you are using HTTPS via a self-signed certificate, you must alter the configuration jenkins-slave.xml file on the slave to specify the -noCertificateCheck option on the command line.

Can a PDF file's print dialog be opened with Javascript?

I usually do something similar to the approach given by How to Use JavaScript to Print a PDF (eHow.com), using an iframe.

  1. a function to house the print trigger...

    function printTrigger(elementId) {
        var getMyFrame = document.getElementById(elementId);
        getMyFrame.focus();
        getMyFrame.contentWindow.print();
    }
    
  2. an button to give the user access...

    (an onClick on an a or button or input or whatever you wish)

    <input type="button" value="Print" onclick="printTrigger('iFramePdf');" />
    
  3. an iframe pointing to your PDF...

    <iframe id="iFramePdf" src="myPdfUrl.pdf" style="display:none;"></iframe>
    

Bonus Idea #1 - Create the iframe and add it to your page within the printTrigger(); so that the PDF isn't loaded until the user clicks your "Print" button, then the javascript can attack! the iframe and trigger the print dialog.


Bonus Idea #2 - Extra credit if you disable your "Print" button and give the user a little loading spinner or something after they click it, so that they know something's in process instead of clicking it repeatedly!

Postgresql query between date ranges

Just in case somebody land here... since 8.1 you can simply use:

SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN SYMMETRIC '2014-02-01' AND '2014-02-28'

From the docs:

BETWEEN SYMMETRIC is the same as BETWEEN except there is no requirement that the argument to the left of AND be less than or equal to the argument on the right. If it is not, those two arguments are automatically swapped, so that a nonempty range is always implied.

How can I check if a scrollbar is visible?

Ugh everyone's answers on here are incomplete, and lets stop using jquery in SO answers already please. Check jquery's documentation if you want info on jquery.

Here's a generalized pure-javascript function for testing whether or not an element has scrollbars in a complete way:

// dimension - Either 'y' or 'x'
// computedStyles - (Optional) Pass in the domNodes computed styles if you already have it (since I hear its somewhat expensive)
function hasScrollBars(domNode, dimension, computedStyles) {
    dimension = dimension.toUpperCase()
    if(dimension === 'Y') {
        var length = 'Height'
    } else {
        var length = 'Width'
    }

    var scrollLength = 'scroll'+length
    var clientLength = 'client'+length
    var overflowDimension = 'overflow'+dimension

    var hasVScroll = domNode[scrollLength] > domNode[clientLength]


    // Check the overflow and overflowY properties for "auto" and "visible" values
    var cStyle = computedStyles || getComputedStyle(domNode)
    return hasVScroll && (cStyle[overflowDimension] == "visible"
                         || cStyle[overflowDimension] == "auto"
                         )
          || cStyle[overflowDimension] == "scroll"
}