Programs & Examples On #Distributed apps

How can I use "." as the delimiter with String.split() in java

You might be interested in the StringTokenizer class. However, the java docs advise that you use the .split method as StringTokenizer is a legacy class.

Jenkins fails when running "service start jenkins"

I had below error:

Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.

Solution was to revert the NAME to jenkins in the below file (Earlier I have changed it to 'NAME=ubuntu'):

sudo vi /etc/default/jenkins
    NAME=jenkins

Now restart passed:

sudo service jenkins restart
sudo systemctl restart jenkins.service

Hope that helps.

Difference between Role and GrantedAuthority in Spring Security

Another way to understand the relationship between these concepts is to interpret a ROLE as a container of Authorities.

Authorities are fine-grained permissions targeting a specific action coupled sometimes with specific data scope or context. For instance, Read, Write, Manage, can represent various levels of permissions to a given scope of information.

Also, authorities are enforced deep in the processing flow of a request while ROLE are filtered by request filter way before reaching the Controller. Best practices prescribe implementing the authorities enforcement past the Controller in the business layer.

On the other hand, ROLES are coarse grained representation of an set of permissions. A ROLE_READER would only have Read or View authority while a ROLE_EDITOR would have both Read and Write. Roles are mainly used for a first screening at the outskirt of the request processing such as http. ... .antMatcher(...).hasRole(ROLE_MANAGER)

The Authorities being enforced deep in the request's process flow allows a finer grained application of the permission. For instance, a user may have Read Write permission to first level a resource but only Read to a sub-resource. Having a ROLE_READER would restrain his right to edit the first level resource as he needs the Write permission to edit this resource but a @PreAuthorize interceptor could block his tentative to edit the sub-resource.

Jake

Getting number of days in a month

 int days = DateTime.DaysInMonth(int year,int month);

or

 int days=System.Globalization.CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(int year,int month);

you have to pass year and month as int then days in month will be return on currespoting year and month

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

For .NET 2.0 you could implement a class which inherits from Dictionary and implements ICloneable.

public class CloneableDictionary<TKey, TValue> : Dictionary<TKey, TValue> where TValue : ICloneable
{
    public IDictionary<TKey, TValue> Clone()
    {
        CloneableDictionary<TKey, TValue> clone = new CloneableDictionary<TKey, TValue>();

        foreach (KeyValuePair<TKey, TValue> pair in this)
        {
            clone.Add(pair.Key, (TValue)pair.Value.Clone());
        }

        return clone;
    }
}

You can then clone the dictionary simply by calling the Clone method. Of course this implementation requires that the value type of the dictionary implements ICloneable, but otherwise a generic implementation isn't practical at all.

How can I remove an entry in global configuration with git config?

git config information will stored in ~/.gitconfig in unix platform.

In Windows it will be stored in C:/users/<NAME>/.gitconfig.

You can edit it manually by opening this files and deleting the fields which you are interested.

How to remove/ignore :hover css style on touch devices

This is also a possible workaround, but you will have to go through your css and add a .no-touch class before your hover styles.

Javascript:

if (!("ontouchstart" in document.documentElement)) {
document.documentElement.className += " no-touch";
}

CSS Example:

<style>
p span {
    display: none;
}

.no-touch p:hover span {
    display: inline;
}
</style>
<p><a href="/">Tap me</a><span>You tapped!</span></p>

Source

P.s. But we should remember, there are coming more and more touch-devices to the market, which are also supporting mouse input at the same time.

Connecting to smtp.gmail.com via command line

Check this post in lifehacker : Geek to Live: Back up Gmail with fetchmail . It uses a command line program. Check and see if it helps. BTW why are you using command line when there are many other nice alternatives?

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

This is my function for the clients timezone, it's lite weight and simple

  function getCurrentDateTimeMySql() {        
      var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
      var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, 19).replace('T', ' ');
      var mySqlDT = localISOTime;
      return mySqlDT;
  }

How can I flush GPU memory using CUDA (physical reset is unavailable)

One can also use nvtop, which gives an interface very similar to htop, but showing your GPU(s) usage instead, with a nice graph. You can also kill processes directly from here.

Here is a link to its Github : https://github.com/Syllo/nvtop

NVTOP interface

View google chrome's cached pictures

Modified version from @dovidev as his version loads the image externally instead of reading the local cache.

  1. Navigate to chrome://cache/
  2. In the chrome top menu go to "View > Developer > Javascript Console"
  3. In the console that opens paste the below and press enter

_x000D_
_x000D_
var cached_anchors = $$('a');_x000D_
document.body.innerHTML = '';_x000D_
for (var i in cached_anchors) {_x000D_
    var ca = cached_anchors[i];_x000D_
    if(ca.href.search('.png') > -1 || ca.href.search('.gif') > -1 || ca.href.search('.jpg') > -1) {_x000D_
        var xhr = new XMLHttpRequest();_x000D_
        xhr.open("GET", ca.href);_x000D_
        xhr.responseType = "document";_x000D_
        xhr.onload = response;_x000D_
        xhr.send();_x000D_
    }_x000D_
}_x000D_
_x000D_
function response(e) {_x000D_
  var hexdata = this.response.getElementsByTagName("pre")[2].innerHTML.split(/\r?\n/).slice(0,-1).map(e => e.split(/[\s:]+\s/)[1]).map(e => e.replace(/\s/g,'')).join('');_x000D_
  var byteArray = new Uint8Array(hexdata.length/2);_x000D_
  for (var x = 0; x < byteArray.length; x++){_x000D_
      byteArray[x] = parseInt(hexdata.substr(x*2,2), 16);_x000D_
  }_x000D_
  var blob = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
  var image = new Image();_x000D_
  image.src = URL.createObjectURL(blob);_x000D_
  document.body.appendChild(image);_x000D_
}
_x000D_
_x000D_
_x000D_

Check if PHP session has already started

For versions of PHP prior to PHP 5.4.0:

if(session_id() == '') {
    // session isn't started
}

Though, IMHO, you should really think about refactoring your session management code if you don't know whether or not a session is started...

That said, my opinion is subjective, and there are situations (examples of which are described in the comments below) where it may not be possible to know if the session is started.

How to keep a Python script output window open?

  1. Go here and download and install Notepad++
  2. Go here and download and install Python 2.7 not 3.
  3. Start, Run Powershell. Enter the following. [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
  4. Close Powershell and reopen it.
  5. Make a directory for your programs. mkdir scripts
  6. Open that directory cd scripts
  7. In Notepad++, in a new file type: print "hello world"
  8. Save the file as hello.py
  9. Go back to powershell and make sure you are in the right directory by typing dir. You should see your file hello.py there.
  10. At the Powershell prompt type: python hello.py

HTML5 best practices; section/header/aside/article elements

Actually, you are quite right when it comes to header/footer. Here is some basic information on how each of the major HTML5 tags can/should be used (I suggest reading the full source linked at the bottom):

section – Used for grouping together thematically-related content. Sounds like a div element, but it’s not. The div has no semantic meaning. Before replacing all your div’s with section elements, always ask yourself: “Is all of the content related?”

aside – Used for tangentially related content. Just because some content appears to the left or right of the main content isn’t enough reason to use the aside element. Ask yourself if the content within the aside can be removed without reducing the meaning of the main content. Pullquotes are an example of tangentially related content.

header – There is a crucial difference between the header element and the general accepted usage of header (or masthead). There’s usually only one header or ‘masthead’ in a page. In HTML5 you can have as many as you want. The spec defines it as “a group of introductory or navigational aids”. You can use a header in any section on your site. In fact, you probably should use a header within most of your sections. The spec describes the section element as “a thematic grouping of content, typically with a heading.”

nav – Intended for major navigation information. A group of links grouped together isn’t enough reason to use the nav element. Site-wide navigation, on the other hand belongs in a nav element.

footer – Sounds like its a description of the position, but its not. Footer elements contain informations about its containing element: who wrote it, copyright, links to related content, etc. Whereas we usually have one footer for an entire document, HTML5 allows us to also have footer within sections.

Source: https://clzd.me/html5-section-aside-header-nav-footer-elements-not-as-obvious-as-they-sound/

Additionally, here's a description on article, not found in the source above:

article – Used for element that specifies independent, self-contained content. An article should make sense on its own. Before replacing all your div’s with article elements, always ask yourself: “Is it possible to read it independently from the rest of the web site?”

What are OLTP and OLAP. What is the difference between them?

The difference is quite simple:

OLTP (Online Transaction Processing)

OLTP is a class of information systems that facilitate and manage transaction-oriented applications. OLTP has also been used to refer to processing in which the system responds immediately to user requests. Online transaction processing applications are high throughput and insert or update-intensive in database management. Some examples of OLTP systems include order entry, retail sales, and financial transaction systems.

OLAP (Online Analytical Processing)

OLAP is part of the broader category of business intelligence, which also encompasses relational database, report writing and data mining. Typical applications of OLAP include business reporting for sales, marketing, management reporting, business process management (BPM), budgeting and forecasting, financial reporting and similar areas.

See more details OLTP and OLAP

How do I load an HTML page in a <div> using JavaScript?

try

async function load_home(){
  content.innerHTML = await (await fetch('home.html')).text();
}

_x000D_
_x000D_
async function load_home() {_x000D_
  let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'_x000D_
_x000D_
  content.innerHTML = await (await fetch(url)).text();_x000D_
}
_x000D_
<div id="topBar"> <a href="#" onclick="load_home()"> HOME </a> </div>_x000D_
<div id="content"> </div>
_x000D_
_x000D_
_x000D_

How to add two edit text fields in an alert dialog

The API Demos in the Android SDK have an example that does just that.

It's under DIALOG_TEXT_ENTRY. They have a layout, inflate it with a LayoutInflater, and use that as the View.

EDIT: What I had linked to in my original answer is stale. Here is a mirror.

How to install maven on redhat linux

Installing maven in Amazon Linux / redhat

--> sudo wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo

--> sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo

-->sudo yum install -y apache-maven

--> mvn --version

Output looks like


Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z) Maven home: /usr/share/apache-maven Java version: 1.8.0_171, vendor: Oracle Corporation Java home: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.amzn2.x86_64/jre Default locale: en_US, platform encoding: UTF-8 OS name: "linux", version: "4.14.47-64.38.amzn2.x86_64", arch: "amd64", family: "unix"

*If its thrown error related to java please follow the below step to update java 8 *

Installing java 8 in amazon linux/redhat

--> yum search java | grep openjdk

--> yum install java-1.8.0-openjdk-headless.x86_64

--> yum install java-1.8.0-openjdk-devel.x86_64

--> update-alternatives --config java #pick java 1.8 and press 1

--> update-alternatives --config javac #pick java 1.8 and press 2

Thank You

#1071 - Specified key was too long; max key length is 1000 bytes

As @Devart says, the total length of your index is too long.

The short answer is that you shouldn't be indexing such long VARCHAR columns anyway, because the index will be very bulky and inefficient.

The best practice is to use prefix indexes so you're only indexing a left substring of the data. Most of your data will be a lot shorter than 255 characters anyway.

You can declare a prefix length per column as you define the index. For example:

...
KEY `index` (`parent_menu_id`,`menu_link`(50),`plugin`(50),`alias`(50))
...

But what's the best prefix length for a given column? Here's a method to find out:

SELECT
 ROUND(SUM(LENGTH(`menu_link`)<10)*100/COUNT(`menu_link`),2) AS pct_length_10,
 ROUND(SUM(LENGTH(`menu_link`)<20)*100/COUNT(`menu_link`),2) AS pct_length_20,
 ROUND(SUM(LENGTH(`menu_link`)<50)*100/COUNT(`menu_link`),2) AS pct_length_50,
 ROUND(SUM(LENGTH(`menu_link`)<100)*100/COUNT(`menu_link`),2) AS pct_length_100
FROM `pds_core_menu_items`;

It tells you the proportion of rows that have no more than a given string length in the menu_link column. You might see output like this:

+---------------+---------------+---------------+----------------+
| pct_length_10 | pct_length_20 | pct_length_50 | pct_length_100 |
+---------------+---------------+---------------+----------------+
|         21.78 |         80.20 |        100.00 |         100.00 |
+---------------+---------------+---------------+----------------+

This tells you that 80% of your strings are less than 20 characters, and all of your strings are less than 50 characters. So there's no need to index more than a prefix length of 50, and certainly no need to index the full length of 255 characters.

PS: The INT(1) and INT(32) data types indicates another misunderstanding about MySQL. The numeric argument has no effect related to storage or the range of values allowed for the column. INT is always 4 bytes, and it always allows values from -2147483648 to 2147483647. The numeric argument is about padding values during display, which has no effect unless you use the ZEROFILL option.

How to get table list in database, using MS SQL 2008?

This should give you a list of all the tables in your database

SELECT Distinct TABLE_NAME FROM information_schema.TABLES

So you can use it similar to your database check.

If NOT EXISTS(SELECT Distinct TABLE_NAME FROM information_schema.TABLES Where TABLE_NAME = 'Your_Table')
BEGIN
    --CREATE TABLE Your_Table
END
GO

How do I line up 3 divs on the same row?

here are two samples: http://jsfiddle.net/H5q5h/1/

one uses float:left and a wrapper with overflow:hidden. the wrapper ensures the sibling of the wrapper starts below the wrapper.

the 2nd one uses the more recent display:inline-block and wrapper can be disregarded. but this is not generally supported by older browsers so tread lightly on this one. also, any white space between the items will cause an unnecessary "margin-like" white space on the left and right of the item divs.

How to select all records from one table that do not exist in another table?

I don't have enough rep points to vote up froadie's answer. But I have to disagree with the comments on Kris's answer. The following answer:

SELECT name
FROM table2
WHERE name NOT IN
    (SELECT name 
     FROM table1)

Is FAR more efficient in practice. I don't know why, but I'm running it against 800k+ records and the difference is tremendous with the advantage given to the 2nd answer posted above. Just my $0.02.

C# DropDownList with a Dictionary as DataSource

Like that you can set DataTextField and DataValueField of DropDownList using "Key" and "Value" texts :

    Dictionary<string, string> list = new Dictionary<string, string>();
    list.Add("item 1", "Item 1");
    list.Add("item 2", "Item 2");
    list.Add("item 3", "Item 3");
    list.Add("item 4", "Item 4");

    ddl.DataSource = list;
    ddl.DataTextField = "Value";
    ddl.DataValueField = "Key";
    ddl.DataBind();

Selenium webdriver click google search

Simple Xpath for locating Google search box is: Xpath=//span[text()='Google Search']

Bootstrap fullscreen layout with 100% height

All you have to do is have a height of 100vh on your main container/wrapper, and then set height 100% or 50% for child elements.. depending on what you're trying to achieve. I tried to copy your mock up in a basic sense.

In case you want to center stuff within, look into flexbox. I put in an example for you.

You can view it on full screen, and resize the browser and see how it works. The layout stays the same.

_x000D_
_x000D_
.left {_x000D_
  background: grey;  _x000D_
}_x000D_
_x000D_
.right {_x000D_
  background: black;  _x000D_
}_x000D_
_x000D_
.main-wrapper {_x000D_
  height: 100vh;  _x000D_
}_x000D_
_x000D_
.section {_x000D_
  height: 100%;  _x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
.half {_x000D_
  background: #f9f9f9;_x000D_
  height: 50%;  _x000D_
  width: 100%;_x000D_
  margin: 15px 0;_x000D_
}_x000D_
_x000D_
h4 {_x000D_
  color: white;  _x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<div class="main-wrapper">_x000D_
  <div class="section left col-xs-3">_x000D_
    <div class="half"><h4>Top left</h4></div>_x000D_
    <div class="half"><h4>Bottom left</h4></div>_x000D_
  </div>_x000D_
  <div class="section right col-xs-9">_x000D_
    <h4>Extra step: center stuff here</h4>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

No module named setuptools

For python3 is:

sudo apt-get install -y python3-setuptools

Python Pandas - Find difference between two data frames

Using the lambda function you can filter the rows with _merge value “left_only” to get all the rows in df1 which are missing from df2

df3 = df1.merge(df2, how = 'outer' ,indicator=True).loc[lambda x :x['_merge']=='left_only']
df

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

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

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

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

Ick.

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

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

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

Laravel Password & Password_Confirmation Validation

I have used in this way. Its Working fine!

$rules = [

            'password' => [

                    'required',

                    'string',

                    'min:6',

                'max:12',             // must be at least 8 characters in length

                ],

            'confirm_password' => 'required|same:password|min:6'

        ];

Android turn On/Off WiFi HotSpot programmatically

We can programmatically turn on and off

setWifiApDisable.invoke(connectivityManager, TETHERING_WIFI);//Have to disable to enable
setwifiApEnabled.invoke(connectivityManager, TETHERING_WIFI, false, mSystemCallback,null);

Using callback class, to programmatically turn on hotspot in pie(9.0) u need to turn off programmatically and the switch on.

Hash table in JavaScript

If all you want to do is store some static values in a lookup table, you can use an Object Literal (the same format used by JSON) to do it compactly:

var table = { one: [1,10,5], two: [2], three: [3, 30, 300] }

And then access them using JavaScript's associative array syntax:

alert(table['one']);    // Will alert with [1,10,5]
alert(table['one'][1]); // Will alert with 10

'App not Installed' Error on Android

Primarily for older phones

I only encountered the App not installed error when trying to install an apk on my phone which runs on 4.4.2 aka KitKat, but my friend did not encounter this error on his phone which runs on 6+. I tried the other solutions such as removing the old/debug version of the app because the apk was a release version, clearing the debug app's data, and even clearing all of my cached data. Then, finally I realized all I had to do was select both signature versions when building my signed apk.

enter image description here

Before I only had V2 (Full APK Signature) selected, but after selecting V1 Jar Signature as well, I was able to successfully install my signed APK on my 4.4.2 device. Hope this helps others!

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

How to fill a Javascript object literal with many static key/value pairs efficiently?

JavaScript's object literal syntax, which is typically used to instantiate objects (seriously, no one uses new Object or new Array), is as follows:

var obj = {
    'key': 'value',
    'another key': 'another value',
     anUnquotedKey: 'more value!'
};

For arrays it's:

var arr = [
    'value',
    'another value',
    'even more values'
];

If you need objects within objects, that's fine too:

var obj = {
    'subObject': {
        'key': 'value'
    },
    'another object': {
         'some key': 'some value',
         'another key': 'another value',
         'an array': [ 'this', 'is', 'ok', 'as', 'well' ]
    }
}

This convenient method of being able to instantiate static data is what led to the JSON data format.

JSON is a little more picky, keys must be enclosed in double-quotes, as well as string values:

{"foo":"bar", "keyWithIntegerValue":123}

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

Create a .bashrc file under ~/.bashrc and away you go. Similarly for ~/.gitconfig.

~ is usually your C:\Users\<your user name> folder. Typing echo ~ in the Git Bash terminal will tell you what that folder is.

If you can't create the file (e.g. running Windows), run the below command:

copy > ~/.bashrc

The window will output an error message (command not found), but the file will be created and ready for you to edit.

How to parse a month name (string) to an integer for comparison in C#?

If you use the DateTime.ParseExact()-method that several people have suggested, you should carefully consider what you want to happen when the application runs in a non-English environment!

In Denmark, which of ParseExact("Januar", ...) and ParseExact("January", ...) should work and which should fail?

That will be the difference between CultureInfo.CurrentCulture and CultureInfo.InvariantCulture.

Delete all rows with timestamp older than x days

DELETE FROM on_search 
WHERE search_date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 180 DAY))

HRESULT: 0x800A03EC on Worksheet.range

I've come across it several different times and every time it was always some error with either duplicating a tab name or in this current case it just occurred because I simply had a typo in the get_Range where I tried to get a Cell by number and number instead of the letter and number.
Drove me crazy because the error pointed me to a few lines down but I had commented out all of the creation of the other sheets above the "error line" and the ones in the line and below were created with no issue.
Happened to scan up a few lines above and saw that I put 6 + lastword, C + lastrow in my get_Range statement and of course you can't have a cell starting with a number it's always letter than number.

SQL Server Restore Error - Access is Denied

Sorry because I cannot comment...

I had the same problem. In my case the problem was related to trying to restore in an old sql server folder (that existed on the server). This is due to old sql server backup (i.e. SQL Server 2012 Backup) restored in a new sql server (SQL Server 2014). The real issue is not too different from @marc_s answer. Anyway, I changed only the target folder to the new SQL Server DATA folder.

Create a custom event in Java

The following is not exactly the same but similar, I was searching for a snippet to add a call to the interface method, but found this question, so I decided to add this snippet for those who were searching for it like me and found this question:

 public class MyClass
 {
        //... class code goes here

        public interface DataLoadFinishedListener {
            public void onDataLoadFinishedListener(int data_type);
        }

        private DataLoadFinishedListener m_lDataLoadFinished;

        public void setDataLoadFinishedListener(DataLoadFinishedListener dlf){
            this.m_lDataLoadFinished = dlf;
        }



        private void someOtherMethodOfMyClass()
        {
            m_lDataLoadFinished.onDataLoadFinishedListener(1);
        }    
    }

Usage is as follows:

myClassObj.setDataLoadFinishedListener(new MyClass.DataLoadFinishedListener() {
            @Override
            public void onDataLoadFinishedListener(int data_type) {
                }
            });

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

if you have number of columns in your database table more than number of columns in your csv you can proceed like this:

LOAD DATA LOCAL INFILE 'pathOfFile.csv'
INTO TABLE youTable 
CHARACTER SET latin1 FIELDS TERMINATED BY ';' #you can use ',' if you have comma separated
OPTIONALLY ENCLOSED BY '"' 
ESCAPED BY '\\' 
LINES TERMINATED BY '\r\n'
(yourcolumn,yourcolumn2,yourcolumn3,yourcolumn4,...);

How can I do string interpolation in JavaScript?

Word of caution: avoid any template system which does't allow you to escape its own delimiters. For example, There would be no way to output the following using the supplant() method mentioned here.

"I am 3 years old thanks to my {age} variable."

Simple interpolation may work for small self-contained scripts, but often comes with this design flaw that will limit any serious use. I honestly prefer DOM templates, such as:

<div> I am <span id="age"></span> years old!</div>

And use jQuery manipulation: $('#age').text(3)

Alternately, if you are simply just tired of string concatenation, there's always alternate syntax:

var age = 3;
var str = ["I'm only", age, "years old"].join(" ");

Convert String to equivalent Enum value

Hope you realise, java.util.Enumeration is different from the Java 1.5 Enum types.

You can simply use YourEnum.valueOf("String") to get the equivalent enum type.

Thus if your enum is defined as so:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY
}

You could do this:

String day = "SUNDAY";

Day dayEnum = Day.valueOf(day);

mysql-python install error: Cannot open include file 'config-win.h'

Assume you want to install package MySQL-python on Windows, maybe try pip install command with --global-option. See the example command below:

pip install MySQL-python ^
 --force-reinstall --no-cache-dir ^
 --global-option=build_ext ^
 --global-option="-IC:\my\install\MySQL-x64\MySQL Connector C 6.0.2\include" ^
 --global-option="-LC:\my\install\MySQL-x64\MySQL Connector C 6.0.2\lib\opt" ^
 --verbose

For this example, I fully installed 64-bit version of MySQL Connector C in customized location of C:\my\install\MySQL-x64\MySQL Connector C 6.0.2\.

By the way, I noticed that pip install MySQL-python by default always looks into directory C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include, even if you're using 64-bit and/or have installed the driver at a different location. I tested on Python-2.7, and I guess this is a bug of either Python or MySQL-python.

Hope the above might be of some help.

Display two fields side by side in a Bootstrap Form

The problem is that .form-control class renders like a DIV element which according to the normal-flow-of-the-page renders on a new line.

One way of fixing issues like this is to use display:inline property. So, create a custom CSS class with display:inline and attach it to your component with a .form-control class. You have to have a width for your component as well.

There are other ways of handling this issue (like arranging your form-control components inside any of the .col classes), but the easiest way is to just make your .form-control an inline element (the way a span would render)

E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation

In your Dockerfile, run this first:

apt-get update && apt-get install -y gnupg2

Node.js - use of module.exports as a constructor

In my opinion, some of the node.js examples are quite contrived.

You might expect to see something more like this in the real world

// square.js
function Square(width) {

  if (!(this instanceof Square)) {
    return new Square(width);
  }

  this.width = width;
};

Square.prototype.area = function area() {
  return Math.pow(this.width, 2);
};

module.exports = Square;

Usage

var Square = require("./square");

// you can use `new` keyword
var s = new Square(5);
s.area(); // 25

// or you can skip it!
var s2 = Square(10);
s2.area(); // 100

For the ES6 people

class Square {
  constructor(width) {
    this.width = width;
  }
  area() {
    return Math.pow(this.width, 2);
  }
}

export default Square;

Using it in ES6

import Square from "./square";
// ...

When using a class, you must use the new keyword to instatiate it. Everything else stays the same.

How to detect the device orientation using CSS media queries?

In Javascript it is better to use screen.width and screen.height. These two values are available in all modern browsers. They give the real dimensions of the screen, even if the browser has been scaled down when the app fires up. window.innerWidth changes when the browser is scaled down, which can't happen on mobile devices but can happen on PCs and laptops.

The values of screen.width and screen.height change when the mobile device flips between portrait and landscape modes, so it is possible to determine the mode by comparing the values. If screen.width is greater than 1280px you're dealing with a PC or laptop.

You can construct an event listener in Javascript to detect when the two values are flipped. The portrait screen.width values to concentrate on are 320px (mainly iPhones), 360px (most other phones), 768px (small tablets) and 800px (regular tablets).

Android "elevation" not showing a shadow

set background color to the layout or view

How do I get a list of folders and sub folders without the files?

I used dir /s /b /o:n /a:d, and it worked perfectly, just make sure you let the file finish writing, or you'll have an incomplete list.

How do you make a div follow as you scroll?

Using styling from CSS, you can define how something is positioned. If you define the element as fixed, it will always remain in the same position on the screen at all times.

div
{
    position:fixed;
    top:20px;
}

How to save traceback / sys.exc_info() values in a variable?

The object can be used as a parameter in Exception.with_traceback() function:

except Exception as e:
    tb = sys.exc_info()
    print(e.with_traceback(tb[2]))

setting y-axis limit in matplotlib

You can instantiate an object from matplotlib.pyplot.axes and call the set_ylim() on it. It would be something like this:

import matplotlib.pyplot as plt
axes = plt.axes()
axes.set_ylim([0, 1])

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

Download it from here:

http://www.iis.net/downloads/microsoft/url-rewrite

or if you already have Web Platform Installer on your machine you can install it from there.

Parsing query strings on Android

Since Android M things have got more complicated. The answer of android.net.URI.getQueryParameter() has a bug which breaks spaces before JellyBean. Apache URLEncodedUtils.parse() worked, but was deprecated in L, and removed in M.

So the best answer now is UrlQuerySanitizer. This has existed since API level 1 and still exists. It also makes you think about the tricky issues like how do you handle special characters, or repeated values.

The simplest code is

UrlQuerySanitizer.ValueSanitizer sanitizer = UrlQuerySanitizer.getAllButNullLegal();
// remember to decide if you want the first or last parameter with the same name
// If you want the first call setPreferFirstRepeatedParameter(true);
sanitizer.parseUrl(url);
String value = sanitizer.getValue("paramName");

If you are happy with the default parsing behavior you can do:

new UrlQuerySanitizer(url).getValue("paramName")

but you should make sure you understand what the default parsing behavor is, as it might not be what you want.

Is there a naming convention for MySQL?

Consistency is what everyone strongly suggest, the rest is upto you as long as it works.

For beginners its easy to get carried away and we name whatever we want at that time. This make sense at that point but a headache later.

foo foobar or foo_bar is great. We name our table straight forward as much as possible and only use underscore if they are two different words. studentregistration to student_registration

like @Zbyszek says, having a simple id is more than enough for the auto-increment. The simplier the better. Why do you need foo_id? We had the same problem early on, we named all our columns with the table prefix. like foo_id, foo_name, foo_age. We dropped the tablename now and kept only the col as short as possible.

Since we are using just an id for PK we will be using foo_bar_fk (tablename is unique, folowed by the unique PK, followed by the _fk) as foreign key. We don't add id to the col name because it is said that the name 'id' is always the PK of the given table. So we have just the tablename and the _fk at the end.

For constrains we remove all underscores and join with camelCase (tablename + Colname + Fk) foobarUsernameFk (for username_fk col). It's just a way we are following. We keep a documentation for every names structures.

When keeping the col name short, we should also keep an eye on the RESTRICTED names.

+------------------------------------+
|               foobar               |
+------------------------------------+
| id (PK for the current table)      |
| username_fk (PK of username table) |
| location (other column)            |
| tel (other column)                 |
+------------------------------------+

Replace single quotes in SQL Server

select replace ( colname, '''', '') AS colname FROM .[dbo].[Db Name]

Programmatically getting the MAC of an Android device

You can no longer get the hardware MAC address of a android device. WifiInfo.getMacAddress() and BluetoothAdapter.getAddress() methods will return 02:00:00:00:00:00. This restriction was introduced in Android 6.0.

But Rob Anderson found a solution which is working for < Marshmallow : https://stackoverflow.com/a/35830358

How do I sort a list of datetime or date objects?

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

Cannot GET / Nodejs Error

Much like leonardocsouza, I had the same problem. To clarify a bit, this is what my folder structure looked like when I ran node server.js

node_modules/
app/
  index.html
  server.js

After printing out the __dirname path, I realized that the __dirname path was where my server was running (app/).

So, the answer to your question is this:

If your server.js file is in the same folder as the files you are trying to render, then

app.use( express.static( path.join( application_root, 'site') ) );

should actually be

app.use(express.static(application_root));

The only time you would want to use the original syntax that you had would be if you had a folder tree like so:

app/
  index.html
node_modules
server.js

where index.html is in the app/ directory, whereas server.js is in the root directory (i.e. the same level as the app/ directory).

Side note: Intead of calling the path utility, you can use the syntax application_root + 'site' to join a path.

Overall, your code could look like:

// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
mongoose = require( 'mongoose' ); //MongoDB integration

//Create server
var app = express();

// Configure server
app.configure( function() {

    //Don't change anything here...

    //Where to serve static content
    app.use( express.static( application_root ) );

    //Nothing changes here either...
});

//Start server --- No changes made here
var port = 5000;
app.listen( port, function() {
    console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});

Concatenate multiple node values in xpath

I used concat method and works well.

concat(//SomeElement/text(),'_',//OtherElement/text())

Concrete Javascript Regex for Accented Characters (Diacritics)

What about this?

^([a-zA-Z]|[à-ú]|[À-Ú])+$

It will match every word with accented characters or not.

.htaccess: where is located when not in www base dir

The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.

Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.

Limit number of characters allowed in form input text field

maxlength:

The maximum number of characters that will be accepted as input. This can be greater that specified by SIZE , in which case the field will scroll appropriately. The default is unlimited.

<input type="text" maxlength="2" id="sessionNo" name="sessionNum" onkeypress="return isNumberKey(event)" />

However, this may or may not be affected by your handler. You may need to use or add another handler function to test for length, as well.

How do I write a Windows batch script to copy the newest file from a directory?

To allow this to work with filenames using spaces, a modified version of the accepted answer is needed:

FOR /F "delims=" %%I IN ('DIR . /B /O:-D') DO COPY "%%I" <<NewDir>> & GOTO :END
:END

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had a similar problem.

As it turned out, I ran mvn clean package install.

Correct way is mvn clean install

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

I got the same error and I changed my version from 4 to 3 and it is solved:

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <!-- Ensure correct version of MVC -->
    <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
    </dependentAssembly>
</assemblyBinding>

Prevent direct access to a php include file

Storing your include files outside the web accessible directory has been mentioned a few times, and is certainly a good strategy where possible. However, another option I have not yet seen mentioned: ensure that your include files don’t contain any runnable code. If your include files merely define functions and classes, and have no code other than that, they will simply produce a blank page when accessed directly.

By all means allow direct access to this file from the browser: it won’t do anything. It defines some functions, but none of them are called, so none of them run.

<?php

function a() {
    // function body
}

function b() {
    // function body
}

The same applies to files which contain only PHP classes, and nothing else.


It’s still a good idea to keep your files outside of the web directory where possible.

  • You might accidentally deactivate PHP, in which case your server may send content of the PHP files to the browser, instead of running PHP and sending the result. This could result in your code (including database passwords, API keys, etc.) leaking.
  • Files in the web directory are squatting on URLs you may want to use for your app. I work with a CMS which cannot have a page called system, because that would conflict with a path used for code. I find this annoying.

AndroidStudio gradle proxy

The following works for me . File -> Settings -> Appearance & Behavior -> System Settings -> HTTP Proxy Put in your proxy setting in Manual proxy configuration

Restart android studio, a prompt pops up and asks you to add the proxy setting to gradle, click yes.

Using HTML5 file uploads with AJAX and jQuery

It's not too hard. Firstly, take a look at FileReader Interface.

So, when the form is submitted, catch the submission process and

var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...


function shipOff(event) {
    var result = event.target.result;
    var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
    $.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}

Then, on the server side (i.e. myscript.php):

$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);

Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg in /uploads/ on your server, and respond with a JSON variable (to a continueSubmission() function) containing the fileName on the server.

Check out fwrite() and jQuery.post().

On the above page it details how to use readAsBinaryString(), readAsDataUrl(), and readAsArrayBuffer() for your other needs (e.g. images, videos, etc).

Resize font-size according to div size

The answer that i am presenting is very simple, instead of using "px","em" or "%", i'll use "vw". In short it might look like this:- h1 {font-size: 5.9vw;} when used for heading purposes.

See this:Demo

For more details:Main tutorial

How to handle windows file upload using Selenium WebDriver?

Double the backslashes in the path, like this:

driver.findElement(browsebutton).sendKeys("C:\\Users\\Desktop\\Training\\Training.jpg");

How to pass the values from one jsp page to another jsp without submit button?

I am trying to Understand your Question and it seems that you want the values in the first JSP to be available in the Second JSP.

  1. It is very bad Habit to Place Java Code snippets Inside JSP file, so that code snippet should go to a servlet.

  2. Pick the values in a servlet ie.

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    
  3. Then Store the Values inside the Session:

    HttpSession sess = request.getSession(); 
    sess.setAttribute("username", username);
    sess.setAttribute("password", password);
    
  4. These values Will be available anywhere in the Application as long as the session is valid.

    HttpSession sess = request.getSession(false); //use false to use the existing session
    sess.getAttribute("username");//this will return username anytime in the session
    sess.getAttribute("password");//this will return password Any time in the session
    

I hope this is what you wanted to know, but please do not use code snippets in the JSP. You can always get the values into the JSP using jstl in the JSPs:

 ${username}//this will give you the username in the JSP
 ${password}// this will give you the password in the JSP

How do I remove blue "selected" outline on buttons?

You can remove the blue outline by using outline: none.

However, I would highly recommend styling your focus states too. This is to help users who are visually impaired.

Check out: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#navigation-mechanisms-focus-visible. More reading here: http://outlinenone.com

How to crop an image in OpenCV using Python

i had this question and found another answer here: copy region of interest

If we consider (0,0) as top left corner of image called im with left-to-right as x direction and top-to-bottom as y direction. and we have (x1,y1) as the top-left vertex and (x2,y2) as the bottom-right vertex of a rectangle region within that image, then:

roi = im[y1:y2, x1:x2]

here is a comprehensive resource on numpy array indexing and slicing which can tell you more about things like cropping a part of an image. images would be stored as a numpy array in opencv2.

:)

How to align checkboxes and their labels consistently cross-browsers

Warning! This answer is too old and doesn't work on modern browsers.

I'm not the poster of this answer, but at the time of writing this, this is the most voted answer by far in both positive and negative votes (+1035 -17), and it's still marked as accepted answer (probably because the original poster of the question is the one who wrote this answer).

As already noted many times in the comments, this answer does not work on most browsers anymore (and seems to be failing to do that since 2013).


After over an hour of tweaking, testing, and trying different styles of markup, I think I may have a decent solution. The requirements for this particular project were:

  1. Inputs must be on their own line.
  2. Checkbox inputs need to align vertically with the label text similarly (if not identically) across all browsers.
  3. If the label text wraps, it needs to be indented (so no wrapping down underneath the checkbox).

Before I get into any explanation, I'll just give you the code:

_x000D_
_x000D_
label {
  display: block;
  padding-left: 15px;
  text-indent: -15px;
}
input {
  width: 13px;
  height: 13px;
  padding: 0;
  margin:0;
  vertical-align: bottom;
  position: relative;
  top: -1px;
  *overflow: hidden;
}
_x000D_
<form>
  <div>
    <label><input type="checkbox" /> Label text</label>
  </div>
</form>
_x000D_
_x000D_
_x000D_

Here is the working example in JSFiddle.

This code assumes that you're using a reset like Eric Meyer's that doesn't override form input margins and padding (hence putting margin and padding resets in the input CSS). Obviously in a live environment you'll probably be nesting/overriding stuff to support other input elements, but I wanted to keep things simple.

Things to note:

  • The *overflow declaration is an inline IE hack (the star-property hack). Both IE 6 and 7 will notice it, but Safari and Firefox will properly ignore it. I think it might be valid CSS, but you're still better off with conditional comments; just used it for simplicity.
  • As best I can tell, the only vertical-align statement that was consistent across browsers was vertical-align: bottom. Setting this and then relatively positioning upwards behaved almost identically in Safari, Firefox and IE with only a pixel or two of discrepancy.
  • The major problem in working with alignment is that IE sticks a bunch of mysterious space around input elements. It isn't padding or margin, and it's damned persistent. Setting a width and height on the checkbox and then overflow: hidden for some reason cuts off the extra space and allows IE's positioning to act very similarly to Safari and Firefox.
  • Depending on your text sizing, you'll no doubt need to adjust the relative positioning, width, height, and so forth to get things looking right.

Hope this helps someone else! I haven't tried this specific technique on any projects other than the one I was working on this morning, so definitely pipe up if you find something that works more consistently.


Warning! This answer is too old and doesn't work on modern browsers.

Replace String in all files in Eclipse

If you want to replace two lines of code with one line, then this does not work. It works in notepad++. I end up open all files in notepad++ and replaced all.

Python assigning multiple variables to same value? list behavior

The code that does what I need could be this:

# test

aux=[[0 for n in range(3)] for i in range(4)]
print('aux:',aux)

# initialization

a,b,c,d=[[0 for n in range(3)] for i in range(4)]

# changing values

a[0]=1
d[2]=5
print('a:',a)
print('b:',b)
print('c:',c)
print('d:',d)

Result:

('aux:', [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]])
('a:', [1, 0, 0])
('b:', [0, 0, 0])
('c:', [0, 0, 0])
('d:', [0, 0, 5])

How to embed new Youtube's live video permanent URL?

The embed URL for a channel's live stream is:

https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID

You can find your CHANNEL_ID at https://www.youtube.com/account_advanced

Dynamic SQL results into temp table in SQL Stored procedure

Be careful of a global temp table solution as this may fail if two users use the same routine at the same time as a global temp table can be seen by all users...

scp (secure copy) to ec2 instance without password

lets assume that your pem file and somefile.txt you want to send is in Downloads folder

scp -i ~/Downloads/mykey.pem ~/Downloads/somefile.txt [email protected]:~/

let me know if it doesn't work

How to set a parameter in a HttpServletRequest?

Sorry, but why not use the following construction:

request.getParameterMap().put(parameterName, new String[] {parameterValue});

Access Controller method from another controller in Laravel 5

//In Controller A
public static function function1(){

}

In Controller B, View or anywhere
A::function1();

How do I get the current username in .NET using C#?

Use System.Windows.Forms.SystemInformation.UserName for the actually logged in user as Environment.UserName still returns the account being used by the current process.

How do I set up Android Studio to work completely offline?

Just as an assist if you go with Android Studio 0.4.x offline mode (because this thread is one of the main ones that google throws up when querying this issue).

From Alex Ruiz (Google+):

If you specify dependency versions using "+" (e.g. 0.8.+) Gradle (not Android Studio) will check that you have the latest version of such dependency periodically (every 24 hours,) even in offline mode

You need to take the plus out.

Retrieving parameters from a URL

Python 2:

import urlparse
url = 'http://foo.appspot.com/abc?def=ghi'
parsed = urlparse.urlparse(url)
print urlparse.parse_qs(parsed.query)['def']

Python 3:

import urllib.parse as urlparse
from urllib.parse import parse_qs
url = 'http://foo.appspot.com/abc?def=ghi'
parsed = urlparse.urlparse(url)
print(parse_qs(parsed.query)['def'])

parse_qs returns a list of values, so the above code will print ['ghi'].

Here's the Python 3 documentation.

Associating existing Eclipse project with existing SVN repository

Try this- Close the project then open it. It links with svn automatically,if project was checked out from valid svn path.

Split string into array of character strings

An efficient way of turning a String into an array of one-character Strings would be to do this:

String[] res = new String[str.length()];
for (int i = 0; i < str.length(); i++) {
    res[i] = Character.toString(str.charAt(i));
}

However, this does not take account of the fact that a char in a String could actually represent half of a Unicode code-point. (If the code-point is not in the BMP.) To deal with that you need to iterate through the code points ... which is more complicated.

This approach will be faster than using String.split(/* clever regex*/), and it will probably be faster than using Java 8+ streams. It is probable faster than this:

String[] res = new String[str.length()];
int 0 = 0;
for (char ch: str.toCharArray[]) {
    res[i++] = Character.toString(ch);
}  

because toCharArray has to copy the characters to a new array.

How can I remove all text after a character in bash?

In Bash (and ksh, zsh, dash, etc.), you can use parameter expansion with % which will remove characters from the end of the string or # which will remove characters from the beginning of the string. If you use a single one of those characters, the smallest matching string will be removed. If you double the character, the longest will be removed.

$ a='hello:world'

$ b=${a%:*}
$ echo "$b"
hello

$ a='hello:world:of:tomorrow'

$ echo "${a%:*}"
hello:world:of

$ echo "${a%%:*}"
hello

$ echo "${a#*:}"
world:of:tomorrow

$ echo "${a##*:}"
tomorrow

Coerce multiple columns to factors at once

The more recent tidyverse way is to use the mutate_at function:

library(tidyverse)
library(magrittr)
set.seed(88)

data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))
cols <- c("A", "C", "D", "H")

data %<>% mutate_at(cols, funs(factor(.)))
str(data)
 $ A: Factor w/ 4 levels "5","17","18",..: 2 1 4 3   
 $ B: int  36 35 2 26
 $ C: Factor w/ 4 levels "22","31","32",..: 1 2 4 3
 $ D: Factor w/ 4 levels "1","9","16","39": 3 4 1 2
 $ E: int  3 14 30 38
 $ F: int  27 15 28 37
 $ G: int  19 11 6 21
 $ H: Factor w/ 4 levels "7","12","20",..: 1 3 4 2
 $ I: int  23 24 13 8
 $ J: int  10 25 4 33

Fatal error: Call to undefined function: ldap_connect()

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

    extension=php_ldap.dll

  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin Restart Apache. You can now use functions of the LDAP Module!

How do I execute .js files locally in my browser?

Around 1:51 in the video, notice how she puts a <script> tag in there? The way it works is like this:

Create an html file (that's just a text file with a .html ending) somewhere on your computer. In the same folder that you put index.html, put a javascript file (that's just a textfile with a .js ending - let's call it game.js). Then, in your index.html file, put some html that includes the script tag with game.js, like Mary did in the video. index.html should look something like this:

<html>
    <head>
        <script src="game.js"></script>
    </head>
</html>

Now, double click on that file in finder, and it should open it up in your browser. To open up the console to see the output of your javascript code, hit Command-alt-j (those three buttons at the same time).

Good luck on your journey, hope it's as fun for you as it has been for me so far :)

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

No @XmlRootElement generated by JAXB

JAXBElement wrappers works for cases where no @XmlRootElement is generated by JAXB. These wrappers are available in ObjectFactory class generated by maven-jaxb2-plugin. For eg:

     public class HelloWorldEndpoint {
        @PayloadRoot(namespace = NAMESPACE_URI, localPart = "person")
        @ResponsePayload
        public JAXBElement<Greeting> sayHello(@RequestPayload JAXBElement<Person> request) {

        Person person = request.getValue();

        String greeting = "Hello " + person.getFirstName() + " " + person.getLastName() + "!";

        Greeting greet = new Greeting();
        greet.setGreeting(greeting);

        ObjectFactory factory = new ObjectFactory();
        JAXBElement<Greeting> response = factory.createGreeting(greet);
        return response;
      }
 }

How to merge two sorted arrays into a sorted array?

public static int[] mergeSorted(int[] left, int[] right) {
    System.out.println("merging " + Arrays.toString(left) + " and " + Arrays.toString(right));
    int[] merged = new int[left.length + right.length];
    int nextIndexLeft = 0;
    int nextIndexRight = 0;
    for (int i = 0; i < merged.length; i++) {
        if (nextIndexLeft >= left.length) {
            System.arraycopy(right, nextIndexRight, merged, i, right.length - nextIndexRight);
            break;
        }
        if (nextIndexRight >= right.length) {
            System.arraycopy(left, nextIndexLeft, merged, i, left.length - nextIndexLeft);
            break;
        }
        if (left[nextIndexLeft] <= right[nextIndexRight]) {
            merged[i] = left[nextIndexLeft];
            nextIndexLeft++;
            continue;
        }
        if (left[nextIndexLeft] > right[nextIndexRight]) {
            merged[i] = right[nextIndexRight];
            nextIndexRight++;
            continue;
        }
    }
    System.out.println("merged : " + Arrays.toString(merged));
    return merged;
}

Just a small different from the original solution

Looping over elements in jQuery

jQuery has an excellent function for looping through a set of elements: .each()

$('#formId').children().each(
    function(){
        //access to form element via $(this)
    }
);

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

This is still the top post when searching, but it's no longer valid. Best answer is here, but the TLDR is

<c-b>:resize-window -A

Dynamic tabs with user-click chosen components

I'm not cool enough for comments. I fixed the plunker from the accepted answer to work for rc2. Nothing fancy, links to the CDN were just broken is all.

'@angular/core': {
  main: 'bundles/core.umd.js',
  defaultExtension: 'js'
},
'@angular/compiler': {
  main: 'bundles/compiler.umd.js',
  defaultExtension: 'js'
},
'@angular/common': {
  main: 'bundles/common.umd.js',
  defaultExtension: 'js'
},
'@angular/platform-browser-dynamic': {
  main: 'bundles/platform-browser-dynamic.umd.js',
  defaultExtension: 'js'
},
'@angular/platform-browser': {
  main: 'bundles/platform-browser.umd.js',
  defaultExtension: 'js'
},

https://plnkr.co/edit/kVJvI1vkzrLZJeRFsZuv?p=preview

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

Turns out all I needed to do was wrap the left-hand side of the expression in soft brackets:

<span class="gallery-date">{{(gallery.date | date:'mediumDate') || "Various"}}</span>

How to try convert a string to a Guid

new Guid(string)

You could also look at using a TypeConverter.

What is the LDF file in SQL Server?

The LDF file holds the database transaction log. See, for example, http://www.databasedesign-resource.com/sql-server-transaction-log.html for a full explanation. There are ways to shrink the transaction file; for example, see http://support.microsoft.com/kb/873235.

how to set default method argument values?

Hopefully I am not misunderstanding this document, but if your using Java 1.8, in theory, you could accomplish something like this by defining a working implementation of a default method ("defender methods") within an interface that you implement.

interface DoInterface {
    void doNothing();
    public default void remove() {
       throw new UnsupportedOperationException("remove");
    }
    public default int doSomething( int arg1, int arg2) {
        val = arg1 + arg2 * arg1;
        log( "Value is: " + val );
        return val;
    }
}
class DoIt extends DoInterface {
    DoIt() {
        log("Called DoIt constructor.");
    }
    public int doSomething() {
        int val = doSomething( 0, 100 );
        return val;
    }
}

Then, call it either way:

DoIt d = new DoIt();
d.doSomething();
d.soSomething( 5, 45 );

Powershell 2 copy-item which creates a folder if doesn't exist

  $filelist | % {
    $file = $_
    mkdir -force (Split-Path $dest) | Out-Null
    cp $file $dest
  } 

How to put two divs on the same line with CSS in simple_form in rails?

why not use flexbox ? so wrap them into another div like that

_x000D_
_x000D_
.flexContainer { _x000D_
   _x000D_
  margin: 2px 10px;_x000D_
  display: flex;_x000D_
} _x000D_
_x000D_
.left {_x000D_
  flex-basis : 30%;_x000D_
}_x000D_
_x000D_
.right {_x000D_
  flex-basis : 30%;_x000D_
}
_x000D_
<form id="new_production" class="simple_form new_production" novalidate="novalidate" method="post" action="/projects/1/productions" accept-charset="UTF-8">_x000D_
    <div style="margin:0;padding:0;display:inline">_x000D_
        <input type="hidden" value="?" name="utf8">_x000D_
        <input type="hidden" value="2UQCUU+tKiKKtEiDtLLNeDrfBDoHTUmz5Sl9+JRVjALat3hFM=" name="authenticity_token">_x000D_
    </div>_x000D_
    <div class="flexContainer">_x000D_
      <div class="left">Proj Name:</div>_x000D_
      <div class="right">must have a name</div>_x000D_
    </div>_x000D_
    <div class="input string required"> </div>_x000D_
 </form>
_x000D_
_x000D_
_x000D_

feel free to play with flex-basis percentage to get more customized space.

How can I map True/False to 1/0 in a Pandas DataFrame?

A succinct way to convert a single column of boolean values to a column of integers 1 or 0:

df["somecolumn"] = df["somecolumn"].astype(int)

Android: Expand/collapse animation

Use ValueAnimator:

ValueAnimator expandAnimation = ValueAnimator.ofInt(mainView.getHeight(), 400);
expandAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(final ValueAnimator animation) {
        int height = (Integer) animation.getAnimatedValue();
        RelativeLayout.LayoutParams lp = (LayoutParams) mainView.getLayoutParams();
        lp.height = height;
    }
});


expandAnimation.setDuration(500);
expandAnimation.start();

Elasticsearch: Failed to connect to localhost port 9200 - Connection refused

I had the same problem refusing connections on 9200 port. Check elasticsearch service status with the command sudo service elasticsearch status. If it is presenting an error and you read anything related to Java, probably the problem is your jvm memory. You can edit it in /etc/elasticsearch/jvm.options. For a 1GB RAM memory machine on Amazon environment, I kept my configuration on:

-Xms128m
-Xmx128m

After setting that and restarting elasticsearch service, it worked like a charm. Nmap and UFW (if you use local firewall) checking should also be useful.

Getting View's coordinates relative to the root layout

No need to calculate it manually.

Just use getGlobalVisibleRect like so:

Rect myViewRect = new Rect();
myView.getGlobalVisibleRect(myViewRect);
float x = myViewRect.left;
float y = myViewRect.top;

Also note that for the centre coordinates, rather than something like:

...
float two = (float) 2
float cx = myViewRect.left + myView.getWidth() / two;
float cy = myViewRect.top + myView.getHeight() / two;

You can just do:

float cx = myViewRect.exactCenterX();
float cy = myViewRect.exactCenterY();

How do you see recent SVN log entries?

This answer is directed at further questions regarding Subversion subcommands options. For every available subcommand (i.e. add, log, status ...), you can simply add the --help option to display the complete list of available options you can use with your subcommand as well as examples on how to use them. The following snippet is taken directly from the svn log --help command output under the "examples" section :

Show the latest 5 log messages for the current working copy
directory and display paths changed in each commit:
  svn log -l 5 -v

UILabel is not auto-shrinking text to fit label size

Swift 4, Xcode 9.4.1

The solution that worked for me: I had a label within a collection view cell, and the label text was getting trimmed. Set the attributes as below on Storyboard

Lines = 0
LineBreak = Word Wrap
Set yourlabel's leading and trailing constraint = 0 (using Autolayout)

How does a ArrayList's contains() method evaluate objects?

Just wanted to note that the following implementation is wrong when value is not a primitive type:

public class Thing
{
    public Object value;  

    public Thing (Object x)
    {
        this.value = x;
    }

    @Override
    public boolean equals(Object object)
    {
        boolean sameSame = false;

        if (object != null && object instanceof Thing)
        {
            sameSame = this.value == ((Thing) object).value;
        }

        return sameSame;
    }
}

In that case I propose the following:

public class Thing {
    public Object value;  

    public Thing (Object x) {
        value = x;
    }

    @Override
    public boolean equals(Object object) {

        if (object != null && object instanceof Thing) {
            Thing thing = (Thing) object;
            if (value == null) {
                return (thing.value == null);
            }
            else {
                return value.equals(thing.value);
            }
        }

        return false;
    }
}

Fast and simple String encrypt/decrypt in JAVA

Simplest way is to add this JAVA library using Gradle:

compile 'se.simbio.encryption:library:2.0.0'

You can use it as simple as this:

Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
String encrypted = encryption.encryptOrNull("top secret string");
String decrypted = encryption.decryptOrNull(encrypted);

ASP.NET Core Web API Authentication

You can implement a middleware which handles Basic authentication.

public async Task Invoke(HttpContext context)
{
    var authHeader = context.Request.Headers.Get("Authorization");
    if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
    {
        var token = authHeader.Substring("Basic ".Length).Trim();
        System.Console.WriteLine(token);
        var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
        var credentials = credentialstring.Split(':');
        if(credentials[0] == "admin" && credentials[1] == "admin")
        {
            var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
            var identity = new ClaimsIdentity(claims, "Basic");
            context.User = new ClaimsPrincipal(identity);
        }
    }
    else
    {
        context.Response.StatusCode = 401;
        context.Response.Headers.Set("WWW-Authenticate", "Basic realm=\"dotnetthoughts.net\"");
    }
    await _next(context);
}

This code is written in a beta version of asp.net core. Hope it helps.

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

The Gantt charts given by Hifzan and Raja are for FCFS algorithms.

With an SJF algorithm, processes can be interrupted. That is, every process doesn't necessarily execute straight through their given burst time.

P3|P2|P4|P3|P5|P1|P5

1|2|3|5|7|8|11|14

P3 arrives at 1ms, then is interrupted by P2 and P4 since they both have smaller burst times, and then P3 resumes. P5 starts executing next, then is interrupted by P1 since P1's burst time is smaller than P5's. You must note the arrival times and be careful. These problems can be trickier than how they appear at-first-glance.

EDIT: This applies only to Preemptive SJF algorithms. A plain SJF algorithm is non-preemptive, meaning it does not interrupt a process.

How to change line width in IntelliJ (from 120 character)

IntelliJ IDEA 2018

File > Settings... > Editor > Code Style > Hard wrap at

Code Style > Hard wrap at

IntelliJ IDEA 2016 & 2017

File > Settings... > Editor > Code Style > Right margin (columns):

File > Settings

Editor > Code Style > Right margin

Regular expression to return text between parenthesis

Use re.search(r'\((.*?)\)',s).group(1):

>>> import re
>>> s = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
>>> re.search(r'\((.*?)\)',s).group(1)
u"date='2/xc2/xb2',time='/case/test.png'"

Cannot read property 'map' of undefined

First of all, set more safe initial data:

getInitialState : function() {
    return {data: {comments:[]}};
},

And ensure your ajax data.

It should work if you follow above two instructions like Demo.

Updated: you can just wrap the .map block with conditional statement.

if (this.props.data) {
  var commentNodes = this.props.data.map(function (comment){
      return (
        <div>
          <h1>{comment.author}</h1>
        </div>
      );
  });
}

add a temporary column with a value

select field1, field2, 'example' as TempField
from table1

This should work across different SQL implementations.

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

The mutable can be handy when you are overriding a const virtual function and want to modify your child class member variable in that function. In most of the cases you would not want to alter the interface of the base class, so you have to use mutable member variable of your own.

How to access the elements of a function's return array?

In order to get the values of each variable, you need to treat the function as you would an array:

function data() {
    $a = "abc";
    $b = "def";
    $c = "ghi";
    return array($a, $b, $c);
}

// Assign a variable to the array; 
// I selected $dataArray (could be any name).

$dataArray = data();
list($a, $b, $c) = $dataArray;
echo $a . " ". $b . " " . $c;

//if you just need 1 variable out of 3;
list(, $b, ) = $dataArray;
echo $b;

How to remove title bar from the android activity?

Add this two line in your style.xml

<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>

How to restrict user to type 10 digit numbers in input element?

You can use maxlength to limit the length. Normally for numeric input you'd use type="number", however this adds a spinny box thing to scroll through numbers, which is completely useless for phone numbers. You can, however, use the pattern attribute to limit input to numbers (and require 10 numbers too, if you want):

<input type="text" maxlength="10" pattern="\d{10}" title="Please enter exactly 10 digits" />

JavaScript moving element in the DOM

var swap = function () {
    var divs = document.getElementsByTagName('div');
    var div1 = divs[0];
    var div2 = divs[1];
    var div3 = divs[2];

    div3.parentNode.insertBefore(div1, div3);
    div1.parentNode.insertBefore(div3, div2);
};

This function may seem strange, but it heavily relies on standards in order to function properly. In fact, it may seem to function better than the jQuery version that tvanfosson posted which seems to do the swap only twice.

What standards peculiarities does it rely on?

insertBefore Inserts the node newChild before the existing child node refChild. If refChild is null, insert newChild at the end of the list of children. If newChild is a DocumentFragment object, all of its children are inserted, in the same order, before refChild. If the newChild is already in the tree, it is first removed.

How do I prevent and/or handle a StackOverflowException?

With .NET 4.0 You can add the HandleProcessCorruptedStateExceptions attribute from System.Runtime.ExceptionServices to the method containing the try/catch block. This really worked! Maybe not recommended but works.

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.ExceptionServices;

namespace ExceptionCatching
{
    public class Test
    {
        public void StackOverflow()
        {
            StackOverflow();
        }

        public void CustomException()
        {
            throw new Exception();
        }

        public unsafe void AccessViolation()
        {
            byte b = *(byte*)(8762765876);
        }
    }

    class Program
    {
        [HandleProcessCorruptedStateExceptions]
        static void Main(string[] args)
        {
            Test test = new Test();
            try {
                //test.StackOverflow();
                test.AccessViolation();
                //test.CustomException();
            }
            catch
            {
                Console.WriteLine("Caught.");
            }

            Console.WriteLine("End of program");

        }

    }      
}

Debugging with Android Studio stuck at "Waiting For Debugger" forever

It has happened to me that it stayed stuck in "Waiting for Debugger" when accidentally I tried to Debug a Release build, sometimes it warns that it is not a debug build and others it silently stucks in "Waiting for Debugger".

The solution is obviously to switch to Debug build

HTML5 Canvas: Zooming

Building on the suggestion of using drawImage you could also combine this with scale function.

So before you draw the image scale the context to the zoom level you want:

ctx.scale(2, 2) // Doubles size of anything draw to canvas.

I've created a small example here http://jsfiddle.net/mBzVR/4/ that uses drawImage and scale to zoom in on mousedown and out on mouseup.

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

If you're having this problem with Spring Boot 1.4.x and up, you might be able to use @OverrideAutoConfiguration(enabled=true) to solve the problem.

Similar to what was asked/answered here https://stackoverflow.com/a/39253304/1410035

How do I split a string with multiple separators in JavaScript?

Another simple but effective method is to use split + join repeatedly.

"a=b,c:d".split('=').join(',').split(':').join(',').split(',')

Essentially doing a split followed by a join is like a global replace so this replaces each separator with a comma then once all are replaced it does a final split on comma

The result of the above expression is:

['a', 'b', 'c', 'd']

Expanding on this you could also place it in a function:

function splitMulti(str, tokens){
        var tempChar = tokens[0]; // We can use the first token as a temporary join character
        for(var i = 1; i < tokens.length; i++){
            str = str.split(tokens[i]).join(tempChar);
        }
        str = str.split(tempChar);
        return str;
}

Usage:

splitMulti('a=b,c:d', ['=', ',', ':']) // ["a", "b", "c", "d"]

If you use this functionality a lot it might even be worth considering wrapping String.prototype.split for convenience (I think my function is fairly safe - the only consideration is the additional overhead of the conditionals (minor) and the fact that it lacks an implementation of the limit argument if an array is passed).

Be sure to include the splitMulti function if using this approach to the below simply wraps it :). Also worth noting that some people frown on extending built-ins (as many people do it wrong and conflicts can occur) so if in doubt speak to someone more senior before using this or ask on SO :)

    var splitOrig = String.prototype.split; // Maintain a reference to inbuilt fn
    String.prototype.split = function (){
        if(arguments[0].length > 0){
            if(Object.prototype.toString.call(arguments[0]) == "[object Array]" ) { // Check if our separator is an array
                return splitMulti(this, arguments[0]);  // Call splitMulti
            }
        }
        return splitOrig.apply(this, arguments); // Call original split maintaining context
    };

Usage:

var a = "a=b,c:d";
    a.split(['=', ',', ':']); // ["a", "b", "c", "d"]

// Test to check that the built-in split still works (although our wrapper wouldn't work if it didn't as it depends on it :P)
        a.split('='); // ["a", "b,c:d"] 

Enjoy!

git - Server host key not cached

I solved similar problem using this workaround.

You just have to switch to Embedded Git, push, press Yes button and then switch back to System Git.

You can find this option in

Tools -> Options -> Git

How to limit the number of selected checkboxes?

I have Alter this function to auto uncheck previous

_x000D_
_x000D_
      var limit = 3;_x000D_
      $('.compare_items').on('click', function(evt) {_x000D_
        index = $(this).parent('td').parent('tr').index();_x000D_
        if ($('.compare_items:checked').length >= limit) {_x000D_
          $('.compare_items').eq(localStorage.getItem('last-checked-item')).removeAttr('checked');_x000D_
          //this.checked = false;_x000D_
        }_x000D_
        localStorage.setItem('last-checked-item', index);_x000D_
      });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="checkbox" class="compare_items">1_x000D_
<input type="checkbox" class="compare_items">2_x000D_
<input type="checkbox" class="compare_items">3_x000D_
<input type="checkbox" class="compare_items">4_x000D_
<input type="checkbox" class="compare_items">5_x000D_
<input type="checkbox" class="compare_items">6_x000D_
<input type="checkbox" class="compare_items">7_x000D_
<input type="checkbox" class="compare_items">8_x000D_
<input type="checkbox" class="compare_items">9_x000D_
<input type="checkbox" class="compare_items">10
_x000D_
_x000D_
_x000D_

how to make div click-able?

Give it an ID like "something", then:

var something = document.getElementById('something');

something.style.cursor = 'pointer';
something.onclick = function() {
    // do something...
};

Changing the background color (as per your updated question):

something.onmouseover = function() {
    this.style.backgroundColor = 'red';
};
something.onmouseout = function() {
    this.style.backgroundColor = '';
};

What is the usefulness of PUT and DELETE HTTP request methods?

DELETE is for deleting the request resource:

The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully …

PUT is for putting or updating a resource on the server:

The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI …

For the full specification visit:

Since current browsers unfortunately do not support any other verbs than POST and GET in HTML forms, you usually cannot utilize HTTP to it's full extent with them (you can still hijack their submission via JavaScript though). The absence of support for these methods in HTML forms led to URIs containing verbs, like for instance

POST http://example.com/order/1/delete

or even worse

POST http://example.com/deleteOrder/id/1

effectively tunneling CRUD semantics over HTTP. But verbs were never meant to be part of the URI. Instead HTTP already provides the mechanism and semantics to CRUD a Resource (e.g. an order) through the HTTP methods. HTTP is a protocol and not just some data tunneling service.

So to delete a Resource on the webserver, you'd call

DELETE http://example.com/order/1

and to update it you'd call

PUT http://example.com/order/1

and provide the updated Resource Representation in the PUT body for the webserver to apply then.

So, if you are building some sort of client for a REST API, you will likely make it send PUT and DELETE requests. This could be a client built inside a browser, e.g. sending requests via JavaScript or it could be some tool running on a server, etc.

For some more details visit:

Mobile website "WhatsApp" button to send message to a specific number

This answer is useful to them who want click to chat whatsapp in website to redirect web.whatsapp.com with default content or message and in mobile device to open in whatsapp in mobile app with default content to text bar in app.

also add jquery link.

<a  target="_blank" title="Contact Us On WhatsApp" href="https://web.whatsapp.com/send?phone=+91xxxxxxxxx&amp;text=Hi, I would like to get more information.." class="whatsapplink hidemobile" style="background-color:#2DC100">
<i class="fa fa-fw fa-whatsapp" style="color:#fff"></i>
<span style="color:#fff">
    Contact Us On WhatsApp        </span>
</a>
<a  target="_blank" title="Contact Us On WhatsApp" href="https://api.whatsapp.com/send?phone=+91xxxxxxxxx&text=Hi,%20I%20would%20like%20to%20get%20more%20information.." class="whatsapplink hideweb" style="background-color:#2DC100">
<i class="fa fa-fw fa-whatsapp" style="color:#fff"></i>
<span style="color:#fff">
    Contact Us On WhatsApp        </span>
</a>

<script type="text/javascript"> 
var mobile = (/iphone|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));  
if (mobile) { 

$('.hidemobile').css('display', 'none'); // OR you can use $('.hidemobile').hide();
} 
else 
{ 
$('.hideweb').css('display', 'none'); // OR you can use $('.hideweb').hide();
}
</script>

Android: How can I validate EditText input?

Why don't you use TextWatcher ?

Since you have a number of EditText boxes to be validated, I think the following shall suit you :

  1. Your activity implements android.text.TextWatcher interface
  2. You add TextChanged listeners to you EditText boxes
txt1.addTextChangedListener(this);
txt2.addTextChangedListener(this);
txt3.addTextChangedListener(this);
  1. Of the overridden methods, you could use the afterTextChanged(Editable s) method as follows
@Override
public void afterTextChanged(Editable s) {
    // validation code goes here
}

The Editable s doesn't really help to find which EditText box's text is being changed. But you could directly check the contents of the EditText boxes like

String txt1String = txt1.getText().toString();
// Validate txt1String

in the same method. I hope I'm clear and if I am, it helps! :)

EDIT: For a cleaner approach refer to Christopher Perry's answer below.

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

df = df.replace({np.nan: None})

Credit goes to this guy here on this Github issue.

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

In HTML, elements containing nothing but normal whitespace characters are considered empty. A paragraph that contains just a normal space character will have zero height. A non-breaking space is a special kind of whitespace character that isn't considered to be insignificant, so it can be used as content for a non-empty paragraph.

Even if you consider CSS margins on paragraphs, since an "empty" paragraph has zero height, its vertical margins will collapse. This causes it to have no height and no margins, making it appear as if it were never there at all.

How to read an external local JSON file in JavaScript?

Since you have a web application, you may have a client and a server.

If you have only your browser, and you want to read a local file from a javascript that is running in your browser, that means that you have only a client. For security reasons, the browser should not let you do such thing.

However, as lauhub explained above, this seems to work:

http://www.html5rocks.com/en/tutorials/file/dndfiles/

Other solution is to setup somewhere in your machine a web server (tiny in windows or monkey in linux) and with an XMLHttpRequest or D3 library, request the file from the server and read it. The server will fetch the file from the local filesystem, and serve it to you through the web.

How can I enable Assembly binding logging?

Instead of Creating New Application Pool,You can go to your Existing application Pool->Right click Advance setting->Enable 32-bit Application-----Set to TRUE

SQL Server SELECT INTO @variable?

You cannot SELECT .. INTO .. a TABLE VARIABLE. The best you can do is create it first, then insert into it. Your 2nd snippet has to be

DECLARE @TempCustomer TABLE
(
   CustomerId uniqueidentifier,
   FirstName nvarchar(100),
   LastName nvarchar(100),
   Email nvarchar(100)
);
INSERT INTO 
    @TempCustomer 
SELECT 
    CustomerId, 
    FirstName, 
    LastName, 
    Email 
FROM 
    Customer
WHERE 
    CustomerId = @CustomerId

Why won't my PHP app send a 404 error?

A little bit shorter version. Suppress odd echo.

if (strstr($_SERVER['REQUEST_URI'],'index.php')){
  header('HTTP/1.0 404 Not Found');
  exit("<h1>404 Not Found</h1>\nThe page that you have requested could not be found.");
}

How do I install the ext-curl extension with PHP 7?

Well I was able to install it by :

sudo apt-get install php-curl

on my system. This will install a dependency package, which depends on the default php version.

After that restart apache

sudo service apache2 restart

Jersey Exception : SEVERE: A message body reader for Java class

Some may be confused why add jersey-json jar can't solve this problem. I found out that this jar has to newer than jersey-json-1.7.jar( 1.7.0 doesn't work, but 1.7.1 works fine.). hope this can help

How to fix corrupt HDFS FIles

You can use

  hdfs fsck /

to determine which files are having problems. Look through the output for missing or corrupt blocks (ignore under-replicated blocks for now). This command is really verbose especially on a large HDFS filesystem so I normally get down to the meaningful output with

  hdfs fsck / | egrep -v '^\.+$' | grep -v eplica

which ignores lines with nothing but dots and lines talking about replication.

Once you find a file that is corrupt

  hdfs fsck /path/to/corrupt/file -locations -blocks -files

Use that output to determine where blocks might live. If the file is larger than your block size it might have multiple blocks.

You can use the reported block numbers to go around to the datanodes and the namenode logs searching for the machine or machines on which the blocks lived. Try looking for filesystem errors on those machines. Missing mount points, datanode not running, file system reformatted/reprovisioned. If you can find a problem in that way and bring the block back online that file will be healthy again.

Lather rinse and repeat until all files are healthy or you exhaust all alternatives looking for the blocks.

Once you determine what happened and you cannot recover any more blocks, just use the

  hdfs fs -rm /path/to/file/with/permanently/missing/blocks

command to get your HDFS filesystem back to healthy so you can start tracking new errors as they occur.

How to animate the change of image in an UIImageView?

Code:

var fadeAnim:CABasicAnimation = CABasicAnimation(keyPath: "contents");

fadeAnim.fromValue = firstImage;
fadeAnim.toValue   = secondImage;
fadeAnim.duration  = 0.8;         //smoothest value

imageView.layer.addAnimation(fadeAnim, forKey: "contents");

imageView.image = secondImage;

Example:

UIImageView Example from code

Fun, More Verbose Solution: (Toggling on a tap)

    let fadeAnim:CABasicAnimation = CABasicAnimation(keyPath: "contents");

    switch imageView.image {
        case firstImage?:
            fadeAnim.fromValue = firstImage;
            fadeAnim.toValue   = secondImage;
            imageView.image    = secondImage;
        default:
            fadeAnim.fromValue = secondImage;
            fadeAnim.toValue   = firstImage;
            imageView.image    = firstImage;
    }

    fadeAnim.duration = 0.8;

    imageView.layer.addAnimation(fadeAnim, forKey: "contents");

List<T> or IList<T>

If you are exposing your class through a library that others will use, you generally want to expose it via interfaces rather than concrete implementations. This will help if you decide to change the implementation of your class later to use a different concrete class. In that case the users of your library won't need to update their code since the interface doesn't change.

If you are just using it internally, you may not care so much, and using List<T> may be ok.

Convert datetime value into string

Use DATE_FORMAT()

SELECT
  DATE_FORMAT(NOW(), '%d %m %Y') AS your_date;

How to disable all div content

function disableItems(divSelector){
    var disableInputs = $(divSelector).find(":input").not("[disabled]");
    disableInputs.attr("data-reenable", true);
    disableInputs.attr("disabled", true);
}

function reEnableItems(divSelector){
    var reenableInputs = $(divSelector).find("[data-reenable]");
    reenableInputs.removeAttr("disabled");
    reenableInputs.removeAttr("data-reenable");
}

Function pointer to member function

Building on @IllidanS4 's answer, I have created a template class that allows virtually any member function with predefined arguments and class instance to be passed by reference for later calling.



template<class RET, class... RArgs> class Callback_t {
public:
    virtual RET call(RArgs&&... rargs) = 0;
    //virtual RET call() = 0;
};

template<class T, class RET, class... RArgs> class CallbackCalltimeArgs : public Callback_t<RET, RArgs...> {
public:
    T * owner;
    RET(T::*x)(RArgs...);
    RET call(RArgs&&... rargs) {
        return (*owner.*(x))(std::forward<RArgs>(rargs)...);
    };
    CallbackCalltimeArgs(T* t, RET(T::*x)(RArgs...)) : owner(t), x(x) {}
};

template<class T, class RET, class... Args> class CallbackCreattimeArgs : public Callback_t<RET> {
public:
    T* owner;
    RET(T::*x)(Args...);
    RET call() {
        return (*owner.*(x))(std::get<Args&&>(args)...);
    };
    std::tuple<Args&&...> args;
    CallbackCreattimeArgs(T* t, RET(T::*x)(Args...), Args&&... args) : owner(t), x(x),
        args(std::tuple<Args&&...>(std::forward<Args>(args)...)) {}
};

Test / example:

class container {
public:
    static void printFrom(container* c) { c->print(); };
    container(int data) : data(data) {};
    ~container() {};
    void print() { printf("%d\n", data); };
    void printTo(FILE* f) { fprintf(f, "%d\n", data); };
    void printWith(int arg) { printf("%d:%d\n", data, arg); };
private:
    int data;
};

int main() {
    container c1(1), c2(20);
    CallbackCreattimeArgs<container, void> f1(&c1, &container::print);
    Callback_t<void>* fp1 = &f1;
    fp1->call();//1
    CallbackCreattimeArgs<container, void, FILE*> f2(&c2, &container::printTo, stdout);
    Callback_t<void>* fp2 = &f2;
    fp2->call();//20
    CallbackCalltimeArgs<container, void, int> f3(&c2, &container::printWith);
    Callback_t<void, int>* fp3 = &f3;
    fp3->call(15);//20:15
}

Obviously, this will only work if the given arguments and owner class are still valid. As far as readability... please forgive me.

Edit: removed unnecessary malloc by making the tuple normal storage. Added inherited type for the reference. Added option to provide all arguments at calltime instead. Now working on having both....

Edit 2: As promised, both. Only restriction (that I see) is that the predefined arguments must come before the runtime supplied arguments in the callback function. Thanks to @Chipster for some help with gcc compliance. This works on gcc on ubuntu and visual studio on windows.

#ifdef _WIN32
#define wintypename typename
#else
#define wintypename
#endif

template<class RET, class... RArgs> class Callback_t {
public:
    virtual RET call(RArgs... rargs) = 0;
    virtual ~Callback_t() = default;
};

template<class RET, class... RArgs> class CallbackFactory {
private:
    template<class T, class... CArgs> class Callback : public Callback_t<RET, RArgs...> {
    private:
        T * owner;
        RET(T::*x)(CArgs..., RArgs...);
        std::tuple<CArgs...> cargs;
        RET call(RArgs... rargs) {
            return (*owner.*(x))(std::get<CArgs>(cargs)..., rargs...);
        };
    public:
        Callback(T* t, RET(T::*x)(CArgs..., RArgs...), CArgs... pda);
        ~Callback() {};
    };
public:
    template<class U, class... CArgs> static Callback_t<RET, RArgs...>* make(U* owner, CArgs... cargs, RET(U::*func)(CArgs..., RArgs...));
};
template<class RET2, class... RArgs2> template<class T2, class... CArgs2> CallbackFactory<RET2, RArgs2...>::Callback<T2, CArgs2...>::Callback(T2* t, RET2(T2::*x)(CArgs2..., RArgs2...), CArgs2... pda) : x(x), owner(t), cargs(std::forward<CArgs2>(pda)...) {}
template<class RET, class... RArgs> template<class U, class... CArgs> Callback_t<RET, RArgs...>* CallbackFactory<RET, RArgs...>::make(U* owner, CArgs... cargs, RET(U::*func)(CArgs..., RArgs...)) {
    return new wintypename CallbackFactory<RET, RArgs...>::Callback<U, CArgs...>(owner, func, std::forward<CArgs>(cargs)...);
}

Onclick javascript to make browser go back to previous page?

the only one that worked for me:

function goBackAndRefresh() {
  window.history.go(-1);
  setTimeout(() => {
    location.reload();
  }, 0);
}

TypeScript and array reduce function

Reduce() is..

  • The reduce() method reduces the array to a single value.
  • The reduce() method executes a provided function for each value of the array (from left-to-right).
  • The return value of the function is stored in an accumulator (result/total).

It was ..

let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6

Change to

let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);

Also you can use in

  1. find max
    let array=[5,4,19,2,7];
    function findMax(acc,val)
    {
     if(val>acc){
       acc=val; 
     }
    }

    let biggest=arrays.reduce(findMax); // 19
  1. find an element that not repeated.
    arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
    v = 0
    for i in range(len(arr)):
    v = v ^ arr[i]
    print(value)  //6

how to convert .java file to a .class file

From the command line, run

javac ClassName.java

error: package javax.servlet does not exist

I only put this code in my pom.xml and I executed the command maven install.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Could not open input file: composer.phar

Try in command line:

curl -sS https://getcomposer.org/installer | php

Check if an element has event listener on it. No jQuery

You don't need to. Just slap it on there as many times as you want and as often as you want. MDN explains identical event listeners:

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener method.

Stashing only staged changes in git - is it possible?

In this scenario, I prefer to create new branches for each issue. I use a prefix temp/ so I know that I can delete these branches later.

git checkout -b temp/bug1

Stage the files that fix bug1 and commit them.

git checkout -b temp/bug2

You can then cherry pick the commits from the respective branches as require and submit a pull request.

npm install hangs

I was having the same problem. I tried a

npm config set registry http://registry.npmjs.org/

to turn off https. I also tried

npm set progress=false 

to turn off the progress bar (it has been reported to slow down downloads).

The problem was with my network driver. I just needed to reboot and the lag went away.

Operation must use an updatable query. (Error 3073) Microsoft Access

(A little late to the party...)

The three ways I've gotten around this problem in the past are:

  1. Reference a text box on an open form
  2. DSum
  3. DLookup

In Python how should I test if a variable is None, True or False

Don't fear the Exception! Having your program just log and continue is as easy as:

try:
    result = simulate(open("myfile"))
except SimulationException as sim_exc:
    print "error parsing stream", sim_exc
else:
    if result:
        print "result pass"
    else:
        print "result fail"

# execution continues from here, regardless of exception or not

And now you can have a much richer type of notification from the simulate method as to what exactly went wrong, in case you find error/no-error not to be informative enough.

Get Android Device Name

Try this code. You get android device name.

public static String getDeviceName() {
    String manufacturer = Build.MANUFACTURER;
    String model = Build.MODEL;
    if (model.startsWith(manufacturer)) {
        return model;
    }
    return manufacturer + " " + model;
}

Best way to get child nodes

Don't let white space fool you. Just test this in a console browser.

Use native javascript. Here is and example with two 'ul' sets with the same class. You don't need to have your 'ul' list all in one line to avoid white space just use your array count to jump over white space.

How to get around white space with querySelector() then childNodes[] js fiddle link: https://jsfiddle.net/aparadise/56njekdo/

var y = document.querySelector('.list');
var myNode = y.childNodes[11].style.backgroundColor='red';

<ul class="list">
    <li>8</li>
    <li>9</li>
    <li>100</li>
</ul>

<ul class="list">
    <li>ABC</li>
    <li>DEF</li>
    <li>XYZ</li>
</ul>

How to create a numpy array of all True or all False?

benchmark for Michael Currie's answer

import perfplot

bench_x = perfplot.bench(
    n_range= range(1, 200),
    setup  = lambda n: (n, n),
    kernels= [
        lambda shape: np.ones(shape, dtype= bool),
        lambda shape: np.full(shape, True)
    ],
    labels = ['ones', 'full']
)

bench_x.show()

enter image description here

Global Events in Angular

This is my version:

export interface IEventListenr extends OnDestroy{
    ngOnDestroy(): void
}

@Injectable()
export class EventManagerService {


    private listeners = {};
    private subject = new EventEmitter();
    private eventObserver = this.subject.asObservable();


    constructor() {

        this.eventObserver.subscribe(({name,args})=>{



             if(this.listeners[name])
             {
                 for(let listener of this.listeners[name])
                 {
                     listener.callback(args);
                 }
             }
        })

    }

    public registerEvent(eventName:string,eventListener:IEventListenr,callback:any)
    {

        if(!this.listeners[eventName])
             this.listeners[eventName] = [];

         let eventExist = false;
         for(let listener of this.listeners[eventName])
         {

             if(listener.eventListener.constructor.name==eventListener.constructor.name)
             {
                 eventExist = true;
                 break;
             }
         }

        if(!eventExist)
        {
             this.listeners[eventName].push({eventListener,callback});
        }
    }

    public unregisterEvent(eventName:string,eventListener:IEventListenr)
    {

        if(this.listeners[eventName])
        {
            for(let i = 0; i<this.listeners[eventName].length;i++)
            {

                if(this.listeners[eventName][i].eventListener.constructor.name==eventListener.constructor.name)
                {
                    this.listeners[eventName].splice(i, 1);
                    break;
                }
            }
        }


    }


    emit(name:string,...args:any[])
    {
        this.subject.next({name,args});
    }
}

use:

export class <YOURCOMPONENT> implements IEventListener{

  constructor(private eventManager: EventManagerService) {


    this.eventManager.registerEvent('EVENT_NAME',this,(args:any)=>{
       ....
    })


  }

  ngOnDestroy(): void {
    this.eventManager.unregisterEvent('closeModal',this)
  }

}

emit:

 this.eventManager.emit("EVENT_NAME");

PHP remove all characters before specific string

You can use strstr to do this.

echo strstr($str, 'www/audio');

Is a Python dictionary an example of a hash table?

There must be more to a Python dictionary than a table lookup on hash(). By brute experimentation I found this hash collision:

>>> hash(1.1)
2040142438
>>> hash(4504.1)
2040142438

Yet it doesn't break the dictionary:

>>> d = { 1.1: 'a', 4504.1: 'b' }
>>> d[1.1]
'a'
>>> d[4504.1]
'b'

Sanity check:

>>> for k,v in d.items(): print(hash(k))
2040142438
2040142438

Possibly there's another lookup level beyond hash() that avoids collisions between dictionary keys. Or maybe dict() uses a different hash.

(By the way, this in Python 2.7.10. Same story in Python 3.4.3 and 3.5.0 with a collision at hash(1.1) == hash(214748749.8).)

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

JFrame in full screen Java

You only need this:

JFrame frame = new JFrame();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

When you use the MAXIMIZED_BOTH modifier, it will max all the way across the window (height and width).

There are some that suggested using this:

frame.setUndecorated(true);

I won't recommend it, because your window won't have a header, thus no close/restore/minimize button.

How to check if a value exists in an array in Ruby

This will tell you not only that it exists but also how many times it appears:

 a = ['Cat', 'Dog', 'Bird']
 a.count("Dog")
 #=> 1

How can I return to a parent activity correctly?

A better way to achieve this is by using two things: call:

NavUtils.navigateUpFromSameTask(this);

Now, in order for this to work, you need to have your manifest file state that activity A has a parent activity B. The parent activity doesn't need anything. In version 4 and above you will get a nice back arrow with no additional effort (this can be done on lower versions as well with a little code, I'll put it below) You can set this data in the manifest->application tab in the GUI (scroll down to the parent activity name, and put it by hand)

Support node:

if you wish to support version below version 4, you need to include metadata as well. right click on the activity, add->meta data, name =android.support.PARENT_ACTIVITY and value = your.full.activity.name

to get the nice arrow in lower versions as well:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

please note you will need support library version 7 to get this all working, but it is well worth it!

How to check if the user can go back in browser history or not

I am using a bit of PHP to achieve the result. It's a bit rusty though. But it should work.

<?php 
function pref(){ 
  return (isset($_SERVER['HTTP_REFERER'])) ? true : '';
}
?>
<html>
<body>

<input type="hidden" id="_pref" value="<?=pref()?>">

<button type="button" id="myButton">GoBack</button>

<!-- Include jquery library -->
<script> 
  if (!$('#_pref').val()) { 
    $('#myButton').hide() // or $('#myButton').remove()
  } 
</script>
</body>
</html>

What does the 'Z' mean in Unix timestamp '120314170138Z'?

The Z stands for 'Zulu' - your times are in UTC. From Wikipedia:

The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time. This is especially true in aviation, where Zulu is the universal standard.

good example of Javadoc

Have a look at Spring framework source, it has excellent javadocs

How can I delete a service in Windows?

If they are .NET created services you can use the installutil.exe with the /u switch its in the .net framework folder like C:\Windows\Microsoft.NET\Framework64\v2.0.50727

how to compare the Java Byte[] array?

Try for this:

boolean blnResult = Arrays.equals(byteArray1, byteArray2);

I am also not sure about this, but try this may be it works.

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

I encountered a similar error with while attempting to play an audio file. At first, it was working, then it stopped working when I started using ChangeDetector's markForCheck method in the same function to trigger a re-render when a promise resolves (I had an issue with view rendering).

When I changed the markForCheck to detectChanges it started working again. I really can't explain what happened, I just thought of dropping this here, perhaps it would help someone.

mysql Foreign key constraint is incorrectly formed error

One more probable cause for the display of this error. The order in which I was creating tables was wrong. I was trying to reference a key from a table that was not yet created.

Duplicate and rename Xcode project & associated folders

I'm using simple BASH script for renaming.

Usage: ./rename.sh oldName newName

#!/bin/sh

OLDNAME=$1
NEWNAME=$2

export LC_CTYPE=C 
export LANG=C
find . -type f ! -path ".*/.*" -exec sed -i '' -e "s/${OLDNAME}/${NEWNAME}/g" {} +

mv "${OLDNAME}.xcodeproj" "${NEWNAME}.xcodeproj"
mv "${OLDNAME}" "${NEWNAME}"

Notes:

  1. This script will ignore all files like .git and .DS_Store
  2. Will not work if old name/new name contains spaces
  3. May not work if you use pods (not tested)
  4. Scheme name will not be changed (anyway project runs and compiles normally)

Found a swap file by the name

Accepted answer fails to mention how to delete the .swp file.

Hit "D" when the prompt comes up and it will remove it.

In my case, after I hit D it left the latest saved version intact and deleted the .swp which got created because I exited VIM incorrectly

SQL Query To Obtain Value that Occurs more than once

I think this answer can also work (it may require a little bit of modification though) :

SELECT * FROM Students AS S1 WHERE EXISTS(SELECT Lastname, count(*) FROM Students AS S2 GROUP BY Lastname HAVING COUNT(*) > 3 WHERE S2.Lastname = S1.Lastname)

How can I use a reportviewer control in an asp.net mvc 3 razor view?

You will not only have to use an asp.net page but

If using the Entity Framework or LinqToSql (if using partial classes) move the data into a separate project, the report designer cannot see the classes.

Move the reports to another project/dll, VS10 has bugs were asp.net projects cannot see object datasources in web apps. Then stream the reports from the dll into your mvc projects aspx page.

This applies for mvc and webform projects. Using sql reports in the local mode is not a pleasent development experience. Also watch your webserver memory if exporting large reports. The reportviewer/export is very poorly designed.

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was just having this issue with my own program. I turned out that the value I was searching for was not in my reference table. I fixed my reference table, and then the error went away.

How to get image width and height in OpenCV?

You can use rows and cols:

cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;

or size():

cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;

ld: framework not found Pods

Just Remove your .framework from the list of "Your Project->General->Linked Framework & Libraries".

Flatten nested dictionaries, compressing keys

Using generators:

def flat_dic_helper(prepand,d):
    if len(prepand) > 0:
        prepand = prepand + "_"
    for k in d:
        i=d[k]
        if type(i).__name__=='dict':
            r = flat_dic_helper(prepand+k,i)
            for j in r:
                yield j
        else:
            yield (prepand+k,i)

def flat_dic(d): return dict(flat_dic_helper("",d))

d={'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}
print(flat_dic(d))


>> {'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}

Mapping many-to-many association table with extra column(s)

Since the SERVICE_USER table is not a pure join table, but has additional functional fields (blocked), you must map it as an entity, and decompose the many to many association between User and Service into two OneToMany associations : One User has many UserServices, and one Service has many UserServices.

You haven't shown us the most important part : the mapping and initialization of the relationships between your entities (i.e. the part you have problems with). So I'll show you how it should look like.

If you make the relationships bidirectional, you should thus have

class User {
    @OneToMany(mappedBy = "user")
    private Set<UserService> userServices = new HashSet<UserService>();
}

class UserService {
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "service_code")
    private Service service;

    @Column(name = "blocked")
    private boolean blocked;
}

class Service {
    @OneToMany(mappedBy = "service")
    private Set<UserService> userServices = new HashSet<UserService>();
}

If you don't put any cascade on your relationships, then you must persist/save all the entities. Although only the owning side of the relationship (here, the UserService side) must be initialized, it's also a good practice to make sure both sides are in coherence.

User user = new User();
Service service = new Service();
UserService userService = new UserService();

user.addUserService(userService);
userService.setUser(user);

service.addUserService(userService);
userService.setService(service);

session.save(user);
session.save(service);
session.save(userService);

Explanation of the UML arrows

A nice cheat sheet (http://loufranco.com/wp-content/uploads/2012/11/cheatsheet.pdf):

It covers:

  • Class Diagram
  • Sequence Diagram
  • Package Diagram
  • Object Diagram
  • Use Case Diagram

And provides a few samples.

Class Diagram Elements, like parent to child relationship , subclass relationship, interface and implementor, plus Sequence Diagram Elements

How to set up tmux so that it starts up with specified windows opened?

tmuxp support JSON or YAML session configuration and a python API. A simple tmuxp configuration file to create a new session in YAML syntax is:

session_name: 2-pane-vertical
windows:
  - window_name: my test window
    panes:
      - pwd
      - pwd

How can I make a weak protocol reference in 'pure' Swift (without @objc)

AnyObject is the official way to use a weak reference in Swift.

class MyClass {
    weak var delegate: MyClassDelegate?
}

protocol MyClassDelegate: AnyObject {
}

From Apple:

To prevent strong reference cycles, delegates should be declared as weak references. For more information about weak references, see Strong Reference Cycles Between Class Instances. Marking the protocol as class-only will later allow you to declare that the delegate must use a weak reference. You mark a protocol as being class-only by inheriting from AnyObject, as discussed in Class-Only Protocols.

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID276

How can I indent multiple lines in Xcode?

If you use synergy (to share one keyboard for two PCs) and PC(MAC) in which you are using xcode is slave, and master PC is Windows PC

keyboard shortcuts are alt+] for indent and alt+[ for un-indent.

Update:

But from synergy version 1.5 working ?+[ for indent and ?+] for un-indent

How to debug stored procedures with print statements?

If you're using MSSQL Server management studio print statements will print out under the messages tab not under the Results tab.

enter image description here

Print statements will appear there.

HTML.ActionLink vs Url.Action in ASP.NET Razor

You can easily present Html.ActionLink as a button by using the appropriate CSS style. For example:

@Html.ActionLink("Save", "ActionMethod", "Controller", new { @class = "btn btn-primary" })

List vs tuple, when to use each?

There's a strong culture of tuples being for heterogeneous collections, similar to what you'd use structs for in C, and lists being for homogeneous collections, similar to what you'd use arrays for. But I've never quite squared this with the mutability issue mentioned in the other answers. Mutability has teeth to it (you actually can't change a tuple), while homogeneity is not enforced, and so seems to be a much less interesting distinction.

How to create a release signed apk file using Gradle?

To complement the other answers, you can also place your gradle.properties file in your own module folder, together with build.gradle, just in case your keystore is specific to one project.

htaccess redirect if URL contains a certain string

RewriteRule ^(.*)foobar(.*)$ http://www.example.com/index.php [L,R=301]

(No space inside your website)

ImportError: No module named Image

On a system with both Python 2 and 3 installed and with pip2-installed Pillow failing to provide Image, it is possible to install PIL for Python 2 in a way that will solve ImportError: No module named Image:

easy_install-2.7 --user PIL

or

sudo easy_install-2.7 PIL

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

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

You can use this equivalent syntax:

obj[name] = value

Conditional HTML Attributes using Razor MVC3

I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:

@{
 var htmlAttr = new Dictionary<string, object>();
 htmlAttr.Add("id", strElementId);
 if (!CSSClass.IsEmpty())
 {
   htmlAttr.Add("class", strCSSClass);
 }
}

@* ... *@

@Html.TextBox("somename", "", htmlAttr)

If this way will be useful for you i recommend to define dictionary htmlAttr in your model so your view doesn't need any @{ } logic blocks (be more clear).

ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536

I had been facing this problem for two days and I found that the directory you create in Oracle also needs to created first on your physical disk.

I didn't find this point mentioned anywhere i tried to look up the solution to this.

Example

If you created a directory, let's say, 'DB_DIR'.

CREATE OR REPLACE DIRECTORY DB_DIR AS 'E:\DB_WORKS';

Then you need to ensure that DB_WORKS exists in your E:\ drive and also file system level Read/Write permissions are available to the Oracle process.

My understanding of UTL_FILE from my experiences is given below for this kind of operation.

UTL_FILE is an object under SYS user. GRANT EXECUTE ON SYS.UTL_FILE TO PUBLIC; needs to given while logged in as SYS. Otherwise, it will give declaration error in procedure. Anyone can create a directory as shown:- CREATE OR REPLACE DIRECTORY DB_DIR AS 'E:\DBWORKS'; But CREATE DIRECTORY permission should be in place. This can be granted as shown:- GRANT CREATE ALL DIRECTORY TO user; while logged in as SYS user. However, if this needs to be used by another user, grants need to be given to that user otherwise it will throw error. GRANT READ, WRITE, EXECUTE ON DB_DIR TO user; while loggedin as the user who created the directory. Then, compile your package. Before executing the procedure, ensure that the Directory exists physically on your Disk. Otherwise it will throw 'Invalid File Operation' error. (V. IMPORTANT) Ensure that Filesystem level Read/Write permissions are in place for the Oracle process. This is separate from the DB level permissions granted.(V. IMPORTANT) Execute procedure. File should get populated with the result set of your query.

Maximum call stack size exceeded error

In my case, two jQuery modals were showing stacked on top of each other. Preventing that solved my problem.