Programs & Examples On #File monitoring

How can I compare two time strings in the format HH:MM:SS?

You could compare the two values right after splitting them with ':'.

How to call a method with a separate thread in Java?

To achieve this with RxJava 2.x you can use:

Completable.fromAction(this::dowork).subscribeOn(Schedulers.io().subscribe();

The subscribeOn() method specifies which scheduler to run the action on - RxJava has several predefined schedulers, including Schedulers.io() which has a thread pool intended for I/O operations, and Schedulers.computation() which is intended for CPU intensive operations.

Compiler error: "initializer element is not a compile-time constant"

The reason is that your are defining your imageSegment outside of a function in your source code (static variable).

In such cases, the initialization cannot include execution of code, like calling a function or allocation a class. Initializer must be a constant whose value is known at compile time.

You can then initialize your static variable inside of your init method (if you postpone its declaration to init).

Get string between two strings in a string

Perhaps, a good way is just to cut out a substring:

String St = "super exemple of string key : text I want to keep - end of my string";

int pFrom = St.IndexOf("key : ") + "key : ".Length;
int pTo = St.LastIndexOf(" - ");

String result = St.Substring(pFrom, pTo - pFrom);

Entity framework left join

If UserGroups has a one to many relationship with UserGroupPrices table, then in EF, once the relationship is defined in code like:

//In UserGroups Model
public List<UserGroupPrices> UserGrpPriceList {get;set;}

//In UserGroupPrices model
public UserGroups UserGrps {get;set;}

You can pull the left joined result set by simply this:

var list = db.UserGroupDbSet.ToList();

assuming your DbSet for the left table is UserGroupDbSet, which will include the UserGrpPriceList, which is a list of all associated records from the right table.

How to add a column in TSQL after a specific column?

Unfortunately you can't.

If you really want them in that order you'll have to create a new table with the columns in that order and copy data. Or rename columns etc. There is no easy way.

HTTP get with headers using RestTemplate

The RestTemplate getForObject() method does not support setting headers. The solution is to use the exchange() method.

So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use

HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...

HttpEntity entity = new HttpEntity(headers);

ResponseEntity<String> response = restTemplate.exchange(
    url, HttpMethod.GET, entity, String.class, param);

Finally, use response.getBody() to get your result.

This question is similar to this question.

unix diff side-to-side results?

You can use vimdiff.

Example:

vimdiff file1 file2

JavaScript equivalent of PHP's in_array()

An equivalent of in_array with underscore is _.indexOf

Examples:

_.indexOf([3, 5, 8], 8); // returns 2, the index of 8 _.indexOf([3, 5, 8], 10); // returns -1, not found

Determine if two rectangles overlap each other?

"If you perform subtraction x or y coordinates corresponding to the vertices of the two facing each rectangle, if the results are the same sign, the two rectangle do not overlap axes that" (i am sorry, i am not sure my translation is correct)

enter image description here

Source: http://www.ieev.org/2009/05/kiem-tra-hai-hinh-chu-nhat-chong-nhau.html

Iterating through a List Object in JSP

another example with just scriplets, when iterating through an ArrayList that contains Maps.

<%   
java.util.List<java.util.Map<String,String>> employees=(java.util.List<java.util.Map<String, String>>)request.getAttribute("employees");    

for (java.util.Map employee: employees) {
%>
<tr>
<td><input value="<%=employee.get("fullName") %>"/></td>    
</tr>
...
<%}%>

Twitter Bootstrap Form File Element Upload Button

With no additional plugin required, this bootstrap solution works great for me:

<div style="position:relative;">
        <a class='btn btn-primary' href='javascript:;'>
            Choose File...
            <input type="file" style='position:absolute;z-index:2;top:0;left:0;filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";opacity:0;background-color:transparent;color:transparent;' name="file_source" size="40"  onchange='$("#upload-file-info").html($(this).val());'>
        </a>
        &nbsp;
        <span class='label label-info' id="upload-file-info"></span>
</div>

demo:

http://jsfiddle.net/haisumbhatti/cAXFA/1/ (bootstrap 2)

enter image description here

http://jsfiddle.net/haisumbhatti/y3xyU/ (bootstrap 3)

enter image description here

Python Requests - No connection adapters

You need to include the protocol scheme:

'http://192.168.1.61:8080/api/call'

Without the http:// part, requests has no idea how to connect to the remote server.

Note that the protocol scheme must be all lowercase; if your URL starts with HTTP:// for example, it won’t find the http:// connection adapter either.

HTTP test server accepting GET/POST requests

Just set one up yourself. Copy this snippet to your webserver.


echo "<pre>";
print_r($_POST);
echo "</pre>";

Just post what you want to that page. Done.

Calculate cosine similarity given 2 sentence strings

The short answer is "no, it is not possible to do that in a principled way that works even remotely well". It is an unsolved problem in natural language processing research and also happens to be the subject of my doctoral work. I'll very briefly summarize where we are and point you to a few publications:

Meaning of words

The most important assumption here is that it is possible to obtain a vector that represents each word in the sentence in quesion. This vector is usually chosen to capture the contexts the word can appear in. For example, if we only consider the three contexts "eat", "red" and "fluffy", the word "cat" might be represented as [98, 1, 87], because if you were to read a very very long piece of text (a few billion words is not uncommon by today's standard), the word "cat" would appear very often in the context of "fluffy" and "eat", but not that often in the context of "red". In the same way, "dog" might be represented as [87,2,34] and "umbrella" might be [1,13,0]. Imagening these vectors as points in 3D space, "cat" is clearly closer to "dog" than it is to "umbrella", therefore "cat" also means something more similar to "dog" than to an "umbrella".

This line of work has been investigated since the early 90s (e.g. this work by Greffenstette) and has yielded some surprisingly good results. For example, here is a few random entries in a thesaurus I built recently by having my computer read wikipedia:

theory -> analysis, concept, approach, idea, method
voice -> vocal, tone, sound, melody, singing
james -> william, john, thomas, robert, george, charles

These lists of similar words were obtained entirely without human intervention- you feed text in and come back a few hours later.

The problem with phrases

You might ask why we are not doing the same thing for longer phrases, such as "ginger foxes love fruit". It's because we do not have enough text. In order for us to reliably establish what X is similar to, we need to see many examples of X being used in context. When X is a single word like "voice", this is not too hard. However, as X gets longer, the chances of finding natural occurrences of X get exponentially slower. For comparison, Google has about 1B pages containing the word "fox" and not a single page containing "ginger foxes love fruit", despite the fact that it is a perfectly valid English sentence and we all understand what it means.

Composition

To tackle the problem of data sparsity, we want to perform composition, i.e. to take vectors for words, which are easy to obtain from real text, and to put the together in a way that captures their meaning. The bad news is nobody has been able to do that well so far.

The simplest and most obvious way is to add or multiply the individual word vectors together. This leads to undesirable side effect that "cats chase dogs" and "dogs chase cats" would mean the same to your system. Also, if you are multiplying, you have to be extra careful or every sentences will end up represented by [0,0,0,...,0], which defeats the point.

Further reading

I will not discuss the more sophisticated methods for composition that have been proposed so far. I suggest you read Katrin Erk's "Vector space models of word meaning and phrase meaning: a survey". This is a very good high-level survey to get you started. Unfortunately, is not freely available on the publisher's website, email the author directly to get a copy. In that paper you will find references to many more concrete methods. The more comprehensible ones are by Mitchel and Lapata (2008) and Baroni and Zamparelli (2010).


Edit after comment by @vpekar: The bottom line of this answer is to stress the fact that while naive methods do exist (e.g. addition, multiplication, surface similarity, etc), these are fundamentally flawed and in general one should not expect great performance from them.

Open Popup window using javascript

To create a popup you'll need the following script:

<script language="javascript" type="text/javascript">

function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}


</script>

Then, you link to it by:

  <a href="popupex.html" onclick="return popitup('popupex.html')">Link to popup</a>

If you want you can call the function directly from document.ready also. Or maybe from another function.

Java Regex to Validate Full Name allow only Spaces and Letters

What about:

  • Peter Müller
  • François Hollande
  • Patrick O'Brian
  • Silvana Koch-Mehrin

Validating names is a difficult issue, because valid names are not only consisting of the letters A-Z.

At least you should use the Unicode property for letters and add more special characters. A first approach could be e.g.:

String regx = "^[\\p{L} .'-]+$";

\\p{L} is a Unicode Character Property that matches any kind of letter from any language

Change select box option background color

My selects would not color the background until I added !important to the style.

    input, select, select option{background-color:#FFE !important}

MySQL - Cannot add or update a child row: a foreign key constraint fails

I've faced this issue and the solution was making sure that all the data from the child field are matching the parent field

for example, you want to add foreign key inside (attendance) table to the column (employeeName)

where the parent is (employees) table, (employeeName) column

all the data in attendance.employeeName must be matching employee.employeeName

ASP.NET MVC 3 - redirect to another action

You have to write this code instead of return View(); :

return RedirectToAction("ActionName", "ControllerName");

Prevent users from submitting a form by hitting Enter

A completely different approach:

  1. The first <button type="submit"> in the form will be activated on pressing Enter.
  2. This is true even if the button is hidden with style="display:none;
  3. The script for that button can return false, which aborts the submission process.
  4. You can still have another <button type=submit> to submit the form. Just return true to cascade the submission.
  5. Pressing Enter while the real submit button is focussed will activate the real submit button.
  6. Pressing Enter inside <textarea> or other form controls will behave as normal.
  7. Pressing Enter inside <input> form controls will trigger the first <button type=submit>, which returns false, and thus nothing happens.

Thus:

<form action="...">
  <!-- insert this next line immediately after the <form> opening tag -->
  <button type=submit onclick="return false;" style="display:none;"></button>

  <!-- everything else follows as normal -->
  <!-- ... -->
  <button type=submit>Submit</button>
</form>

React Modifying Textarea Values

As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.

The value of the following uncontrolled textarea cannot be changed because of value

 <textarea type="text" value="some value"
    onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute

<textarea type="text" defaultValue="sample" 
    onChange={(event) => this.handleOnChange(event)}></textarea>

<textarea type="text" 
   onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener

<textarea value={this.state.textareaValue} 
onChange={(event) => this.handleOnChange(event)}></textarea>

Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return <div>
        <form onSubmit={(event) => this.handleOnSubmit(event)}>
          <textarea rows={10} cols={30} value={this.state.textareaValue} 
            onChange={(event) => this.handleOnChange(event)}></textarea>
          <br/>
          <input type="submit" value="Save"/>
        </form>
      </div>
  }
}
ReactDOM.render(<Editor />, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

Truncate a string straight JavaScript

_x000D_
_x000D_
var pa = document.getElementsByTagName('p')[0].innerHTML;_x000D_
var rpa = document.getElementsByTagName('p')[0];_x000D_
// console.log(pa.slice(0, 30));_x000D_
var newPa = pa.slice(0, 29).concat('...');_x000D_
rpa.textContent = newPa;_x000D_
console.log(newPa)
_x000D_
<p>_x000D_
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here_x000D_
</p>
_x000D_
_x000D_
_x000D_

How to get the first word in the string

You shoud do something like :

print line.split()[0]

Best way to center a <div> on a page vertically and horizontally?

There is actually a solution, using css3, which can vertically center a div of unknown height. The trick is to move the div down by 50%, then use transformY to get it back up to the middle. The only prerequisite is that the to-be-centered element has a parent. Example:

<div class="parent">
    <div class="center-me">
        Text, images, whatever suits you.
    </div>
</div>

.parent { 
    /* height can be whatever you want, also auto if you want a child 
       div to be responsible for the sizing */ 
    height: 200px;
}

.center-me { 
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    /* prefixes needed for cross-browser support */
    -ms-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
}

Supported by all major browsers, and IE 9 and up (don't bother about IE 8, as it died together with win xp this autumn. Thank god.)

JS Fiddle Demo

Python - Extracting and Saving Video Frames

Following script will extract frames every half a second of all videos in folder. (Works on python 3.7)

import cv2
import os
listing = os.listdir(r'D:/Images/AllVideos')
count=1
for vid in listing:
    vid = r"D:/Images/AllVideos/"+vid
    vidcap = cv2.VideoCapture(vid)
    def getFrame(sec):
        vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*1000)
        hasFrames,image = vidcap.read()
        if hasFrames:
            cv2.imwrite("D:/Images/Frames/image"+str(count)+".jpg", image) # Save frame as JPG file
        return hasFrames
    sec = 0
    frameRate = 0.5 # Change this number to 1 for each 1 second
    
    success = getFrame(sec)
    while success:
        count = count + 1
        sec = sec + frameRate
        sec = round(sec, 2)
        success = getFrame(sec)

How to get access to raw resources that I put in res folder?

In some situations we have to get image from drawable or raw folder using image name instead if generated id

// Image View Object 
        mIv = (ImageView) findViewById(R.id.xidIma);
// create context Object for  to Fetch  image from resourse 
Context mContext=getApplicationContext();

// getResources().getIdentifier("image_name","res_folder_name", package_name);

// find out below example 
    int i = mContext.getResources().getIdentifier("ic_launcher","raw", mContext.getPackageName());

// now we will get contsant id for that image       
        mIv.setBackgroundResource(i);

Hidden features of Windows batch files

I have always found it difficult to read comments that are marked by a keyword on each line:

REM blah blah blah

Easier to read:

:: blah blah blah

How to "z-index" to make a menu always on top of the content

You most probably don't need z-index to do that. You can use relative and absolute positioning.

I advise you to take a better look at css positioning and the difference between relative and absolute positioning... I saw you're setting position: absolute; to an element and trying to float that element. It won't work friend! When you understand positioning in CSS it will make your work a lot easier! ;)

Edit: Just to be clear, positioning is not a replacement for them and I do use z-index. I just try to avoid using them. Using z-indexes everywhere seems easy and fun at first... until you have bugs related to them and find yourself having to revisit and manage z-indexes.

How can I pass a parameter to a Java Thread?

This answer comes very late, but maybe someone will find it useful. It is about how to pass a parameter(s) to a Runnable without even declaring named class (handy for inliners):

    String someValue = "Just a demo, really...";

    new Thread(new Runnable() {
        private String myParam;

        public Runnable init(String myParam) {
            this.myParam = myParam;
            return this;
        }

        @Override
        public void run() {
            System.out.println("This is called from another thread.");
            System.out.println(this.myParam);
        }
    }.init(someValue)).start();

Of course you can postpone execution of start to some more convenient or appropriate moment. And it is up to you what will be the signature of init method (so it may take more and/or different arguments) and of course even its name, but basically you get an idea.

In fact there is also another way of passing a parameter to an anonymous class, with the use of the initializer blocks. Consider this:

    String someValue = "Another demo, no serious thing...";
    int anotherValue = 42;

    new Thread(new Runnable() {
        private String myParam;
        private int myOtherParam;
        // instance initializer
        {
            this.myParam = someValue;
            this.myOtherParam = anotherValue;
        }

        @Override
        public void run() {
            System.out.println("This comes from another thread.");
            System.out.println(this.myParam + ", " + this.myOtherParam);
        }
    }).start();

So all happens inside of the initializer block.

MySQL query to get column names?

if you use php, use this gist.

it can get select fields full info with no result,and all custom fields such as:

SELECT a.name aname, b.name bname, b.* 
FROM table1 a LEFT JOIN table2 b
ON a.id = b.pid;

if above sql return no data,will also get the field names aname, bname, b's other field name

just two line:

$query_info = mysqli_query($link, $data_source);
$fetch_fields_result = $query_info->fetch_fields();

Summernote image upload

UPLOAD IMAGES WITH PROGRESS BAR

Thought I'd extend upon user3451783's answer and provide one with an HTML5 progress bar. I found that it was very annoying uploading photos without knowing if anything was happening at all.

HTML

<progress></progress>

<div id="summernote"></div>

JS

// initialise editor

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

// send the file

function sendFile(file, editor, welEditable) {
        data = new FormData();
        data.append("file", file);
        $.ajax({
            data: data,
            type: 'POST',
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
                return myXhr;
            },
            url: root + '/assets/scripts/php/app/uploadEditorImages.php',
            cache: false,
            contentType: false,
            processData: false,
            success: function(url) {
                editor.insertImage(welEditable, url);
            }
        });
}

// update progress bar

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded, max:e.total});
        // reset progress on complete
        if (e.loaded == e.total) {
            $('progress').attr('value','0.0');
        }
    }
}

Example for boost shared_mutex (multiple reads/one write)?

It looks like you would do something like this:

boost::shared_mutex _access;
void reader()
{
  // get shared access
  boost::shared_lock<boost::shared_mutex> lock(_access);

  // now we have shared access
}

void writer()
{
  // get upgradable access
  boost::upgrade_lock<boost::shared_mutex> lock(_access);

  // get exclusive access
  boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
  // now we have exclusive access
}

How to make an ng-click event conditional?

We can add ng-click event conditionally without using disabled class.

HTML:

<div ng-repeat="object in objects">
<span ng-click="!object.status && disableIt(object)">{{object.value}}</span>
</div>

Easy way to get a test file into JUnit

I know you said you didn't want to read the file in by hand, but this is pretty easy

public class FooTest
{
    private BufferedReader in = null;

    @Before
    public void setup()
        throws IOException
    {
        in = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream("/data.txt")));
    }

    @After
    public void teardown()
        throws IOException
    {
        if (in != null)
        {
            in.close();
        }

        in = null;
    }

    @Test
    public void testFoo()
        throws IOException
    {
        String line = in.readLine();

        assertThat(line, notNullValue());
    }
}

All you have to do is ensure the file in question is in the classpath. If you're using Maven, just put the file in src/test/resources and Maven will include it in the classpath when running your tests. If you need to do this sort of thing a lot, you could put the code that opens the file in a superclass and have your tests inherit from that.

Create component to specific module with Angular-CLI

  1. You can generate a Module using ng generate module <module name>.
  2. Then use this command to generate a component related to that module, ng generate component <component name> --module=<module name>

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

You can also use the Secure Template Overloads, they will help you replace the unsecure calls with secure ones anywhere it is possible to easily deduce buffer size (static arrays).

Just add the following:

#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 

Then fix the remaining warnings by hand, by using the _s functions.

How do I mount a remote Linux folder in Windows through SSH?

Back in 2002, Novell developed some software called NetDrive that can map a WebDAV, FTP, SFTP, etc. share to a windows drive letter. It is now abandonware, so it's no longer maintained (and not available on the Novell website), but it's free to use. I found quite a few available to download by searching for "netdrive.exe" I actually downloaded a few and compared their md5sums to make sure that I was getting a common (and hopefully safe) version.

Update 10 Nov 2017 SFTPNetDrive is the current project from the original netdrive project. And they made it free for personal use:

We Made SFTP Net Drive FREE for Personal Use

They have paid options as well on the website.

Expand a div to fill the remaining width

Thanks for the plug of Simpl.css!

remember to wrap all your columns in ColumnWrapper like so.

<div class="ColumnWrapper">
    <div class="Colum­nOne­Half">Tree</div>
    <div class="Colum­nOne­Half">View</div>
</div>

I am about to release version 1.0 of Simpl.css so help spread the word!

How to change a table name using an SQL query?

Please use this on SQL Server 2005:

sp_rename old_table_name , new_table_name

it will give you:

Caution: Changing any part of an object name could break scripts and stored procedures.

but your table name will be changed.

Align two divs horizontally side by side center to the page using bootstrap css

Alternate Bootstrap 4 solution (this way you can use divs which are smaller than col-6):

Horizontal Align Center

<div class="container">
  <div class="row justify-content-center">
    <div class="col-4">
      One of two columns
    </div>
    <div class="col-4">
      One of two columns
    </div>
  </div>
</div>

More

How to set environment variables from within package.json?

@luke's answer was almost the one I needed! Thanks.

As the selected answer is very straightforward (and correct), but old, I would like to offer an alternative for importing variables from a .env separate file when running your scripts and fixing some limitations to Luke's answer. Try this:

::: .env file :::

# This way, you CAN use comments in your .env files
NODE_PATH="src/"

# You can also have extra/empty lines in it
SASS_PATH="node_modules:src/styles"

Then, in your package json, you will create a script that will set the variables and run it before the scripts you need them:

::: package.json :::

scripts: {
  "set-env": "export $(cat .env | grep \"^[^#;]\" |xargs)",
  "storybook": "npm run set-env && start-storybook -s public"
}

Some observations:

  • The regular expression in the grep'ed cat command will clear the comments and empty lines.

  • The && don't need to be "glued" to npm run set-env, as it would be required if you were setting the variables in the same command.

  • If you are using yarn, you may see a warning, you can either change it to yarn set-env or use npm run set-env --scripts-prepend-node-path && instead.

Different environments

Another advantage when using it is that you can have different environment variables.

scripts: {
  "set-env:production": "export $(cat .production.env | grep \"^[^#;]\" |xargs)",
  "set-env:development": "export $(cat .env | grep \"^[^#;]\" |xargs)",
}

Please, remember not to add .env files to your git repository when you have keys, passwords or sensitive/personal data in them!

Properties order in Margin

Just because @MartinCapodici 's comment is awesome I write here as an answer to give visibility.

All clockwise:

  • WPF start West (left->top->right->bottom)
  • Netscape (ie CSS) start North (top->right->bottom->left)

Replace Fragment inside a ViewPager

This is my way to achieve that.

First of all add Root_fragment inside viewPager tab in which you want to implement button click fragment event. Example;

@Override
public Fragment getItem(int position) {
  if(position==0)
      return RootTabFragment.newInstance();
  else
      return SecondPagerFragment.newInstance();
}

First of all, RootTabFragment should be include FragmentLayout for fragment change.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/root_frame"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
</FrameLayout>

Then, inside RootTabFragment onCreateView, implement fragmentChange for your FirstPagerFragment

getChildFragmentManager().beginTransaction().replace(R.id.root_frame, FirstPagerFragment.newInstance()).commit();

After that, implement onClick event for your button inside FirstPagerFragment and make fragment change like that again.

getChildFragmentManager().beginTransaction().replace(R.id.root_frame, NextFragment.newInstance()).commit();

Hope this will help you guy.

Comparing two dataframes and getting the differences

Building on alko's answer that almost worked for me, except for the filtering step (where I get: ValueError: cannot reindex from a duplicate axis), here is the final solution I used:

# join the dataframes
united_data = pd.concat([data1, data2, data3, ...])
# group the data by the whole row to find duplicates
united_data_grouped = united_data.groupby(list(united_data.columns))
# detect the row indices of unique rows
uniq_data_idx = [x[0] for x in united_data_grouped.indices.values() if len(x) == 1]
# extract those unique values
uniq_data = united_data.iloc[uniq_data_idx]

How to make a <svg> element expand or contract to its parent container?

Suppose I have an SVG which looks like this: pic1

And I want to put it in a div and make it fill the div responsively. My way of doing it is as follows:

First I open the SVG file in an application like inkscape. In File->Document Properties I set the width of the document to 800px and and the height to 600px (you can choose other sizes). Then I fit the SVG into this document.

pic2

Then I save this file as a new SVG file and get the path data from this file. Now in HTML the code that does the magic is as follows:

<div id="containerId">    
    <svg
    id="svgId" 
    xmlns:svg="http://www.w3.org/2000/svg"
    xmlns="http://www.w3.org/2000/svg"
    version="1.1"
    x="0"
    y="0"
    width="100%"
    height="100%"
    viewBox="0 0 800 600"
    preserveAspectRatio="none">
       <path d="m0 0v600h800v-600h-75.07031l-431 597.9707-292.445315-223.99609 269.548825-373.97461h-271.0332z" fill="#f00"/>
    </svg>
</div>

Note that width and height of SVG are both set to 100%, since we want it to fill the container vertically and horizontally ,but width and height of the viewBox are the same as the width and height of the document in inkscape which is 800px X 600px. The next thing you need to do is set the preserveAspectRatio to "none". If you need to have more information on this attribute here's a good link. And that's all there is to it.

One more thing is that this code works on almost all the major browsers even the old ones but on some versions of android and ios you need to use some javascrip/jQuery code to keep it consistent. I use the following in document ready and resize functions:

$('#svgId').css({
    'width': $('#containerId').width() + 'px',
    'height': $('#containerId').height() + 'px'
});

Hope it helps!

Convert blob to base64

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

Form the docs readAsDataURL encodes to base64

SQL Server Convert Varchar to Datetime

You could do it this way but it leaves it as a varchar

declare @s varchar(50)

set @s = '2011-09-28 18:01:00'

select convert(varchar, cast(@s as datetime), 105) + RIGHT(@s, 9)

or

select convert(varchar(20), @s, 105)

How do you convert WSDLs to Java classes using Eclipse?

Using command prompt in windows you can use below command to get class files.

wsimport "complete file path of your .wsdl file"
example : wsimport C:\Users\schemas\com\myprofile\myprofile2019.wsdl

if you want to generate source code you should be using below commnad.

wsimport -keep -s src "complete file path of your .wsdl file"
example : wsimport -keep -s src C:\Users\schemas\com\myprofile\myprofile2019.wsdl

Note : Here "-s" means source directory and "src" is name of folder that should be created before executing this command. Wsimport is a tool which is bundled along with JAVA SE, no seperate download is required.

Binding ComboBox SelectedItem using MVVM

You seem to be unnecessarily setting properties on your ComboBox. You can remove the DisplayMemberPath and SelectedValuePath properties which have different uses. It might be an idea for you to take a look at the Difference between SelectedItem, SelectedValue and SelectedValuePath post here for an explanation of these properties. Try this:

<ComboBox Name="cbxSalesPeriods"
    ItemsSource="{Binding SalesPeriods}"
    SelectedItem="{Binding SelectedSalesPeriod}"
    IsSynchronizedWithCurrentItem="True"/>

Furthermore, it is pointless using your displayPeriod property, as the WPF Framework would call the ToString method automatically for objects that it needs to display that don't have a DataTemplate set up for them explicitly.


UPDATE >>>

As I can't see all of your code, I cannot tell you what you are doing wrong. Instead, all I can do is to provide you with a complete working example of how to achieve what you want. I've removed the pointless displayPeriod property and also your SalesPeriodVO property from your class as I know nothing about it... maybe that is the cause of your problem??. Try this:

public class SalesPeriodV
{
    private int month, year;

    public int Year
    {
        get { return year; }
        set
        {
            if (year != value)
            {
                year = value;
                NotifyPropertyChanged("Year");
            }
        }
    }

    public int Month
    {
        get { return month; }
        set
        {
            if (month != value)
            {
                month = value;
                NotifyPropertyChanged("Month");
            }
        }
    }

    public override string ToString()
    {
        return String.Format("{0:D2}.{1}", Month, Year);
    }

    public virtual event PropertyChangedEventHandler PropertyChanged;
    protected virtual void NotifyPropertyChanged(params string[] propertyNames)
    {
        if (PropertyChanged != null)
        {
            foreach (string propertyName in propertyNames) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            PropertyChanged(this, new PropertyChangedEventArgs("HasError"));
        }
    }
}

Then I added two properties into the view model:

private ObservableCollection<SalesPeriodV> salesPeriods = new ObservableCollection<SalesPeriodV>();
public ObservableCollection<SalesPeriodV> SalesPeriods
{
    get { return salesPeriods; }
    set { salesPeriods = value; NotifyPropertyChanged("SalesPeriods"); }
}
private SalesPeriodV selectedItem = new SalesPeriodV();
public SalesPeriodV SelectedItem
{
    get { return selectedItem; }
    set { selectedItem = value; NotifyPropertyChanged("SelectedItem"); }
}

Then initialised the collection with your values:

SalesPeriods.Add(new SalesPeriodV() { Month = 3, Year = 2013 } );
SalesPeriods.Add(new SalesPeriodV() { Month = 4, Year = 2013 } );

And then data bound only these two properties to a ComboBox:

<ComboBox ItemsSource="{Binding SalesPeriods}" SelectedItem="{Binding SelectedItem}" />

That's it... that's all you need for a perfectly working example. You should see that the display of the items comes from the ToString method without your displayPeriod property. Hopefully, you can work out your mistakes from this code example.

How can I make window.showmodaldialog work in chrome 37?

Yes, It's deprecated. Spent yesterday rewriting code to use Window.open and PostMessage instead.

add a temporary column with a value

select field1, field2, NewField = 'example' from table1 

SELECT with LIMIT in Codeigniter

I don't know what version of CI you were using back in 2013, but I am using CI3 and I just tested with two null parameters passed to limit() and there was no LIMIT or OFFSET in the rendered query (I checked by using get_compiled_select()).

This means that -- assuming your have correctly posted your coding attempt -- you don't need to change anything (or at least the old issue is no longer a CI issue).

If this was my project, this is how I would write the method to return an indexed array of objects or an empty array if there are no qualifying rows in the result set.

function nationList($limit = null, $start = null) {
    // assuming the language value is sanitized/validated/whitelisted
    return $this->db
        ->select('nation.id, nation.name_' . $this->session->userdata('language') . ' AS name')
        ->from('nation')
        ->order_by("name")
        ->limit($limit, $start)
        ->get()
        ->result();
}

These refinements remove unnecessary syntax, conditions, and the redundant loop.

For reference, here is the CI core code:

/**
 * LIMIT
 *
 * @param   int $value  LIMIT value
 * @param   int $offset OFFSET value
 * @return  CI_DB_query_builder
 */
public function limit($value, $offset = 0)
{
    is_null($value) OR $this->qb_limit = (int) $value;
    empty($offset) OR $this->qb_offset = (int) $offset;

    return $this;
}

So the $this->qb_limit and $this->qb_offset class objects are not updated because null evaluates as true when fed to is_null() or empty().

How do you set the document title in React?

Simply you can create a function in a js file and export it for usages in components

like below:

export default function setTitle(title) {
  if (typeof title !== "string") {
     throw new Error("Title should be an string");
  }
  document.title = title;
}

and use it in any component like this:

import React, { Component } from 'react';
import setTitle from './setTitle.js' // no need to js extension at the end

class App extends Component {
  componentDidMount() {
    setTitle("i am a new title");
  }

  render() {
    return (
      <div>
        see the title
      </div>
    );
  }
}

export default App

jQuery append() vs appendChild()

I know this is an old and answered question and I'm not looking for votes I just want to add an extra little thing that I think might help newcomers.

yes appendChild is a DOM method and append is JQuery method but practically the key difference is that appendChild takes a node as a parameter by that I mean if you want to add an empty paragraph to the DOM you need to create that p element first

var p = document.createElement('p')

then you can add it to the DOM whereas JQuery append creates that node for you and adds it to the DOM right away whether it's a text element or an html element or a combination!

$('p').append('<span> I have been appended </span>');

FirebaseInstanceIdService is deprecated

FirebaseinstanceIdService is deprecated. So have to use "FirebaseMessagingService"

Sea the image please:

enter image description here

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("NEW_TOKEN",s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    }
}

Eclipse count lines of code

One possible way to count lines of code in Eclipse:

using the Search / File... menu, select File Search tab, specify \n[\s]* for Containing text (this will not count empty lines), and tick Regular expression.

Hat tip: www.monblocnotes.com/node/2030

Rebuild Docker container on file changes

You can run build for a specific service by running docker-compose up --build <service name> where the service name must match how did you call it in your docker-compose file.

Example Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application in docker-compose file. You can then simply run docker-compose up --build application

Extra parameters In case you want to add extra parameters to your command such as -d for running in the background, the parameter must be before the service name: docker-compose up --build -d application

How to convert string to integer in UNIX

Use this:

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

int main()
{
    const char *d1 = "11";
    int d1int = atoi(d1);
    printf("d1 = %d\n", d1);
    return 0;
}

etc.

How remove border around image in css?

I faced similar problem with img tag I had added following line with img tag.

<img class="my-class">

And this is the css class

.my-class{
    background-image: url('add.gif');
    background-repeat: no-repeat;
    display: inline-block;
    width: 27px;
    height: 27px;
}

I changed the img tag to span tag with same css class. Border is not visible now.

<span class="my-class"></span>

Escaping quotation marks in PHP

$text1= "From time to \"time\"";

or

$text1= 'From time to "time"';

mssql convert varchar to float

You can convert varchars to floats, and you can do it in the manner you have expressed. Your varchar must not be a numeric value. There must be something else in it. You can use IsNumeric to test it. See this:

declare @thing varchar(100)

select @thing = '122.332'

--This returns 1 since it is numeric.
select isnumeric(@thing)

--This converts just fine.
select convert(float,@thing)

select @thing = '122.332.'

--This returns 0 since it is not numeric.
select isnumeric(@thing)

--This convert throws.
select convert(float,@thing)

How an 'if (A && B)' statement is evaluated?

for logical && both the parameters must be true , then it ll be entered in if {} clock otherwise it ll execute else {}. for logical || one of parameter or condition is true is sufficient to execute if {}.

if( (A) && (B) ){
     //if A and B both are true
}else{
}
if( (A) ||(B) ){
     //if A or B is true 
}else{
}

Run function in script from command line (Node JS)

This one is dirty but works :)

I will be calling main() function from my script. Previously I just put calls to main at the end of script. However I did add some other functions and exported them from script (to use functions in some other parts of code) - but I dont want to execute main() function every time I import other functions in other scripts.

So I did this, in my script i removed call to main(), and instead at the end of script I put this check:

if (process.argv.includes('main')) {
   main();
}

So when I want to call that function in CLI: node src/myScript.js main

How do we check if a pointer is NULL pointer?

I always think simply if(p != NULL){..} will do the job.

It will.

Drop data frame columns by name

Dplyr Solution

I doubt this will get much attention down here, but if you have a list of columns that you want to remove, and you want to do it in a dplyr chain I use one_of() in the select clause:

Here is a simple, reproducable example:

undesired <- c('mpg', 'cyl', 'hp')

mtcars <- mtcars %>%
  select(-one_of(undesired))

Documentation can be found by running ?one_of or here:

http://genomicsclass.github.io/book/pages/dplyr_tutorial.html

Change the maximum upload file size

the answers are a bit incomplete, 3 things you have to do

in php.ini of your php installation (note: depending if you want it for CLI, apache, or nginx, find the right php.ini to manipulate. For nginx it is usually located in /etc/php/7.1/fpm where 7.1 depends on your version. For apache usually /etc/php/7.1/apache2)

post_max_size=500M

upload_max_filesize=500M

memory_limit=900M

or set other values. Restart/reload apache if you have apache installed or php-fpm for nginx if you use nginx.

Javascript : natural sort of alphanumerical strings

So you need a natural sort ?

If so, than maybe this script by Brian Huisman based on David koelle's work would be what you need.

It seems like Brian Huisman's solution is now directly hosted on David Koelle's blog:

How do I update a GitHub forked repository?

Here is GitHub's official document on Syncing a fork:

Syncing a fork

The Setup

Before you can sync, you need to add a remote that points to the upstream repository. You may have done this when you originally forked.

Tip: Syncing your fork only updates your local copy of the repository; it does not update your repository on GitHub.

$ git remote -v
# List the current remotes
origin  https://github.com/user/repo.git (fetch)
origin  https://github.com/user/repo.git (push)

$ git remote add upstream https://github.com/otheruser/repo.git
# Set a new remote

$ git remote -v
# Verify new remote
origin    https://github.com/user/repo.git (fetch)
origin    https://github.com/user/repo.git (push)
upstream  https://github.com/otheruser/repo.git (fetch)
upstream  https://github.com/otheruser/repo.git (push)

Syncing

There are two steps required to sync your repository with the upstream: first you must fetch from the remote, then you must merge the desired branch into your local branch.

Fetching

Fetching from the remote repository will bring in its branches and their respective commits. These are stored in your local repository under special branches.

$ git fetch upstream
# Grab the upstream remote's branches
remote: Counting objects: 75, done.
remote: Compressing objects: 100% (53/53), done.
remote: Total 62 (delta 27), reused 44 (delta 9)
Unpacking objects: 100% (62/62), done.
From https://github.com/otheruser/repo
 * [new branch]      master     -> upstream/master

We now have the upstream's master branch stored in a local branch, upstream/master

$ git branch -va
# List all local and remote-tracking branches
* master                  a422352 My local commit
  remotes/origin/HEAD     -> origin/master
  remotes/origin/master   a422352 My local commit
  remotes/upstream/master 5fdff0f Some upstream commit

Merging

Now that we have fetched the upstream repository, we want to merge its changes into our local branch. This will bring that branch into sync with the upstream, without losing our local changes.

$ git checkout master
# Check out our local master branch
Switched to branch 'master'

$ git merge upstream/master
# Merge upstream's master into our own
Updating a422352..5fdff0f
Fast-forward
 README                    |    9 -------
 README.md                 |    7 ++++++
 2 files changed, 7 insertions(+), 9 deletions(-)
 delete mode 100644 README
 create mode 100644 README.md

If your local branch didn't have any unique commits, git will instead perform a "fast-forward":

$ git merge upstream/master
Updating 34e91da..16c56ad
Fast-forward
 README.md                 |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

Tip: If you want to update your repository on GitHub, follow the instructions here

Fastest way to compute entropy in Python

Uniformly distributed data (high entropy):

s=range(0,256)

Shannon entropy calculation step by step:

import collections
import math

# calculate probability for each byte as number of occurrences / array length
probabilities = [n_x/len(s) for x,n_x in collections.Counter(s).items()]
# [0.00390625, 0.00390625, 0.00390625, ...]

# calculate per-character entropy fractions
e_x = [-p_x*math.log(p_x,2) for p_x in probabilities]
# [0.03125, 0.03125, 0.03125, ...]

# sum fractions to obtain Shannon entropy
entropy = sum(e_x)
>>> entropy 
8.0

One-liner (assuming import collections):

def H(s): return sum([-p_x*math.log(p_x,2) for p_x in [n_x/len(s) for x,n_x in collections.Counter(s).items()]])

A proper function:

import collections
import math

def H(s):
    probabilities = [n_x/len(s) for x,n_x in collections.Counter(s).items()]
    e_x = [-p_x*math.log(p_x,2) for p_x in probabilities]    
    return sum(e_x)

Test cases - English text taken from CyberChef entropy estimator:

>>> H(range(0,256))
8.0
>>> H(range(0,64))
6.0
>>> H(range(0,128))
7.0
>>> H([0,1])
1.0
>>> H('Standard English text usually falls somewhere between 3.5 and 5')
4.228788210509104

How to detect orientation change in layout in Android?

In case this is of use to some newer dev's because its not specified above. Just to be very explicit:

You need two things if using onConfigurationChanged:

  1. An onConfigurationChanged method in your Activity Class

  2. Specify in your manifest which configuration changes will be handled by your onConfigurationChanged method

The manifest snippet in the above answers, while no doubt correct for the particular app that manifest belongs to, is NOT exactly what you need to add in your manifest to trigger the onConfigurationChanged method in your Activity Class. i.e. the below manifest entry may not be correct for your app.

<activity name= ".MainActivity" android:configChanges="orientation|screenSize"/>

In the above manifest entry, there are various Android actions for android:configChanges="" which can trigger the onCreate in your Activity lifecycle.

This is very important - The ones NOT Specified in the manifest are the ones that trigger your onCreate and The ones specified in the manifest are the ones that trigger your onConfigurationChanged method in your Activity Class.

So you need to identify which config changes you need to handle yourself. For the Android Encyclopedically Challenged like me, I used the quick hints pop-out in Android Studio and added in almost every possible configuration option. Listing all of these basically said that I would handle everything and onCreate will never be called due to configurations.

<activity name= ".MainActivity" android:configChanges="screenLayout|touchscreen|mnc|mcc|density|uiMode|fontScale|orientation|keyboard|layoutDirection|locale|navigation|smallestScreenSize|keyboardHidden|colorMode|screenSize"/>

Now obviously I don't want to handle everything, so I began eliminating the above options one at a time. Re-building and testing my app after each removal.

Another important point: If there is just one configuration option being handled automatically that triggers your onCreate (You do not have it listed in your manifest above), then it will appear like onConfigurationChanged is not working. You must put all relevant ones into your manifest.

I ended up with 3 that were triggering onCreate originally, then I tested on an S10+ and I was still getting the onCreate, so I had to do my elimination exercise again and I also needed the |screenSize. So test on a selection of platforms.

<activity name= ".MainActivity" android:configChanges="screenLayout|uiMode|orientation|screenSize"/>

So my suggestion, although I'm sure someone can poke holes in this:

  1. Add your onConfigurationChanged method in your Activity Class with a TOAST or LOG so you can see when its working.

  2. Add all possible configuration options to your manifest.

  3. Confirm your onConfigurationChanged method is working by testing your app.

  4. Remove each config option from your manifest file one at a time, testing your app after each.

  5. Test on as large a variety of devices as possible.

  6. Do not copy/paste my snippet above to your manifest file. Android updates change the list, so use the pop-out Android Studio hints to make sure you get them all.

I hope this saves someone some time.

My onConfigurationChanged method just for info below. onConfigurationChanged is called in the lifecycle after the new orientation is available, but before the UI has been recreated. Hence my first if to check the orientation works correctly, and then the 2nd nested if to look at the visibility of my UI ImageView also works correctly.

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            pokerCardLarge = findViewById(R.id.pokerCardLgImageView);

            if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
                Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
                pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
                pokerCardLarge.setImageBitmap(image);
            }

        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            pokerCardLarge = findViewById(R.id.pokerCardLgImageView);

            if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
                Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
                pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
                pokerCardLarge.setImageBitmap(image);
            }

        }
    }

What is difference between png8 and png24

From the Web Designer’s Guide to PNG Image Format

PNG-8 and PNG-24

There are two PNG formats: PNG-8 and PNG-24. The numbers are shorthand for saying "8-bit PNG" or "24-bit PNG." Not to get too much into technicalities — because as a web designer, you probably don’t care — 8-bit PNGs mean that the image is 8 bits per pixel, while 24-bit PNGs mean 24 bits per pixel.

To sum up the difference in plain English: Let’s just say PNG-24 can handle a lot more color and is good for complex images with lots of color such as photographs (just like JPEG), while PNG-8 is more optimized for things with simple colors, such as logos and user interface elements like icons and buttons.

Another difference is that PNG-24 natively supports alpha transparency, which is good for transparent backgrounds. This difference is not 100% true because Adobe products’ Save for Web command allows PNG-8 with alpha transparency.

Rails select helper - Default selected value, how?

If try to print the f object, then you will see that there is f.object that can be probed for getting the selected item (applicable for all rails version > 2.3)

logger.warn("f #{f.object.inspect}")

so, use the following script to get the proper selected option:

:selected => f.object.your_field 

When does a cookie with expiration time 'At end of session' expire?

Just to correct mingos' answer:

If you set the expiration time to 0, the cookie won't be created at all. I've tested this on Google Chrome at least, and when set to 0 that was the result. The cookie, I guess, expires immediately after creation.

To set a cookie so it expires at the end of the browsing session, simply OMIT the expiration parameter altogether.

Example:

Instead of:

document.cookie = "cookie_name=cookie_value; 0; path=/";

Just write:

document.cookie = "cookie_name=cookie_value; path=/";

Using Mockito's generic "any()" method

As I needed to use this feature for my latest project (at one point we updated from 1.10.19), just to keep the users (that are already using the mockito-core version 2.1.0 or greater) up to date, the static methods from the above answers should be taken from ArgumentMatchers class:

import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.any;

Please keep this in mind if you are planning to keep your Mockito artefacts up to date as possibly starting from version 3, this class may no longer exist:

As per 2.1.0 and above, Javadoc of org.mockito.Matchers states:

Use org.mockito.ArgumentMatchers. This class is now deprecated in order to avoid a name clash with Hamcrest * org.hamcrest.Matchers class. This class will likely be removed in version 3.0.

I have written a little article on mockito wildcards if you're up for further reading.

How to loop through an array of objects in swift

You can try using the simple NSArray in syntax for iterating over the array in swift which makes for shorter code. The following is working for me:

class ModelAttachment {
    var id: String?
    var url: String?
    var thumb: String?
}

var modelAttachementObj = ModelAttachment()
modelAttachementObj.id = "1"
modelAttachementObj.url = "http://www.google.com"
modelAttachementObj.thumb = "thumb"

var imgs: Array<ModelAttachment> = [modelAttachementObj]

for img in imgs  {
    let url = img.url
    NSLog(url!)
}

See docs here

How do I get the path of the current executed file in Python?

import os
current_file_path=os.path.dirname(os.path.realpath('__file__'))

How to add hyperlink in JLabel?

I'd like to offer yet another solution. It's similar to the already proposed ones as it uses HTML-code in a JLabel, and registers a MouseListener on it, but it also displays a HandCursor when you move the mouse over the link, so the look&feel is just like what most users would expect. If browsing is not supported by the platform, no blue, underlined HTML-link is created that could mislead the user. Instead, the link is just presented as plain text. This could be combined with the SwingLink class proposed by @dimo414.

public class JLabelLink extends JFrame {

private static final String LABEL_TEXT = "For further information visit:";
private static final String A_VALID_LINK = "http://stackoverflow.com";
private static final String A_HREF = "<a href=\"";
private static final String HREF_CLOSED = "\">";
private static final String HREF_END = "</a>";
private static final String HTML = "<html>";
private static final String HTML_END = "</html>";

public JLabelLink() {
    setTitle("HTML link via a JLabel");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    Container contentPane = getContentPane();
    contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));

    JLabel label = new JLabel(LABEL_TEXT);
    contentPane.add(label);

    label = new JLabel(A_VALID_LINK);
    contentPane.add(label);
    if (isBrowsingSupported()) {
        makeLinkable(label, new LinkMouseListener());
    }

    pack();
}

private static void makeLinkable(JLabel c, MouseListener ml) {
    assert ml != null;
    c.setText(htmlIfy(linkIfy(c.getText())));
    c.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
    c.addMouseListener(ml);
}

private static boolean isBrowsingSupported() {
    if (!Desktop.isDesktopSupported()) {
        return false;
    }
    boolean result = false;
    Desktop desktop = java.awt.Desktop.getDesktop();
    if (desktop.isSupported(Desktop.Action.BROWSE)) {
        result = true;
    }
    return result;

}

private static class LinkMouseListener extends MouseAdapter {

    @Override
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        JLabel l = (JLabel) evt.getSource();
        try {
            URI uri = new java.net.URI(JLabelLink.getPlainLink(l.getText()));
            (new LinkRunner(uri)).execute();
        } catch (URISyntaxException use) {
            throw new AssertionError(use + ": " + l.getText()); //NOI18N
        }
    }
}

private static class LinkRunner extends SwingWorker<Void, Void> {

    private final URI uri;

    private LinkRunner(URI u) {
        if (u == null) {
            throw new NullPointerException();
        }
        uri = u;
    }

    @Override
    protected Void doInBackground() throws Exception {
        Desktop desktop = java.awt.Desktop.getDesktop();
        desktop.browse(uri);
        return null;
    }

    @Override
    protected void done() {
        try {
            get();
        } catch (ExecutionException ee) {
            handleException(uri, ee);
        } catch (InterruptedException ie) {
            handleException(uri, ie);
        }
    }

    private static void handleException(URI u, Exception e) {
        JOptionPane.showMessageDialog(null, "Sorry, a problem occurred while trying to open this link in your system's standard browser.", "A problem occured", JOptionPane.ERROR_MESSAGE);
    }
}

private static String getPlainLink(String s) {
    return s.substring(s.indexOf(A_HREF) + A_HREF.length(), s.indexOf(HREF_CLOSED));
}

//WARNING
//This method requires that s is a plain string that requires
//no further escaping
private static String linkIfy(String s) {
    return A_HREF.concat(s).concat(HREF_CLOSED).concat(s).concat(HREF_END);
}

//WARNING
//This method requires that s is a plain string that requires
//no further escaping
private static String htmlIfy(String s) {
    return HTML.concat(s).concat(HTML_END);
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            new JLabelLink().setVisible(true);
        }
    });
}
}

How to copy java.util.list Collection

Use the ArrayList copy constructor, then sort that.

List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);

After making the copy, any changes to newList do not affect oldList.

Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

Determine the data types of a data frame's columns

For small data frames:

library(tidyverse)

as_tibble(mtcars)

gives you a print out of the df with data types

# A tibble: 32 x 11
     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
 * <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1  21       6  160    110  3.9   2.62  16.5     0     1     4     4
 2  21       6  160    110  3.9   2.88  17.0     0     1     4     4
 3  22.8     4  108     93  3.85  2.32  18.6     1     1     4     1

For large data frames:

glimpse(mtcars)

gives you a structured view of data types:

Observations: 32
Variables: 11
$ mpg  <dbl> 21.0, 21.0, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19.2, 17.8, 16.4, 17....
$ cyl  <dbl> 6, 6, 4, 6, 8, 6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 8, 8, 8, 8, ...
$ disp <dbl> 160.0, 160.0, 108.0, 258.0, 360.0, 225.0, 360.0, 146.7, 140.8, 167.6, 167.6...
$ hp   <dbl> 110, 110, 93, 110, 175, 105, 245, 62, 95, 123, 123, 180, 180, 180, 205, 215...
$ drat <dbl> 3.90, 3.90, 3.85, 3.08, 3.15, 2.76, 3.21, 3.69, 3.92, 3.92, 3.92, 3.07, 3.0...
$ wt   <dbl> 2.620, 2.875, 2.320, 3.215, 3.440, 3.460, 3.570, 3.190, 3.150, 3.440, 3.440...
$ qsec <dbl> 16.46, 17.02, 18.61, 19.44, 17.02, 20.22, 15.84, 20.00, 22.90, 18.30, 18.90...
$ vs   <dbl> 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, ...
$ am   <dbl> 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, ...
$ gear <dbl> 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4, 3, 3, 3, 3, 3, ...
$ carb <dbl> 4, 4, 1, 1, 2, 1, 4, 2, 2, 4, 4, 3, 3, 3, 4, 4, 4, 1, 2, 1, 1, 2, 2, 4, 2, ...

To get a list of the columns' data type (as said by @Alexandre above):

map(mtcars, class)

gives a list of data types:

$mpg
[1] "numeric"

$cyl
[1] "numeric"

$disp
[1] "numeric"

$hp
[1] "numeric"

To change data type of a column:

library(hablar)

mtcars %>% 
  convert(chr(mpg, am),
          int(carb))

converts columns mpg and am to character and the column carb to integer:

# A tibble: 32 x 11
   mpg     cyl  disp    hp  drat    wt  qsec    vs am     gear  carb
   <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <dbl> <int>
 1 21        6  160    110  3.9   2.62  16.5     0 1         4     4
 2 21        6  160    110  3.9   2.88  17.0     0 1         4     4
 3 22.8      4  108     93  3.85  2.32  18.6     1 1         4     1
 4 21.4      6  258    110  3.08  3.22  19.4     1 0         3     1

Disable sorting on last column when using jQuery DataTables

On DataTable 1.9.x:

$('.dataTable').dataTable({
    'aoColumnDefs': [{
        'bSortable': false,
        'aTargets': [-1], /* 1st colomn, starting from the right */
    }]
});

While on 1.10.x

$('.dataTable').dataTable({
    columnDefs: [{ orderable: false, "targets": -1 }] /* -1 = 1st colomn, starting from the right */
});

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

How to analyze a JMeter summary report?

Short explanation looks like:

  1. Sample - number of requests sent
  2. Avg - an Arithmetic mean for all responses (sum of all times / count)
  3. Minimal response time (ms)
  4. Maximum response time (ms)
  5. Deviation - see Standard Deviation article
  6. Error rate - percentage of failed tests
  7. Throughput - how many requests per second does your server handle. Larger is better.
  8. KB/Sec - self expalanatory
  9. Avg. Bytes - average response size

If you having troubles with interpreting results you could try BM.Sense results analysis service

Failed to resolve version for org.apache.maven.archetypes

I simple use below steps:

Create Maven project -> check checkobox -> "Create a simple project (skip archetype selection)"

It works for me

I want to multiply two columns in a pandas DataFrame and add the result into a new column

Since this question came up again, I think a good clean approach is using assign.

The code is quite expressive and self-describing:

df = df.assign(Value = lambda x: x.Prices * x.Amount * x.Action.replace({'Buy' : 1, 'Sell' : -1}))

How to select element using XPATH syntax on Selenium for Python?

HTML

<div id='a'>
  <div>
    <a class='click'>abc</a>
  </div>
</div>

You could use the XPATH as :

//div[@id='a']//a[@class='click']

output

<a class="click">abc</a>

That said your Python code should be as :

driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")

Check if enum exists in Java

Based on Jon Skeet answer i've made a class that permits to do it easily at work:

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import java.util.EnumSet;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * This permits to easily implement a failsafe implementation of the enums's valueOf
 * Better use it inside the enum so that only one of this object instance exist for each enum...
 * (a cache could solve this if needed)
 * </p>
 *
 * <p>
 * Basic usage exemple on an enum class called MyEnum:
 *
 *   private static final FailSafeValueOf<MyEnum> FAIL_SAFE = FailSafeValueOf.create(MyEnum.class);
 *   public static MyEnum failSafeValueOf(String enumName) {
 *       return FAIL_SAFE.valueOf(enumName);
 *   }
 *
 * </p>
 *
 * <p>
 * You can also use it outside of the enum this way:
 *   FailSafeValueOf.create(MyEnum.class).valueOf("EnumName");
 * </p>
 *
 * @author Sebastien Lorber <i>([email protected])</i>
 */
public class FailSafeValueOf<T extends Enum<T>> {

    private final Map<String,T> nameToEnumMap;

    private FailSafeValueOf(Class<T> enumClass) {
        Map<String,T> map = Maps.newHashMap();
        for ( T value : EnumSet.allOf(enumClass)) {
            map.put( value.name() , value);
        }
        nameToEnumMap = ImmutableMap.copyOf(map);
    }

    /**
     * Returns the value of the given enum element
     * If the 
     * @param enumName
     * @return
     */
    public T valueOf(String enumName) {
        return nameToEnumMap.get(enumName);
    }

    public static <U extends Enum<U>> FailSafeValueOf<U> create(Class<U> enumClass) {
        return new FailSafeValueOf<U>(enumClass);
    }

}

And the unit test:

import org.testng.annotations.Test;

import static org.testng.Assert.*;


/**
 * @author Sebastien Lorber <i>([email protected])</i>
 */
public class FailSafeValueOfTest {

    private enum MyEnum {
        TOTO,
        TATA,
        ;

        private static final FailSafeValueOf<MyEnum> FAIL_SAFE = FailSafeValueOf.create(MyEnum.class);
        public static MyEnum failSafeValueOf(String enumName) {
            return FAIL_SAFE.valueOf(enumName);
        }
    }

    @Test
    public void testInEnum() {
        assertNotNull( MyEnum.failSafeValueOf("TOTO") );
        assertNotNull( MyEnum.failSafeValueOf("TATA") );
        assertNull( MyEnum.failSafeValueOf("TITI") );
    }

    @Test
    public void testInApp() {
        assertNotNull( FailSafeValueOf.create(MyEnum.class).valueOf("TOTO") );
        assertNotNull( FailSafeValueOf.create(MyEnum.class).valueOf("TATA") );
        assertNull( FailSafeValueOf.create(MyEnum.class).valueOf("TITI") );
    }

}

Notice that i used Guava to make an ImmutableMap but actually you could use a normal map i think since the map is never returned...

Setting button text via javascript

Set the text of the button by setting the innerHTML

var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');
b.innerHTML = 'test value';

var wrapper = document.getElementById('divWrapper');
wrapper.appendChild(b);

http://jsfiddle.net/jUVpE/

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

In my case, I was doing this (wrong):

...
TextView content = new TextView(context);
for (Quote quote : favQuotes) {
  content.setText(quote.content);
...

instead of (good):

...
for (Quote quote : favQuotes) {
  TextView content = new TextView(context);
  content.setText(quote.content);
...

SQL Error: ORA-00942 table or view does not exist

Here is an answer: http://www.dba-oracle.com/concepts/synonyms.htm

An Oracle synonym basically allows you to create a pointer to an object that exists somewhere else. You need Oracle synonyms because when you are logged into Oracle, it looks for all objects you are querying in your schema (account). If they are not there, it will give you an error telling you that they do not exist.

How to Set Opacity (Alpha) for View in Android

I've run into this problem with ICS/JB because the default buttons for the Holo theme consist of images that are slightly transparent. For a background this is especially noticeable.

Gingerbread vs. ICS+:

Gingerbread ICS

Copying over all of the drawable states and images for each resolution and making the transparent images solid is a pain, so I've opted for a dirtier solution: wrap the button in a holder that has a white background. Here's a crude XML drawable (ButtonHolder) which does exactly that:

Your XML file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              style="@style/Content">
  <RelativeLayout style="@style/ButtonHolder">
      <Button android:id="@+id/myButton"
              style="@style/Button"
              android:text="@string/proceed"/>
    </RelativeLayout>
</LinearLayout>

ButtonHolder.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape android:shape="rectangle">
      <solid android:color="@color/white"/>
    </shape>
  </item>

</layer-list>

styles.xml

.
.
.      
  <style name="ButtonHolder">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:background">@drawable/buttonholder</item>
  </style>

  <style name="Button" parent="@android:style/Widget.Button">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:textStyle">bold</item>
  </style>
.
.
.

However, this results in a white border because the Holo button images include margins to account for the pressed space:

Too much white Too much white pressed

So the solution is to give the white background a margin (4dp worked for me) and rounded corners (2dp) to completely hide the white yet make the button solid:

ButtonHolder.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

  <item>
    <shape android:shape="rectangle">
      <solid android:color="@android:color/transparent"/>
    </shape>
  </item>

  <item android:top="4dp" android:bottom="4dp" android:left="4dp" android:right="4dp">
    <shape android:shape="rectangle">
      <solid android:color="@color/white"/>
      <corners android:radius="2dp" />
    </shape>
  </item>

</layer-list>

The final result looks like this:

No white No white pressed

You should target this style for v14+, and tweak or exclude it for Gingerbread/Honeycomb because their native button image sizes are different from ICS and JB's (e.g. this exact style behind a Gingerbread button results in a small bit of white below the button).

Plotting with C#

FWIW, you probably want to look at F# instead of C# in the context of technical computing because F# is specifically designed for that purpose. However, I developed my own commercial plotting library because I was not satisfied with anything freely available on .NET.

What is the HTML unicode character for a "tall" right chevron?

Use '›'

&rsaquo; -> single right angle quote. For single left angle quote, use &lsaquo;

Check if a Class Object is subclass of another Class Object in Java

You want this method:

boolean isList = List.class.isAssignableFrom(myClass);

where in general, List (above) should be replaced with superclass and myClass should be replaced with subclass

From the JavaDoc:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

Reference:


Related:

a) Check if an Object is an instance of a Class or Interface (including subclasses) you know at compile time:

boolean isInstance = someObject instanceof SomeTypeOrInterface;

Example:

assertTrue(Arrays.asList("a", "b", "c") instanceof List<?>);

b) Check if an Object is an instance of a Class or Interface (including subclasses) you only know at runtime:

Class<?> typeOrInterface = // acquire class somehow
boolean isInstance = typeOrInterface.isInstance(someObject);

Example:

public boolean checkForType(Object candidate, Class<?> type){
    return type.isInstance(candidate);
}

How to programmatically set style attribute in a view

At runtime, you know what style you want your button to have. So beforehand, in xml in the layout folder, you can have all ready to go buttons with the styles you need. So in the layout folder, you might have a file named: button_style_1.xml. The contents of that file might look like:

<?xml version="1.0" encoding="utf-8"?>
<Button
    android:id="@+id/styleOneButton"
    style="@style/FirstStyle" />

If you are working with fragments, then in onCreateView you inflate that button, like:

Button firstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);

where container is the ViewGroup container associated with the onCreateView method you override when creating your fragment.

Need two more such buttons? You create them like this:

Button secondFirstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);
Button thirdFirstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);

You can customize those buttons:

secondFirstStyleBtn.setText("My Second");
thirdFirstStyleBtn.setText("My Third");

Then you add your customized, stylized buttons to the layout container you also inflated in the onCreateView method:

_stylizedButtonsContainer = (LinearLayout) rootView.findViewById(R.id.stylizedButtonsContainer);

_stylizedButtonsContainer.addView(firstStyleBtn);
_stylizedButtonsContainer.addView(secondFirstStyleBtn);
_stylizedButtonsContainer.addView(thirdFirstStyleBtn);

And that's how you can dynamically work with stylized buttons.

Checkout old commit and make it a new commit

This is exactly what I wanted to do. I was not sure of the previous command git cherry-pick C, it sounds nice but it seems you do this to get changes from another branch but not on same branch, has anyone tried it?

So I did something else which also worked : I got the files I wanted back from the old commit file by file

git checkout <commit-hash> <filename>

ex : git checkout 08a6497b76ad098a5f7eda3e4ec89e8032a4da51 file.css

-> this takes the files as they were from the old commit

Then I did my changes. And I committed again.

git status (to check which files were modified)
git diff (to check the changes you made)
git add .
git commit -m "my message"

I checked my history with git log, and I still have my history along with my new changes made from the old files. And I could push too.

Note that to go back to the state you want you need to put the hash of the commit before the unwanted changes. Also make sure you don't have uncommitted changes before you do that.

Non-invocable member cannot be used like a method?

It have happened because you are trying to use the property "OffenceBox.Text" like a method. Try to remove parenteses from OffenceBox.Text() and it'll work fine.

Remember that you cannot create a method and a property with the same name in a class.


By the way, some alias could confuse you, since sometimes it's method or property, e.g: "Count" alias:


Namespace: System.Linq

using System.Linq

namespace Teste
{
    public class TestLinq
    {
        public return Foo()
        {
            var listX = new List<int>();
            return listX.Count(x => x.Id == 1);
        }
    }
}


Namespace: System.Collections.Generic

using System.Collections.Generic

namespace Teste
{
    public class TestList
    {
        public int Foo()
        {
            var listX = new List<int>();
            return listX.Count;
        }
    }
}

Non-static variable cannot be referenced from a static context

To be able to access them from your static methods they need to be static member variables, like this:

public class MyProgram7 {
  static Scanner scan = new Scanner(System.in);
  static int compareCount = 0;
  static int low = 0;
  static int high = 0;
  static int mid = 0;  
  static int key = 0;  
  static Scanner temp;  
  static int[]list;  
  static String menu, outputString;  
  static int option = 1;  
  static boolean found = false;

  public static void main (String[]args) throws IOException {
  ...

anaconda/conda - install a specific package version

To install a specific package:

conda install <pkg>=<version>

eg:

conda install matplotlib=1.4.3

Getting input values from text box

You will notice you have no value attr in the input tags.
Also, although not shown, make sure the Javascript is run after the html is in place.

SQL query with avg and group by

As I understand, you want the average value for each id at each pass. The solution is

SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;

Regex to replace multiple spaces with a single space

Comprehensive unencrypted answer for newbies et al.

This is for all of the dummies like me who test the scripts written by some of you guys which do not work.

The following 3 examples are the steps I took to remove special characters AND extra spaces on the following 3 websites (all of which work perfectly) {1. EtaVisa.com 2. EtaStatus.com 3. Tikun.com} so I know that these work perfectly.

We have chained these together with over 50 at a time and NO problems.

// This removed special characters + 0-9 and allows for just letters (upper and LOWER case)

function NoDoublesPls1()
{
var str=document.getElementById("NoDoubles1");
var regex=/[^a-z]/gi;
str.value=str.value.replace(regex ,"");
}

// This removed special characters and allows for just letters (upper and LOWER case) and 0-9 AND spaces

function NoDoublesPls2()
{
var str=document.getElementById("NoDoubles2");
var regex=/[^a-z 0-9]/gi;
str.value=str.value.replace(regex ,"");
}

// This removed special characters and allows for just letters (upper and LOWER case) and 0-9 AND spaces // The .replace(/\s\s+/g, " ") at the end removes excessive spaces // when I used single quotes, it did not work.

function NoDoublesPls3()
{    var str=document.getElementById("NoDoubles3");
var regex=/[^a-z 0-9]/gi;
str.value=str.value.replace(regex ,"") .replace(/\s\s+/g, " ");
}

::NEXT:: Save #3 as a .js // I called mine NoDoubles.js

::NEXT:: Include your JS into your page

 <script language="JavaScript" src="js/NoDoubles.js"></script>

Include this in your form field:: such as

<INPUT type="text" name="Name"
     onKeyUp="NoDoublesPls3()" onKeyDown="NoDoublesPls3()" id="NoDoubles3"/>

So that it looks like this

<INPUT type="text" name="Name" onKeyUp="NoDoublesPls3()" onKeyDown="NoDoublesPls3()" id="NoDoubles3"/>

This will remove special characters, allow for single spaces and remove extra spaces.

How to make a list of n numbers in Python and randomly select any number?

You don't need to count stuff if you want to pick a random element. Just use random.choice() and pass your iterable:

import random
items = ['foo', 'bar', 'baz']
print random.choice(items)

If you really have to count them, use random.randint(1, count+1).

How to delete multiple rows in SQL where id = (x to y)

You can use BETWEEN:

DELETE FROM table
where id between 163 and 265

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

maybe whole database + tables + fields should have the same charset??!

i.e.

CREATE TABLE `politicas` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Nombre` varchar(250) CHARACTER SET utf8 NOT NULL,
  -------------------------------------^here!!!!!!!!!!!
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
  -------------------------------------------------^here!!!!!!!!!

How to use SearchView in Toolbar Android

If you would like to setup the search facility inside your Fragment, just add these few lines:

Step 1 - Add the search field to you toolbar:

<item
    android:id="@+id/action_search"
    android:icon="@android:drawable/ic_menu_search"
    app:showAsAction="always|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView"
    android:title="Search"/>

Step 2 - Add the logic to your onCreateOptionsMenu()

import android.support.v7.widget.SearchView; // not the default !

@Override
public boolean onCreateOptionsMenu( Menu menu) {
    getMenuInflater().inflate( R.menu.main, menu);

    MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
    searchView = (SearchView) myActionMenuItem.getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            // Toast like print
            UserFeedback.show( "SearchOnQueryTextSubmit: " + query);
            if( ! searchView.isIconified()) {
                searchView.setIconified(true);
            }
            myActionMenuItem.collapseActionView();
            return false;
        }
        @Override
        public boolean onQueryTextChange(String s) {
            // UserFeedback.show( "SearchOnQueryTextChanged: " + s);
            return false;
        }
    });
    return true;
}

Explanation of the UML arrows

enter image description here

enter image description here

I think these pictures are understandable.

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

design a stack such that getMinimum( ) should be O(1)

I am posting the complete code here to find min and max in a given stack.

Time complexity will be O(1)..

package com.java.util.collection.advance.datastructure;

/**
 * 
 * @author vsinha
 *
 */
public abstract interface Stack<E> {

    /**
     * Placing a data item on the top of the stack is called pushing it
     * @param element
     * 
     */
    public abstract void push(E element);


    /**
     * Removing it from the top of the stack is called popping it
     * @return the top element
     */
    public abstract E pop();

    /**
     * Get it top element from the stack and it 
     * but the item is not removed from the stack, which remains unchanged
     * @return the top element
     */
    public abstract E peek();

    /**
     * Get the current size of the stack.
     * @return
     */
    public abstract int size();


    /**
     * Check whether stack is empty of not.
     * @return true if stack is empty, false if stack is not empty
     */
    public abstract boolean empty();



}



package com.java.util.collection.advance.datastructure;

@SuppressWarnings("hiding")
public abstract interface MinMaxStack<Integer> extends Stack<Integer> {

    public abstract int min();

    public abstract int max();

}


package com.java.util.collection.advance.datastructure;

import java.util.Arrays;

/**
 * 
 * @author vsinha
 *
 * @param <E>
 */
public class MyStack<E> implements Stack<E> {

    private E[] elements =null;
    private int size = 0;
    private int top = -1;
    private final static int DEFAULT_INTIAL_CAPACITY = 10;


    public MyStack(){
        // If you don't specify the size of stack. By default, Stack size will be 10
        this(DEFAULT_INTIAL_CAPACITY);
    }

    @SuppressWarnings("unchecked")
    public MyStack(int intialCapacity){
        if(intialCapacity <=0){
            throw new IllegalArgumentException("initial capacity can't be negative or zero");
        }
        // Can't create generic type array
        elements =(E[]) new Object[intialCapacity];
    }

    @Override
    public void push(E element) {
        ensureCapacity();
        elements[++top] = element;
        ++size;
    }

    @Override
    public E pop() {
        E element = null;
        if(!empty()) {
            element=elements[top];
            // Nullify the reference
            elements[top] =null;
            --top;
            --size;
        }
        return element;
    }

    @Override
    public E peek() {
        E element = null;
        if(!empty()) {
            element=elements[top];
        }
        return element;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean empty() {
        return size == 0;
    }

    /**
     * Increases the capacity of this <tt>Stack by double of its current length</tt> instance, 
     * if stack is full 
     */
    private void ensureCapacity() {
        if(size != elements.length) {
            // Don't do anything. Stack has space.
        } else{
            elements = Arrays.copyOf(elements, size *2);
        }
    }

    @Override
    public String toString() {
        return "MyStack [elements=" + Arrays.toString(elements) + ", size="
                + size + ", top=" + top + "]";
    }


}


package com.java.util.collection.advance.datastructure;

/**
 * Time complexity will be O(1) to find min and max in a given stack.
 * @author vsinha
 *
 */
public class MinMaxStackFinder extends MyStack<Integer> implements MinMaxStack<Integer> {

    private MyStack<Integer> minStack;

    private MyStack<Integer> maxStack;

    public MinMaxStackFinder (int intialCapacity){
        super(intialCapacity);
        minStack =new MyStack<Integer>();
        maxStack =new MyStack<Integer>();

    }
    public void push(Integer element) {
        // Current element is lesser or equal than min() value, Push the current element in min stack also.
        if(!minStack.empty()) {
            if(min() >= element) {
                minStack.push(element);
            }
        } else{
            minStack.push(element);
        }
        // Current element is greater or equal than max() value, Push the current element in max stack also.
        if(!maxStack.empty()) {
            if(max() <= element) {
                maxStack.push(element);
            }
        } else{
            maxStack.push(element);
        }
        super.push(element);
    }


    public Integer pop(){
        Integer curr = super.pop();
        if(curr !=null) {
            if(min() == curr) {
                minStack.pop();
            } 

            if(max() == curr){
                maxStack.pop();
            }
        }
        return curr;
    }


    @Override
    public int min() {
        return minStack.peek();
    }

    @Override
    public int max() {
        return maxStack.peek();
    }


    @Override
    public String toString() {
        return super.toString()+"\nMinMaxStackFinder [minStack=" + minStack + "\n maxStack="
                + maxStack + "]" ;
    }




}

// You can use the below program to execute it.

package com.java.util.collection.advance.datastructure;

import java.util.Random;

public class MinMaxStackFinderApp {

    public static void main(String[] args) {
        MinMaxStack<Integer> stack =new MinMaxStackFinder(10);
        Random random =new Random();
        for(int i =0; i< 10; i++){
            stack.push(random.nextInt(100));
        }
        System.out.println(stack);
        System.out.println("MAX :"+stack.max());
        System.out.println("MIN :"+stack.min());

        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();

        System.out.println(stack);
        System.out.println("MAX :"+stack.max());
        System.out.println("MIN :"+stack.min());
    }
}

Let me know if you are facing any issue

Thanks, Vikash

Error CS2001: Source file '.cs' could not be found

I had this problem, too.

Possible causes in my case: I had deleted a duplicated view twice and a view model. I reverted one of the deletes and then the InitializeComponent error appeared. I took these steps.

  1. I checked all of the solutions mentioned on this question. The class name and build action were correct.
  2. I Cleaned my Solution and rebuilt. Another error appeared. "Error CS2001: Source file '.cs' could not be found"
  3. I found this answer and followed the steps.
  4. I reloaded the project and cleaned/rebuilt again.
  5. My solution builds without errors and my application works now.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

For users which have flavors in the project and found this thread:

Notice, that if your module dependency has different flavors, you should use one of the strategies:

  1. Module that tightens dependencies should have the same flavors and dimensions as the dependency module
  2. You should explicitly indicate which configuration you target in the module

Like that:

dependencies {
    compile project(path: ':module', configuration:'alphaDebug') 
}

JavaScript string and number conversion

parseInt is misfeatured like scanf:

parseInt("12 monkeys", 10) is a number with value '12'
+"12 monkeys"              is a number with value 'NaN'
Number("12 monkeys")       is a number with value 'NaN'

NULL value for int in Update statement

By using NULL without any quotes.

UPDATE `tablename` SET `fieldName` = NULL;

Pretty print in MongoDB shell as default

Oh so i guess .pretty() is equal to:

db.collection.find().forEach(printjson);

How to open spss data files in excel?

I help develop the Colectica for Excel addin, which opens SPSS and Stata data files in Excel. This does not require ODBC configuration; it reads the file and then inserts the data and metadata into your worksheet.

The addin is downloadable from http://www.colectica.com/software/colecticaforexcel

Raw SQL Query without DbSet - Entity Framework Core

For now, until there is something new from EFCore I would used a command and map it manually

  using (var command = this.DbContext.Database.GetDbConnection().CreateCommand())
  {
      command.CommandText = "SELECT ... WHERE ...> @p1)";
      command.CommandType = CommandType.Text;
      var parameter = new SqlParameter("@p1",...);
      command.Parameters.Add(parameter);

      this.DbContext.Database.OpenConnection();

      using (var result = command.ExecuteReader())
      {
         while (result.Read())
         {
            .... // Map to your entity
         }
      }
  }

Try to SqlParameter to avoid Sql Injection.

 dbData.Product.FromSql("SQL SCRIPT");

FromSql doesn't work with full query. Example if you want to include a WHERE clause it will be ignored.

Some Links:

Executing Raw SQL Queries using Entity Framework Core

Raw SQL Queries

Changing SQL Server collation to case insensitive from case sensitive?

You can do that but the changes will affect for new data that is inserted on the database. On the long run follow as suggested above.

Also there are certain tricks you can override the collation, such as parameters for stored procedures or functions, alias data types, and variables are assigned the default collation of the database. To change the collation of an alias type, you must drop the alias and re-create it.

You can override the default collation of a literal string by using the COLLATE clause. If you do not specify a collation, the literal is assigned the database default collation. You can use DATABASEPROPERTYEX to find the current collation of the database.

You can override the server, database, or column collation by specifying a collation in the ORDER BY clause of a SELECT statement.

How do I send a file as an email attachment using Linux command line?

Another alternative - Swaks (Swiss Army Knife for SMTP).

swaks -tls \
    --to ${MAIL_TO} \
    --from ${MAIL_FROM} \
    --server ${MAIL_SERVER} \
    --auth LOGIN \
    --auth-user ${MAIL_USER} \
    --auth-password ${MAIL_PASSWORD} \
    --header "Subject: $MAIL_SUBJECT" \
    --header "Content-Type: text/html; charset=UTF-8" \
    --body "$MESSAGE" \
    --attach mysqldbbackup.sql

Escape quotes in JavaScript

The problem is that HTML doesn't recognize the escape character. You could work around that by using the single quotes for the HTML attribute and the double quotes for the onclick.

<a href="#" onclick='DoEdit("Preliminary Assessment \"Mini\""); return false;'>edit</a>

error: resource android:attr/fontVariationSettings not found

Usually it's because of sdk versions and/or dependencies.

For Cordova developers, put your dependencies settings in "project.properties" file under CORDOVA_PROJECT_ROOT/platforms/android/ folder, like this:

target=android-26
android.library.reference.1=CordovaLib
android.library.reference.2=app
cordova.system.library.1=com.android.support:support-v4:26.1.0
cordova.gradle.include.2=cordova-plugin-googlemaps/app-tbxml-android.gradle
cordova.system.library.3=com.android.support:support-core-utils:26.1.0
cordova.system.library.4=com.google.android.gms:play-services-maps:15.0.0
cordova.system.library.5=com.google.android.gms:play-services-location:15.0.0

So if you use CLI "cordova build", it will overwrite the dependencies section:

dependencies {
    implementation fileTree(dir: 'libs', include: '*.jar')
    // SUB-PROJECT DEPENDENCIES START 
   /* section being overwritten by cordova, referencing project.properties */
...
    // SUB-PROJECT DEPENDENCIES END
}

If you are using proper libraries and its versions in project.properties, you should be fine.

How do I get a plist as a Dictionary in Swift?

It is best to use native dictionaries and arrays because they have been optimized for use with swift. That being said you can use NS... classes in swift and I think this situation warrants that. Here is how you would implement it:

var path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist")
var dict = NSDictionary(contentsOfFile: path)

So far (in my opinion) this is the easiest and most efficient way to access a plist, but in the future I expect that apple will add more functionality (such as using plist) into native dictionaries.

Convert nullable bool? to bool

This is an interesting variation on the theme. At first and second glances you would assume the true branch is taken. Not so!

bool? flag = null;
if (!flag ?? true)
{
    // false branch
}
else
{
    // true branch
}

The way to get what you want is to do this:

if (!(flag ?? true))
{
    // false branch
}
else
{
    // true branch
}

Rename multiple columns by names

Another solution for dataframes which are not too large is (building on @thelatemail answer):

x <- data.frame(q=1,w=2,e=3)

> x
  q w e
1 1 2 3

colnames(x) <- c("A","w","B")

> x
  A w B
1 1 2 3

Alternatively, you can also use:

names(x) <- c("C","w","D")

> x
  C w D
1 1 2 3

Furthermore, you can also rename a subset of the columnnames:

names(x)[2:3] <- c("E","F")

> x
  C E F
1 1 2 3

C# Numeric Only TextBox Control

this way is right with me:

private void textboxNumberic_KeyPress(object sender, KeyPressEventArgs e)
{
     const char Delete = (char)8;
     e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}

UITableView with fixed section headers

You can also set the tableview's bounces property to NO. This will keep the section headers non-floating/static, but then you also lose the bounce property of the tableview.

Flexbox not giving equal width to elements

To create elements with equal width using Flex, you should set to your's child (flex elements):

flex-basis: 25%;
flex-grow: 0;

It will give to all elements in row 25% width. They will not grow and go one by one.

scipy.misc module has no attribute imread?

For Python 3, it is best to use imread in matplotlib.pyplot:

from matplotlib.pyplot import imread

What is the default database path for MongoDB?

The Windows x64 installer shows the a path in the installer UI/wizard.

You can confirm which path it used later, by opening your mongod.cfg file. My mongod.cfg was located here C:\Program Files\MongoDB\Server\4.0\bin\mongod.cfg (change for your version of MongoDB!

When I opened my mongd.cfg I found this line, showing the default db path:

dbPath: C:\Program Files\MongoDB\Server\4.0\data

However, this caused an error when trying to run mongod, which was still expecting to find C:\data\db:

2019-05-05T09:32:36.084-0700 I STORAGE [initandlisten] exception in initAndListen: NonExistentPath: Data directory C:\data\db\ not found., terminating

You could pass mongod a --dbpath=... parameter. In my case:

mongod --dbpath="C:\Program Files\MongoDB\Server\4.0\data"

Bootstrap 3 Horizontal Divider (not in a dropdown)

As I found the default Bootstrap <hr/> size unsightly, here's some simple HTML and CSS to balance out the element visually:

HTML:

<hr class="half-rule"/>

CSS:

.half-rule { 
    margin-left: 0;
    text-align: left;
    width: 50%;
 }

Find a value in an array of objects in Javascript

This answer is good for typescript / Angular 2, 4, 5+

I got this answer with the help of @rujmah answer above. His answer brings in the array count... and then find's the value and replaces it with another value...

What this answer does is simply grabs the array name that might be set in another variable via another module / component... in this case the array I build had a css name of stay-dates. So what this does is extract that name and then allows me to set it to another variable and use it like so. In my case it was an html css class.

let obj = this.highlightDays.find(x => x.css); let index = this.highlightDays.indexOf(obj); console.log('here we see what hightlightdays is ', obj.css); let dayCss = obj.css;

Why are my PowerShell scripts not running?

On Windows 10: Click change security property of myfile.ps1 and change "allow access" by right click / properties on myfile.ps1

How to redirect user's browser URL to a different page in Nodejs?

OP: "I would love if there were a way to do it where I didn't have to know the host address..."

response.writeHead(301, {
  Location: "http" + (request.socket.encrypted ? "s" : "") + "://" + 
    request.headers.host + newRoom
});
response.end();

How do I make a <div> move up and down when I'm scrolling the page?

Here is the Jquery Code

$(document).ready(function () {
     var el = $('#Container');
        var originalelpos = el.offset().top; // take it where it originally is on the page

        //run on scroll
        $(window).scroll(function () {
            var el = $('#Container'); // important! (local)
            var elpos = el.offset().top; // take current situation
            var windowpos = $(window).scrollTop();
            var finaldestination = windowpos + originalelpos;
            el.stop().animate({ 'top': finaldestination }, 1000);
        });
    });

Send Outlook Email Via Python?

For a solution that uses outlook see TheoretiCAL's answer below.

Otherwise, use the smtplib that comes with python. Note that this will require your email account allows smtp, which is not necessarily enabled by default.

SERVER = "smtp.example.com"
FROM = "[email protected]"
TO = ["listOfEmails"] # must be a list

SUBJECT = "Subject"
TEXT = "Your Text"

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()

EDIT: this example uses reserved domains like described in RFC2606

SERVER = "smtp.example.com"
FROM = "[email protected]"
TO = ["[email protected]"] # must be a list

SUBJECT = "Hello!"
TEXT = "This is a test of emailing through smtp of example.com."

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.login("MrDoe", "PASSWORD")
server.sendmail(FROM, TO, message)
server.quit()

For it to actually work with gmail, Mr. Doe will need to go to the options tab in gmail and set it to allow smtp connections.

Note the addition of the login line to authenticate to the remote server. The original version does not include this, an oversight on my part.

What's the difference between eval, exec, and compile?

  1. exec is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example:

     exec('print(5)')           # prints 5.
     # exec 'print 5'     if you use Python 2.x, nor the exec neither the print is a function there
     exec('print(5)\nprint(6)')  # prints 5{newline}6.
     exec('if True: print(6)')  # prints 6.
     exec('5')                 # does nothing and returns nothing.
    
  2. eval is a built-in function (not a statement), which evaluates an expression and returns the value that expression produces. Example:

     x = eval('5')              # x <- 5
     x = eval('%d + 6' % x)     # x <- 11
     x = eval('abs(%d)' % -100) # x <- 100
     x = eval('x = 5')          # INVALID; assignment is not an expression.
     x = eval('if 1: x = 4')    # INVALID; if is a statement, not an expression.
    
  3. compile is a lower level version of exec and eval. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:

  4. compile(string, '', 'eval') returns the code object that would have been executed had you done eval(string). Note that you cannot use statements in this mode; only a (single) expression is valid.

  5. compile(string, '', 'exec') returns the code object that would have been executed had you done exec(string). You can use any number of statements here.

  6. compile(string, '', 'single') is like the exec mode but expects exactly one expression/statement, eg compile('a=1 if 1 else 3', 'myf', mode='single')

Prevent screen rotation on Android

In your Manifest file, for each Activity that you want to lock the screen rotation add: if you want to lock it in horizontal mode:

<activity
        ...
        ...
        android:screenOrientation="landscape">

or if you want to lock it in vertical mode:

<activity
            ...
            ...
            android:screenOrientation="portrait">

Python 'list indices must be integers, not tuple"

To create list of lists, you need to separate them with commas, like this

coin_args = [
    ["pennies", '2.5', '50.0', '.01'],
    ["nickles", '5.0', '40.0', '.05'],
    ["dimes", '2.268', '50.0', '.1'],
    ["quarters", '5.67', '40.0', '.25']
]

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher

In my case(Bootstrap) the issue was, having the JQuery 3.0.0 which is also not fine, So using a version which is an earlier version like 2.2.4.

The Error i got was: Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3

Using any of these CDN below as the source would help if this is the case!

jQuery version 2.2.4:

http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.4.js

http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.4.min.js

Hope this helped at least someone!.. :)

Thank you!

Android: Proper Way to use onBackPressed() with Toast

You may also need to reset counter in onPause to prevent cases when user presses home or navigates away by some other means after first back press. Otherwise, I don't see an issue.

Convert Java Array to Iterable

I had the same problem and solved it like this:

final YourType[] yourArray = ...;
return new Iterable<YourType>() {
  public Iterator<YourType> iterator() {
     return Iterators.forArray(yourArray);   // Iterators is a Google guava utility
  }
}

The iterator itself is a lazy UnmodifiableIterator but that's exactly what I needed.

How do I replace multiple spaces with a single space in C#?

Consolodating other answers, per Joel, and hopefully improving slightly as I go:

You can do this with Regex.Replace():

string s = Regex.Replace (
    "   1  2    4 5", 
    @"[ ]{2,}", 
    " "
    );

Or with String.Split():

static class StringExtensions
{
    public static string Join(this IList<string> value, string separator)
    {
        return string.Join(separator, value.ToArray());
    }
}

//...

string s = "     1  2    4 5".Split (
    " ".ToCharArray(), 
    StringSplitOptions.RemoveEmptyEntries
    ).Join (" ");

tr:hover not working

tr:hover doesn't work in old browsers.

You can use jQuery for this:

.tr-hover
{  
  background-color:#fefefe;
}
$('.list1 tr').hover(function()
{
    $(this).addClass('tr-hover');
},function()
{
    $(this).removeClass('tr-hover');
});

How to get the return value from a thread in python?

In Python 3.2+, stdlib concurrent.futures module provides a higher level API to threading, including passing return values or exceptions from a worker thread back to the main thread:

import concurrent.futures

def foo(bar):
    print('hello {}'.format(bar))
    return 'foo'

with concurrent.futures.ThreadPoolExecutor() as executor:
    future = executor.submit(foo, 'world!')
    return_value = future.result()
    print(return_value)

How to make Firefox headless programmatically in Selenium with Python?

To invoke Firefox Browser headlessly, you can set the headless property through Options() class as follows:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.headless = True
driver = webdriver.Firefox(options=options, executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("http://google.com/")
print ("Headless Firefox Initialized")
driver.quit()

There's another way to accomplish headless mode. If you need to disable or enable the headless mode in Firefox, without changing the code, you can set the environment variable MOZ_HEADLESS to whatever if you want Firefox to run headless, or don't set it at all.

This is very useful when you are using for example continuous integration and you want to run the functional tests in the server but still be able to run the tests in normal mode in your PC.

$ MOZ_HEADLESS=1 python manage.py test # testing example in Django with headless Firefox

or

$ export MOZ_HEADLESS=1   # this way you only have to set it once
$ python manage.py test functional/tests/directory
$ unset MOZ_HEADLESS      # if you want to disable headless mode

Outro

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

Display QImage with QtGui

As far as I know, QPixmap is used for displaying images and QImage for reading them. There are QPixmap::convertFromImage() and QPixmap::fromImage() functions to convert from QImage.

Internal and external fragmentation

First of all the term fragmentation cues there's an entity divided into parts — fragments.

  • Internal fragmentation: Typical paper book is a collection of pages (text divided into pages). When a chapter's end isn't located at the end of page and new chapter starts from new page, there's a gap between those chapters and it's a waste of space — a chunk (page for a book) has unused space inside (internally) — "white space"

  • External fragmentation: Say you have a paper diary and you didn't write your thoughts sequentially page after page, but, rather randomly. You might end up with a situation when you'd want to write 3 pages in row, but you can't since there're no 3 clean pages one-by-one, you might have 15 clean pages in the diary totally, but they're not contiguous

How to get value of selected radio button?

If you are using the JQuery, please use the bellow snippet for group of radio buttons.

var radioBtValue= $('input[type=radio][name=radiobt]:checked').val();

how to remove css property using javascript?

You can also do this in jQuery by saying $(selector).css("zoom", "")

What are advantages of Artificial Neural Networks over Support Vector Machines?

We should also consider that the SVM system can be applied directly to non-metric spaces, such as the set of labeled graphs or strings. In fact, the internal kernel function can be generalized properly to virtually any kind of input, provided that the positive definiteness requirement of the kernel is satisfied. On the other hand, to be able to use an ANN on a set of labeled graphs, explicit embedding procedures must be considered.

Check if record exists from controller in Rails

When you call Business.where(:user_id => current_user.id) you will get an array. This Array may have no objects or one or many objects in it, but it won't be null. Thus the check == nil will never be true.

You can try the following:

if Business.where(:user_id => current_user.id).count == 0

So you check the number of elements in the array and compare them to zero.

or you can try:

if Business.find_by_user_id(current_user.id).nil?

this will return one or nil.

How to show/hide if variable is null

To clarify, the above example does work, my code in the example did not work for unrelated reasons.

If myvar is false, null or has never been used before (i.e. $scope.myvar or $rootScope.myvar never called), the div will not show. Once any value has been assigned to it, the div will show, except if the value is specifically false.

The following will cause the div to show:

$scope.myvar = "Hello World";

or

$scope.myvar = true;

The following will hide the div:

$scope.myvar = null;

or

$scope.myvar = false;

How to write one new line in Bitbucket markdown?

It's possible, as addressed in Issue #7396:

When you do want to insert a <br /> break tag using Markdown, you end a line with two or more spaces, then type return or Enter.

how to find host name from IP with out login to the host

You can do a reverse DNS lookup with host, too. Just give it the IP address as an argument:

$ host 192.168.0.10
server10 has address 192.168.0.10

How to create an HTTPS server in Node.js?

Found this question while googling "node https" but the example in the accepted answer is very old - taken from the docs of the current (v0.10) version of node, it should look like this:

var https = require('https');
var fs = require('fs');

var options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8000);

CSS customized scroll bar in div

Here's a webkit example which works for Chrome and Safari:

CSS:

::-webkit-scrollbar 
{
    width: 40px;
    background-color:#4F4F4F;
}

::-webkit-scrollbar-button:vertical:increment 
{
    height:40px;
    background-image: url(/Images/Scrollbar/decrement.png);
    background-size:39px 30px;
    background-repeat:no-repeat;
}

::-webkit-scrollbar-button:vertical:decrement 
{
    height:40px;
    background-image: url(/Images/Scrollbar/increment.png);    
    background-size:39px 30px;
    background-repeat:no-repeat;
}

Output:

enter image description here

How can I make space between two buttons in same div?

Put them inside btn-toolbar or some other container, not btn-group. btn-group joins them together. More info on Bootstrap documentation.

Edit: The original question was for Bootstrap 2.x, but the same is still valid for Bootstrap 3 and Bootstrap 4.

In Bootstrap 4 you will need to add appropriate margin to your groups using utility classes, such as mx-2.

Optional args in MATLAB functions

A good way of going about this is not to use nargin, but to check whether the variables have been set using exist('opt', 'var').

Example:

function [a] = train(x, y, opt)
    if (~exist('opt', 'var'))
        opt = true;
    end
end

See this answer for pros of doing it this way: How to check whether an argument is supplied in function call?

How can I debug a Perl script?

Note that the Perldebugger can also be invoked from the scripts shebang line, which is how I mostly use the -x flag you refer to, to debug shell scripts.

#! /usr/bin/perl -d

How do I make JavaScript beep?

I wrote a function to beep with the new Audio API.

var beep = (function () {
    var ctxClass = window.audioContext ||window.AudioContext || window.AudioContext || window.webkitAudioContext
    var ctx = new ctxClass();
    return function (duration, type, finishedCallback) {

        duration = +duration;

        // Only 0-4 are valid types.
        type = (type % 5) || 0;

        if (typeof finishedCallback != "function") {
            finishedCallback = function () {};
        }

        var osc = ctx.createOscillator();

        osc.type = type;
        //osc.type = "sine";

        osc.connect(ctx.destination);
        if (osc.noteOn) osc.noteOn(0); // old browsers
        if (osc.start) osc.start(); // new browsers

        setTimeout(function () {
            if (osc.noteOff) osc.noteOff(0); // old browsers
            if (osc.stop) osc.stop(); // new browsers
            finishedCallback();
        }, duration);

    };
})();

jsFiddle.

Create a global variable in TypeScript

This is how I have fixed it:

Steps:

  1. Declared a global namespace, for e.g. custom.d.ts as below :
declare global {
    namespace NodeJS {
        interface Global {
            Config: {}
        }
    }
}
export default global;
  1. Map the above created a file into "tsconfig.json" as below:
"typeRoots": ["src/types/custom.d.ts" ]
  1. Get the above created global variable in any of the files as below:
console.log(global.config)

Note:

  1. typescript version: "3.0.1".

  2. In my case, the requirement was to set the global variable before boots up the application and the variable should access throughout the dependent objects so that we can get the required config properties.

Hope this helps!

Thank you

How to pass value from <option><select> to form action

instead of trying to catch both POST and GET responses - you can have everything you want in the POST.

Your code:

<form method="POST" action="index.php?action=contact_agent&agent_id=">
  <select>
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
</form>

can easily become:

<form method="POST" action="index.php">
  <input type="hidden" name="action" value="contact_agent">
  <select name="agent_id">
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
  <button type="submit">Submit POST Data</button>
</form>

then in index.php - these values will be populated

$_POST['action'] // "contact_agent"
$_POST['agent_id'] // 1, 2 or 3 based on selection in form... 

Python function attributes - uses and abuses

Function attributes can be used to write light-weight closures that wrap code and associated data together:

#!/usr/bin/env python

SW_DELTA = 0
SW_MARK  = 1
SW_BASE  = 2

def stopwatch():
   import time

   def _sw( action = SW_DELTA ):

      if action == SW_DELTA:
         return time.time() - _sw._time

      elif action == SW_MARK:
         _sw._time = time.time()
         return _sw._time

      elif action == SW_BASE:
         return _sw._time

      else:
         raise NotImplementedError

   _sw._time = time.time() # time of creation

   return _sw

# test code
sw=stopwatch()
sw2=stopwatch()
import os
os.system("sleep 1")
print sw() # defaults to "SW_DELTA"
sw( SW_MARK )
os.system("sleep 2")
print sw()
print sw2()

1.00934004784

2.00644397736

3.01593494415

JQuery $.ajax() post - data in a java servlet

Simple method to sending data using java script and ajex call.

First right your form like this

<form id="frm_details" method="post" name="frm_details">
<input  id="email" name="email" placeholder="Your Email id" type="text" />
    <button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form> 

javascript logic target on form id #frm_details after sumbit

$(function(){
        $("#frm_details").on("submit", function(event) {
            event.preventDefault();

            var formData = {
                'email': $('input[name=email]').val() //for get email 
            };
            console.log(formData);

            $.ajax({
                url: "/tsmisc/api/subscribe-newsletter",
                type: "post",
                data: formData,
                success: function(d) {
                    alert(d);
                }
            });
        });
    }) 





General 
Request URL:https://test.abc
Request Method:POST
Status Code:200 
Remote Address:13.76.33.57:443

From Data
email:[email protected]

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

How to reset a timer in C#?

You can do timer.Interval = timer.Interval

List comprehension vs map

I consider that the most Pythonic way is to use a list comprehension instead of map and filter. The reason is that list comprehensions are clearer than map and filter.

In [1]: odd_cubes = [x ** 3 for x in range(10) if x % 2 == 1] # using a list comprehension

In [2]: odd_cubes_alt = list(map(lambda x: x ** 3, filter(lambda x: x % 2 == 1, range(10)))) # using map and filter

In [3]: odd_cubes == odd_cubes_alt
Out[3]: True

As you an see, a comprehension does not require extra lambda expressions as map needs. Furthermore, a comprehension also allows filtering easily, while map requires filter to allow filtering.

How to compare Boolean?

Using direct conditions (like ==, !=, !condition) will have a slight performance improvement over the .equals(condition) as in one case you are calling the method from an object whereas direct comparisons are performed directly.

.NET HttpClient. How to POST string value?

Here I found this article which is send post request using JsonConvert.SerializeObject() & StringContent() to HttpClient.PostAsync data

static async Task Main(string[] args)
{
    var person = new Person();
    person.Name = "John Doe";
    person.Occupation = "gardener";

    var json = Newtonsoft.Json.JsonConvert.SerializeObject(person);
    var data = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");

    var url = "https://httpbin.org/post";
    using var client = new HttpClient();

    var response = await client.PostAsync(url, data);

    string result = response.Content.ReadAsStringAsync().Result;
    Console.WriteLine(result);
}

What is the "right" way to iterate through an array in Ruby?

This will iterate through all the elements:

array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }

Prints:

1
2
3
4
5
6

This will iterate through all the elements giving you the value and the index:

array = ["A", "B", "C"]
array.each_with_index {|val, index| puts "#{val} => #{index}" }

Prints:

A => 0
B => 1
C => 2

I'm not quite sure from your question which one you are looking for.

Height equal to dynamic width (CSS fluid layout)

Expanding upon the padding top/bottom technique, it is possible to use a pseudo element to set the height of the element. Use float and negative margins to remove the pseudo element from the flow and view.

This allows you to place content inside the box without using an extra div and/or CSS positioning.

_x000D_
_x000D_
.fixed-ar::before {_x000D_
  content: "";_x000D_
  float: left;_x000D_
  width: 1px;_x000D_
  margin-left: -1px;_x000D_
}_x000D_
.fixed-ar::after {_x000D_
  content: "";_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
_x000D_
/* proportions */_x000D_
_x000D_
.fixed-ar-1-1::before {_x000D_
  padding-top: 100%;_x000D_
}_x000D_
.fixed-ar-4-3::before {_x000D_
  padding-top: 75%;_x000D_
}_x000D_
.fixed-ar-16-9::before {_x000D_
  padding-top: 56.25%;_x000D_
}_x000D_
_x000D_
_x000D_
/* demo */_x000D_
_x000D_
.fixed-ar {_x000D_
  margin: 1em 0;_x000D_
  max-width: 400px;_x000D_
  background: #EEE url(https://lorempixel.com/800/450/food/5/) center no-repeat;_x000D_
  background-size: contain;_x000D_
}
_x000D_
<div class="fixed-ar fixed-ar-1-1">1:1 Aspect Ratio</div>_x000D_
<div class="fixed-ar fixed-ar-4-3">4:3 Aspect Ratio</div>_x000D_
<div class="fixed-ar fixed-ar-16-9">16:9 Aspect Ratio</div>
_x000D_
_x000D_
_x000D_

Set System.Drawing.Color values

You can make extension to just change one color component

static class ColorExtension
{
    public static Color ChangeG(Color this color,byte g) 
    {
        return Color.FromArgb(color.A,color.R,g,color.B);
    }
}

then you can use this:

  yourColor = yourColor.ChangeG(100);

Get User Selected Range

Selection is its own object within VBA. It functions much like a Range object.

Selection and Range do not share all the same properties and methods, though, so for ease of use it might make sense just to create a range and set it equal to the Selection, then you can deal with it programmatically like any other range.

Dim myRange as Range
Set myRange = Selection

For further reading, check out the MSDN article.

Matplotlib: "Unknown projection '3d'" error

I encounter the same problem, and @Joe Kington and @bvanlew's answer solve my problem.

but I should add more infomation when you use pycharm and enable auto import.

when you format the code, the code from mpl_toolkits.mplot3d import Axes3D will auto remove by pycharm.

so, my solution is

from mpl_toolkits.mplot3d import Axes3D
Axes3D = Axes3D  # pycharm auto import
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

and it works well!

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

Just to be complete...

For 32 bit OS you must add a registry entry to:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

*******OR*******

For 64 bit OS you must add a registry entry to:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

This entry must be a DWORD, with the name being the name of your executable, that hosts the Webbrowser control; i.e.:

myappname.exe (DON'T USE "Contoso.exe" as in the MSDN web page...it's just a placeholder name)

Then give it a DWORD value, according to the table on:

http://msdn.microsoft.com/en-us/library/ee330730(v=vs.85).aspx#browser_emulation

I changed to 11001 decimal or 0x2AF9 hex --- (IE 11 EMULATION) since that isn't the DEFAULT value (if you have IE 11 installed -- or whatever version).

That MSDN article contains notes on several other Registry changes that affects Internet Explorer web browser behavior.

Creating and Naming Worksheet in Excel VBA

Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.

A better way to do this is to pop up a dialog box and get the name you wish to use.

How to count the number of lines of a string in javascript

To split using a regex use /.../

lines = str.split(/\r\n|\r|\n/); 

Setting up a cron job in Windows

The windows equivalent to a cron job is a scheduled task.

A scheduled task can be created as described by Alex and Rudu, but it can also be done command line with schtasks (if you for instance need to script it or add it to version control).

An example:

schtasks /create /tn calculate /tr calc /sc weekly /d MON /st 06:05 /ru "System"

Creates the task calculate, which starts the calculator(calc) every monday at 6:05 (should you ever need that.)

All available commands can be found here: http://technet.microsoft.com/en-us/library/cc772785%28WS.10%29.aspx

It works on windows server 2008 as well as windows server 2003.

Python: print a generator expression?

Unlike a list or a dictionary, a generator can be infinite. Doing this wouldn't work:

def gen():
    x = 0
    while True:
        yield x
        x += 1
g1 = gen()
list(g1)   # never ends

Also, reading a generator changes it, so there's not a perfect way to view it. To see a sample of the generator's output, you could do

g1 = gen()
[g1.next() for i in range(10)]

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

An alternative that works for me is to simply convert to a CSV.

How do I enable php to work with postgresql?

I have to add in httpd.conf this line (Windows):

LoadFile "C:/Program Files (x86)/PostgreSQL/8.3/bin/libpq.dll"

What does the "at" (@) symbol do in Python?

What does the “at” (@) symbol do in Python?

@ symbol is a syntactic sugar python provides to utilize decorator,
to paraphrase the question, It's exactly about what does decorator do in Python?

Put it simple decorator allow you to modify a given function's definition without touch its innermost (it's closure).
It's the most case when you import wonderful package from third party. You can visualize it, you can use it, but you cannot touch its innermost and its heart.

Here is a quick example,
suppose I define a read_a_book function on Ipython

In [9]: def read_a_book():
   ...:     return "I am reading the book: "
   ...: 
In [10]: read_a_book()
Out[10]: 'I am reading the book: '

You see, I forgot to add a name to it.
How to solve such a problem? Of course, I could re-define the function as:

def read_a_book():
    return "I am reading the book: 'Python Cookbook'"

Nevertheless, what if I'm not allowed to manipulate the original function, or if there are thousands of such function to be handled.

Solve the problem by thinking different and define a new_function

def add_a_book(func):
    def wrapper():
        return func() + "Python Cookbook"
    return wrapper

Then employ it.

In [14]: read_a_book = add_a_book(read_a_book)
In [15]: read_a_book()
Out[15]: 'I am reading the book: Python Cookbook'

Tada, you see, I amended read_a_book without touching it inner closure. Nothing stops me equipped with decorator.

What's about @

@add_a_book
def read_a_book():
    return "I am reading the book: "
In [17]: read_a_book()
Out[17]: 'I am reading the book: Python Cookbook'

@add_a_book is a fancy and handy way to say read_a_book = add_a_book(read_a_book), it's a syntactic sugar, there's nothing more fancier about it.

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

Another avenue that hasn't been considered is that your postgres was installed by pgvm (Postgres Version Manager).

Uninstall with pgvm uninstall 9.0.3

How to open CSV file in R when R says "no such file or directory"?

Sound like you just have an issue with the path. Include the full path, if you use backslashes they need to be escaped: "C:\\folder\\folder\\Desktop\\file.csv" or "C:/folder/folder/Desktop/file.csv".

myfile = read.csv("C:/folder/folder/Desktop/file.csv")  # or read.table()

It may also be wise to avoid spaces and symbols in your file names, though I'm fairly certain spaces are OK.

Center a popup window on screen?

function fnPopUpWindow(pageId) {
     popupwindow("hellowWorld.php?id="+pageId, "printViewer", "500", "300");
}

function popupwindow(url, title, w, h) {
    var left = Math.round((screen.width/2)-(w/2));
    var top = Math.round((screen.height/2)-(h/2));
    return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, '
            + 'menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=' + w 
            + ', height=' + h + ', top=' + top + ', left=' + left);
}
<a href="javascript:void(0);" onclick="fnPopUpWindow('10');">Print Me</a>

Note: you have to use Math.round for getting the exact integer of width and height.

How to Auto resize HTML table cell to fit the text size

Well, me also I was struggling with this issue: this is how I solved it: apply table-layout: auto; to the <table> element.

CSS Image size, how to fill, but not stretch?

The only real way is to have a container around your image and use overflow:hidden:

HTML

<div class="container"><img src="ckk.jpg" /></div>

CSS

.container {
    width: 300px;
    height: 200px;
    display: block;
    position: relative;
    overflow: hidden;
}

.container img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
}

It's a pain in CSS to do what you want and center the image, there is a quick fix in jquery such as:

var conHeight = $(".container").height();
var imgHeight = $(".container img").height();
var gap = (imgHeight - conHeight) / 2;
$(".container img").css("margin-top", -gap);

http://jsfiddle.net/x86Q7/2/

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

We use IBM Rational Application Developer (RAD) and had the same problem.

ErrorMessage:

Access restriction: The type 'JAXWSProperties' is not API (restriction on required library 'C:\IBM\RAD95\jdk\jre\lib\rt.jar')

Solution:

go to java build path and under Library tab, remove JRE System Library. Then again Add Library --> JRE System Library

update one table with data from another

UPDATE table1
SET 
`ID` = (SELECT table2.id FROM table2 WHERE table1.`name`=table2.`name`)

CSS selector based on element text?

Not with CSS directly, you could set CSS properties via JavaScript based on the internal contents but in the end you would still need to be operating in the definitions of CSS.

Accessing member of base class

Working example. Notes below.

class Animal {
    constructor(public name) {
    }

    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    move() {
        alert(this.name + " is Slithering...");
        super.move(5);
    }
}

class Horse extends Animal {
    move() {
        alert(this.name + " is Galloping...");
        super.move(45);
    }
}

var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);
  1. You don't need to manually assign the name to a public variable. Using public name in the constructor definition does this for you.

  2. You don't need to call super(name) from the specialised classes.

  3. Using this.name works.

Notes on use of super.

This is covered in more detail in section 4.9.2 of the language specification.

The behaviour of the classes inheriting from Animal is not dissimilar to the behaviour in other languages. You need to specify the super keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move() or this.move() you would be dealing with the specialised Snake or Horse function, so using super.move() explicitly calls the base class function.

There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name and this.name - there is simply this.name. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.

How can I remove item from querystring in asp.net using c#?

well I have a simple solution , but there is a little javascript involve.

assuming the Query String is "ok=1"

    string url = Request.Url.AbsoluteUri.Replace("&ok=1", "");
   url = Request.Url.AbsoluteUri.Replace("?ok=1", "");
  Response.Write("<script>window.location = '"+url+"';</script>");

How can I disable a button on a jQuery UI dialog?

If you're including the .button() plugin/widget that jQuery UI contains (if you have the full library and are on 1.8+, you have it), you can use it to disable the button and update the state visually, like this:

$(".ui-dialog-buttonpane button:contains('Confirm')").button("disable");

You can give it a try here...or if you're on an older version or not using the button widget, you can disable it like this:

$(".ui-dialog-buttonpane button:contains('Confirm')").attr("disabled", true)
                                              .addClass("ui-state-disabled");

If you want it inside a specific dialog, say by ID, then do this:

$("#dialogID").next(".ui-dialog-buttonpane button:contains('Confirm')")
              .attr("disabled", true);

In other cases where :contains() might give false positives then you can use .filter() like this, but it's overkill here since you know your two buttons. If that is the case in other situations, it'd look like this:

$("#dialogID").next(".ui-dialog-buttonpane button").filter(function() {
  return $(this).text() == "Confirm";
}).attr("disabled", true);

This would prevent :contains() from matching a substring of something else.

Difference between View and ViewGroup in Android

View is the SuperClass of All component like TextView, EditText, ListView, etc.. while ViewGroup is Collection of Views(TextView, EditText, ListView, etc..), somewhat like container.

Difference between using bean id and name in Spring configuration file

Both id and name are bean identifiers in Spring IOC container/ApplicationContecxt. The id attribute lets you specify exactly one id but using name attribute you can give alias name to that bean.

You can check the spring doc here.

Printing 2D array in matrix format

you can do like this also

        long[,] arr = new long[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 }};

        for (int i = 0; i < arr.GetLength(0); i++)
        {
            for (int j = 0; j < arr.GetLength(1); j++)
            {
                Console.Write(arr[i,j]+" ");
            }
            Console.WriteLine();
        }

Select option padding not working in chrome

I just found a way to get padding applied to the select input in chrome

select{
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    padding: 5px;
}

Seems to work in the current chrome 39.0.2171.71 (64-bit) and safari (I only tested this on a mac).

This seems to remove the default styling added to the select input (it also removed the drop down arrow), but allows you to then use your own styling without chrome overriding it.

I stumbled across this fix while using code from here: http://fettblog.eu/style-select-elements/