Programs & Examples On #Uimodalpresentationformsh

onChange and onSelect in DropDownList

hmm. why don't you use onClick()

<select id="mySelect" onChange="enable();">
   <option onClick="disable();">No</option>
   <option onClick="enable();">Yes</option>
</select>

How to make html table vertically scrollable

The best way to do this is strictly separate your table into two different tables - header and body:

<div class="header">
  <table><tr><!-- th here --></tr></table>
</div>

<div class="body">
  <table><tr><!-- td here --></tr></table>
</div>

.body {
  height: 100px;
  overflow: auto
}

If your table has a big width (more than screen width), then you have to add scroll events for horizontal scrolling header and body synchroniously.

You should never touch table tags (table, tbody, thead, tfoot, tr) with CSS properties display and overflow. Dealing with DIV wrappers is much more preferable.

HTML Button : Navigate to Other Page - Different Approaches

I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.

I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.

Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.

Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.

Subset and ggplot2

@agstudy's answer didn't work for me with the latest version of ggplot2, but this did, using maggritr pipes:

ggplot(data=dat)+ 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
                data = . %>% filter(ID %in% c("P1" , "P3")))

It works because if geom_line sees that data is a function, it will call that function with the inherited version of data and use the output of that function as data.

Git stash pop- needs merge, unable to refresh index

I have found that the best solution is to branch off your stash and do a resolution afterwards.

git stash branch <branch-name>

if you drop of clear your stash, you may lose your changes and you will have to recur to the reflog.

Convert Current date to integer

Your Problem is because of getTime() . it always return following.

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

Because the max integer value is less then the return value by getTime() that why is showing wrong result.

I do not understand how execlp() works in Linux

The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:

execl("/bin/ls", "ls", "-la", NULL);

The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:

execlp("ls", "ls", "-la", NULL);

Find unique lines

I find this easier.

sort -u input_filename > output_filename

-u stands for unique.

SQL grammar for SELECT MIN(DATE)

SELECT  MIN(Date)  AS Date  FROM tbl_Employee /*To get First date Of Employee*/

Powershell folder size of folders without listing Subdirectories

The solution posted by @Linga: "Get-ChildItem -Recurse 'directory_path' | Measure-Object -Property Length -Sum" is nice and short. However, it only computes the size of 'directory_path', without sub-directories.
Here is a simple solution for listing all sub-directory sizes. With a little pretty-printing added.
(Note: use the -File option to avoid errors for empty sub-directories)

foreach ($d in gci -Directory -Force) {
  '{0:N0}' -f ((gci $d -File -Recurse -Force | measure length -sum).sum) + "`t`t$d" 
}

m2eclipse error

I would add some points that helped me to solve this problem :

Having the local repository OK, on the other hand, turned out to be quite costly, as many archetypes would not get loaded, due apparently to timeouts of m2eclipse and very unstable communication speeds in my case.

In many cases only the error file could be found in the folder ex : xxx.jar.lastUpdated, instead of the jar or pom file. I had always to suppress this file to permit a new download.

Also really worthy were :

  • as already said, using the mvn clean install from the command line, apparently much more patient than m2eclipse, and also efficient and verbose, at least for the time being.

  • (and also the Update Project of the Maven menu)

  • downloading using the dependency:get goal

    mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get -DrepoUrl=url -Dartifact=groupId:artifactId:version1

(from within the project folder) (hint given in another thread, thanks also).

  • also downloading and installing manually (.jar+.sha1), from in particular, "m2proxy atlassian" .

  • adding other repositories in the pom.xml itself (the settings.xml mirror configuration did'nt do the job, I don't know yet why). Ex : nexus/content/repositories/releases/ et nexus/content/repositories/releases/, sous repository.jboss.org, ou download.java.net/maven/2 .

To finish, in any case, a lot of time (!..) could have been et could certainly still be spared with a light tool repairing thoroughly the local repository straightaway. I could not yet find it. Actually it should even be normally a mvn command ("--repair-local-repository").

Why my regexp for hyphenated words doesn't work?

A couple of things:

  1. Your regexes need to be anchored by separators* or you'll match partial words, as is the case now
  2. You're not using the proper syntax for a non-capturing group. It's (?: not (:?

If you address the first problem, you won't need groups at all.

*That is, a blank or beginning/end of string.

Preferred method to store PHP arrays (json_encode vs serialize)

Seems like serialize is the one I'm going to use for 2 reasons:

  • Someone pointed out that unserialize is faster than json_decode and a 'read' case sounds more probable than a 'write' case.

  • I've had trouble with json_encode when having strings with invalid UTF-8 characters. When that happens the string ends up being empty causing loss of information.

How to copy a huge table data into another table in SQL Server

I have been working with our DBA to copy an audit table with 240M rows to another database.

Using a simple select/insert created a huge tempdb file.

Using a the Import/Export wizard worked but copied 8M rows in 10min

Creating a custom SSIS package and adjusting settings copied 30M rows in 10Min

The SSIS package turned out to be the fastest and most efficent for our purposes

Earl

Any good, visual HTML5 Editor or IDE?

Radrails 3 is supposed to have it, Aptana Studio 3 will have it. Radrails is in beta, so thats kind of a downer, but none the less it is there to give'r a whirl.

It is multi-platform too, for those of us non-Windoze fellas.

Count all occurrences of a string in lots of files with grep

This works for multiple occurrences per line:

grep -o string * | wc -l

How to create a shortcut using PowerShell

I don't know any native cmdlet in powershell but you can use com object instead:

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()

you can create a powershell script save as set-shortcut.ps1 in your $pwd

param ( [string]$SourceExe, [string]$DestinationPath )

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()

and call it like this

Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"

If you want to pass arguments to the target exe, it can be done by:

#Set the additional parameters for the shortcut  
$Shortcut.Arguments = "/argument=value"  

before $Shortcut.Save().

For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.

param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()

How to set alignment center in TextBox in ASP.NET?

To center align text

input[type='text'] { text-align:center;}

To center align the textbox in the container that it sits in, apply text-align:center to the container.

How do I search for an object by its ObjectId in the mongo console?

If you're using Node.js:

In that req.user is ObjectId format.

var mongoose = require("mongoose");
var ObjectId = mongoose.Schema.Types.ObjectId;

function getUsers(req, res)
    User.findOne({"_id":req.user}, { password: 0 }) 
         .then(data => { 
             res.send(data);})g
}
exports.getUsers = getUsers;

Join String list elements with a delimiter in one step

You can use the StringUtils.join() method of Apache Commons Lang:

String join = StringUtils.join(joinList, "+");

error: function returns address of local variable

I came up with this simple and straight-forward (i hope so) code example which should explain itself!

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

/* function header definitions */
char* getString();                     //<- with malloc (good practice)
char * getStringNoMalloc();  //<- without malloc (fails! don't do this!)
void getStringCallByRef(char* reference); //<- callbyref (good practice)

/* the main */
int main(int argc, char*argv[]) {

    //######### calling with malloc
    char * a = getString();
    printf("MALLOC ### a = %s \n", a); 
    free(a);

    //######### calling without malloc
    char * b = getStringNoMalloc();
    printf("NO MALLOC ### b = %s \n", b); //this doesnt work, question to yourself: WHY?
    //HINT: the warning says that a local reference is returned. ??!
    //NO free here!

    //######### call-by-reference
    char c[100];
    getStringCallByRef(c);
    printf("CALLBYREF ### c = %s \n", c);

    return 0;
}

//WITH malloc
char* getString() {

    char * string;
    string = malloc(sizeof(char)*100);

    strcat(string, "bla");
    strcat(string, "/");
    strcat(string, "blub");

    printf("string : '%s'\n", string);

    return string;
}

//WITHOUT malloc (watch how it does not work this time)
char* getStringNoMalloc() {

     char string[100] = {};

     strcat(string, "bla");
     strcat(string, "/");
     strcat(string, "blub");
     //INSIDE this function "string" is OK
     printf("string : '%s'\n", string);

     return string; //but after returning.. it is NULL? :)
}

// ..and the call-by-reference way to do it (prefered)
void getStringCallByRef(char* reference) {

    strcat(reference, "bla");
    strcat(reference, "/");
    strcat(reference, "blub");
    //INSIDE this function "string" is OK
    printf("string : '%s'\n", reference);
    //OUTSIDE it is also OK because we hand over a reference defined in MAIN
    // and not defined in this scope (local), which is destroyed after the function finished
}

When compiling it, you get the [intended] warning:

me@box:~$ gcc -o example.o example.c 
example.c: In function ‘getStringNoMalloc’:
example.c:58:16: warning: function returns address of local variable [-Wreturn-local-addr]
         return string; //but after returning.. it is NULL? :)
            ^~~~~~

...basically what we are discussing here!

running my example yields this output:

me@box:~$ ./example.o 
string : 'bla/blub'
MALLOC ### a = bla/blub 
string : 'bla/blub'
NO MALLOC ### b = (null) 
string : 'bla/blub'
CALLBYREF ### c = bla/blub 

Theory:

This has been answered very nicely by User @phoxis. Basically think about it this way: Everything inbetween { and } is local scope, thus by the C-Standard is "undefined" outside. By using malloc you take memory from the HEAP (programm scope) and not from the STACK (function scope) - thus its 'visible' from outside. The second correct way to do it is call-by-reference. Here you define the var inside the parent-scope, thus it is using the STACK (because the parent scope is the main()).

Summary:

3 Ways to do it, One of them false. C is kind of to clumsy to just have a function return a dynamically sized String. Either you have to malloc and then free it, or you have to call-by-reference. Or use C++ ;)

python ignore certificate validation urllib2

For those who uses an opener, you can achieve the same thing based on Enno Gröper's great answer:

import urllib2, ssl

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx), your_first_handler, your_second_handler[...])
opener.addheaders = [('Referer', 'http://example.org/blah.html')]

content = opener.open("https://localhost/").read()

And then use it as before.

According to build_opener and HTTPSHandler, a HTTPSHandler is added if ssl module exists, here we just specify our own instead of the default one.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

his issue is happening due to change of protocol from http to https for central repository. please refer following link for more details. https://support.sonatype.com/hc/en-us/articles/360041287334-Central-501-HTTPS-Required 

In order to fix the problem, copy following into your pom.ml file. This will set the repository url to use https.

<repositories>
        <repository>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <releases>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
        </pluginRepository>
    </pluginRepositories>

Eclipse does not highlight matching variables

Java - Editor - Mark Occurrences in Eclipse Photon.

Java - Editor - Mark Occurrences

Eclipse Java EE IDE for Web Developers. Version: Photon Release (4.8.0)

What's the difference between a method and a function?

I know many others have already answered, but I found following is a simple, yet effective single line answer. Though it doesn't look a lot better than others answers here, but if you read it carefully, it has everything you need to know about the method vs function.

A method is a function that has a defined receiver, in OOP terms, a method is a function on an instance of an object.

Converting java.sql.Date to java.util.Date

The class java.sql.Date is designed to carry only a date without time, so the conversion result you see is correct for this type. You need to use a java.sql.Timestamp to get a full date with time.

java.util.Date newDate = result.getTimestamp("VALUEDATE");

Set mouse focus and move cursor to end of input using jQuery

I have found the same thing as suggested above by a few folks. If you focus() first, then push the val() into the input, the cursor will get positioned to the end of the input value in Firefox,Chrome and IE. If you push the val() into the input field first, Firefox and Chrome position the cursor at the end, but IE positions it to the front when you focus().

$('element_identifier').focus().val('some_value') 

should do the trick (it always has for me anyway).

Before and After Suite execution hook in jUnit 4.x

The only way I think then to get the functionality you want would be to do something like

import junit.framework.Test;  
import junit.framework.TestResult;  
import junit.framework.TestSuite;  

public class AllTests {  
    public static Test suite() {  
        TestSuite suite = new TestSuite("TestEverything");  
        //$JUnit-BEGIN$  
        suite.addTestSuite(TestOne.class);  
        suite.addTestSuite(TestTwo.class);  
        suite.addTestSuite(TestThree.class);  
        //$JUnit-END$  
     }  

     public static void main(String[] args)  
     {  
        AllTests test = new AllTests();  
        Test testCase = test.suite();  
        TestResult result = new TestResult();  
        setUp();  
        testCase.run(result);  
        tearDown();  
     }  
     public void setUp() {}  
     public void tearDown() {}  
} 

I use something like this in eclipse, so I'm not sure how portable it is outside of that environment

How to make a movie out of images in python

Here is a minimal example using moviepy. For me this was the easiest solution.

import os
import moviepy.video.io.ImageSequenceClip
image_folder='folder_with_images'
fps=1

image_files = [image_folder+'/'+img for img in os.listdir(image_folder) if img.endswith(".png")]
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)
clip.write_videofile('my_video.mp4')

what happens when you type in a URL in browser

First the computer looks up the destination host. If it exists in local DNS cache, it uses that information. Otherwise, DNS querying is performed until the IP address is found.

Then, your browser opens a TCP connection to the destination host and sends the request according to HTTP 1.1 (or might use HTTP 1.0, but normal browsers don't do it any more).

The server looks up the required resource (if it exists) and responds using HTTP protocol, sends the data to the client (=your browser)

The browser then uses HTML parser to re-create document structure which is later presented to you on screen. If it finds references to external resources, such as pictures, css files, javascript files, these are is delivered the same way as the HTML document itself.

How do I select text nodes with jQuery?

jQuery doesn't have a convenient function for this. You need to combine contents(), which will give just child nodes but includes text nodes, with find(), which gives all descendant elements but no text nodes. Here's what I've come up with:

var getTextNodesIn = function(el) {
    return $(el).find(":not(iframe)").addBack().contents().filter(function() {
        return this.nodeType == 3;
    });
};

getTextNodesIn(el);

Note: If you're using jQuery 1.7 or earlier, the code above will not work. To fix this, replace addBack() with andSelf(). andSelf() is deprecated in favour of addBack() from 1.8 onwards.

This is somewhat inefficient compared to pure DOM methods and has to include an ugly workaround for jQuery's overloading of its contents() function (thanks to @rabidsnail in the comments for pointing that out), so here is non-jQuery solution using a simple recursive function. The includeWhitespaceNodes parameter controls whether or not whitespace text nodes are included in the output (in jQuery they are automatically filtered out).

Update: Fixed bug when includeWhitespaceNodes is falsy.

function getTextNodesIn(node, includeWhitespaceNodes) {
    var textNodes = [], nonWhitespaceMatcher = /\S/;

    function getTextNodes(node) {
        if (node.nodeType == 3) {
            if (includeWhitespaceNodes || nonWhitespaceMatcher.test(node.nodeValue)) {
                textNodes.push(node);
            }
        } else {
            for (var i = 0, len = node.childNodes.length; i < len; ++i) {
                getTextNodes(node.childNodes[i]);
            }
        }
    }

    getTextNodes(node);
    return textNodes;
}

getTextNodesIn(el);

How to start a stopped Docker container with a different command?

Add a check to the top of your Entrypoint script

Docker really needs to implement this as a new feature, but here's another workaround option for situations in which you have an Entrypoint that terminates after success or failure, which can make it difficult to debug.

If you don't already have an Entrypoint script, create one that runs whatever command(s) you need for your container. Then, at the top of this file, add these lines to entrypoint.sh:

# Run once, hold otherwise
if [ -f "already_ran" ]; then
    echo "Already ran the Entrypoint once. Holding indefinitely for debugging."
    cat
fi
touch already_ran

# Do your main things down here

To ensure that cat holds the connection, you may need to provide a TTY. I'm running the container with my Entrypoint script like so:

docker run -t --entrypoint entrypoint.sh image_name

This will cause the script to run once, creating a file that indicates it has already run (in the container's virtual filesystem). You can then restart the container to perform debugging:

docker start container_name

When you restart the container, the already_ran file will be found, causing the Entrypoint script to stall with cat (which just waits forever for input that will never come, but keeps the container alive). You can then execute a debugging bash session:

docker exec -i container_name bash

While the container is running, you can also remove already_ran and manually execute the entrypoint.sh script to rerun it, if you need to debug that way.

jQuery: select all elements of a given class, except for a particular Id

Use the :not selector.

$(".thisclass:not(#thisid)").doAction();

If you have multiple ids or selectors just use the comma delimiter, in addition:

(".thisclass:not(#thisid,#thatid)").doAction();

Using IS NULL or IS NOT NULL on join conditions - Theory question

The NULL part is calculated AFTER the actual join, so that is why it needs to be in the where clause.

Check if XML Element exists

You can validate that and much more by using an XML schema language, like XSD.

If you mean conditionally, within code, then XPath is worth a look as well.

How to pass objects to functions in C++?

Do I need to pass pointers, references, or non-pointer and non-reference values?

This is a question that matters when writing a function and choosing the types of the parameters it takes. That choice will affect how the function is called and it depends on a few things.

The simplest option is to pass objects by value. This basically creates a copy of the object in the function, which has many advantages. But sometimes copying is costly, in which case a constant reference, const&, is usually best. And sometimes you need your object to be changed by the function. Then a non-constant reference, &, is needed.

For guidance on the choice of parameter types, see the Functions section of the C++ Core Guidelines, starting with F.15. As a general rule, try to avoid raw pointers, *.

I want to align the text in a <td> to the top

Use <td valign="top" style="width: 259px"> instead...

How does DHT in torrents work?

What happens with bittorrent and a DHT is that at the beginning bittorrent uses information embedded in the torrent file to go to either a tracker or one of a set of nodes from the DHT. Then once it finds one node, it can continue to find others and persist using the DHT without needing a centralized tracker to maintain it.

The original information bootstraps the later use of the DHT.

Dynamically create checkbox with JQuery from text input

<div id="cblist">
    <input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>

<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />

<script type="text/javascript">
$(document).ready(function() {
    $('#btnSave').click(function() {
        addCheckbox($('#txtName').val());
    });
});

function addCheckbox(name) {
   var container = $('#cblist');
   var inputs = container.find('input');
   var id = inputs.length+1;

   $('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
   $('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
}
</script>

PowerShell script to check the status of a URL

$request = [System.Net.WebRequest]::Create('http://stackoverflow.com/questions/20259251/powershell-script-to-check-the-status-of-a-url')

$response = $request.GetResponse()

$response.StatusCode

$response.Close()

Format Date output in JSF

Use <f:convertDateTime>. You can nest this in any input and output component. Pattern rules are same as java.text.SimpleDateFormat.

<h:outputText value="#{someBean.dateField}" >
    <f:convertDateTime pattern="dd.MM.yyyy HH:mm" />
</h:outputText>

Clearing content of text file using C#

 using (FileStream fs = File.Create(path))
 {

 }

Will create or overwrite a file.

Session timeout in ASP.NET

IIS sessions timeout value is for classic .asp applications only, this is controlled on IIS configuration. In your case For ASP.NET apps, only the web.config-specified timeout value applies.

Bootstrap table striped: How do I change the stripe background colour?

Add the following CSS style after loading Bootstrap:

.table-striped>tbody>tr:nth-child(odd)>td, 
.table-striped>tbody>tr:nth-child(odd)>th {
   background-color: red; // Choose your own color here
 }

Locking pattern for proper use of .NET MemoryCache

public interface ILazyCacheProvider : IAppCache
{
    /// <summary>
    /// Get data loaded - after allways throw cached result (even when data is older then needed) but very fast!
    /// </summary>
    /// <param name="key"></param>
    /// <param name="getData"></param>
    /// <param name="slidingExpiration"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    T GetOrAddPermanent<T>(string key, Func<T> getData, TimeSpan slidingExpiration);
}

/// <summary>
/// Initialize LazyCache in runtime
/// </summary>
public class LazzyCacheProvider: CachingService, ILazyCacheProvider
{
    private readonly Logger _logger = LogManager.GetLogger("MemCashe");
    private readonly Hashtable _hash = new Hashtable();
    private readonly List<string>  _reloader = new List<string>();
    private readonly ConcurrentDictionary<string, DateTime> _lastLoad = new ConcurrentDictionary<string, DateTime>();  


    T ILazyCacheProvider.GetOrAddPermanent<T>(string dataKey, Func<T> getData, TimeSpan slidingExpiration)
    {
        var currentPrincipal = Thread.CurrentPrincipal;
        if (!ObjectCache.Contains(dataKey) && !_hash.Contains(dataKey))
        {
            _hash[dataKey] = null;
            _logger.Debug($"{dataKey} - first start");
            _lastLoad[dataKey] = DateTime.Now;
            _hash[dataKey] = ((object)GetOrAdd(dataKey, getData, slidingExpiration)).CloneObject();
            _lastLoad[dataKey] = DateTime.Now;
           _logger.Debug($"{dataKey} - first");
        }
        else
        {
            if ((!ObjectCache.Contains(dataKey) || _lastLoad[dataKey].AddMinutes(slidingExpiration.Minutes) < DateTime.Now) && _hash[dataKey] != null)
                Task.Run(() =>
                {
                    if (_reloader.Contains(dataKey)) return;
                    lock (_reloader)
                    {
                        if (ObjectCache.Contains(dataKey))
                        {
                            if(_lastLoad[dataKey].AddMinutes(slidingExpiration.Minutes) > DateTime.Now)
                                return;
                            _lastLoad[dataKey] = DateTime.Now;
                            Remove(dataKey);
                        }
                        _reloader.Add(dataKey);
                        Thread.CurrentPrincipal = currentPrincipal;
                        _logger.Debug($"{dataKey} - reload start");
                        _hash[dataKey] = ((object)GetOrAdd(dataKey, getData, slidingExpiration)).CloneObject();
                        _logger.Debug($"{dataKey} - reload");
                        _reloader.Remove(dataKey);
                    }
                });
        }
        if (_hash[dataKey] != null) return (T) (_hash[dataKey]);

        _logger.Debug($"{dataKey} - dummy start");
        var data = GetOrAdd(dataKey, getData, slidingExpiration);
        _logger.Debug($"{dataKey} - dummy");
        return (T)((object)data).CloneObject();
    }
}

How to retrieve checkboxes values in jQuery

Anyway, you probably need something like this:

 var val = $('#c_b :checkbox').is(':checked').val();
 $('#t').val( val );

This will get the value of the first checked checkbox on the page and insert that in the textarea with id='textarea'.

Note that in your example code you should put the checkboxes in a form.

In SQL, how can you "group by" in ranges?

select t.range as score, count(*) as Count 
from (
      select UserId,
         case when isnull(score ,0) >= 0 and isnull(score ,0)< 5 then '0-5'
                when isnull(score ,0) >= 5 and isnull(score ,0)< 10 then '5-10'
                when isnull(score ,0) >= 10 and isnull(score ,0)< 15 then '10-15'
                when isnull(score ,0) >= 15 and isnull(score ,0)< 20 then '15-20'               
         else ' 20+' end as range
         ,case when isnull(score ,0) >= 0 and isnull(score ,0)< 5 then 1
                when isnull(score ,0) >= 5 and isnull(score ,0)< 10 then 2
                when isnull(score ,0) >= 10 and isnull(score ,0)< 15 then 3
                when isnull(score ,0) >= 15 and isnull(score ,0)< 20 then 4             
         else 5  end as pd
     from score table
     ) t

group by t.range,pd order by pd

MySQL Error 1093 - Can't specify target table for update in FROM clause

Recently i had to update records in the same table i did it like below:

UPDATE skills AS s, (SELECT id  FROM skills WHERE type = 'Programming') AS p
SET s.type = 'Development' 
WHERE s.id = p.id;

What is the HTML tabindex attribute?

Controlling the order of tabbing (pressing the tab key to move focus) within the page.

Reference: http://www.w3.org/TR/html401/interact/forms.html#h-17.11.1

Making a Bootstrap table column fit to content

Kind of an old question, but I arrived here looking for this. I wanted the table to be as small as possible, fitting to it's contents. The solution was to simply set the table width to an arbitrary small number (1px for example). I even created a CSS class to handle it:

.table-fit {
    width: 1px;
}

And use it like so:

<table class="table table-fit">

Example: JSFiddle

How can I prevent a window from being resized with tkinter?

This code makes a window with the conditions that the user cannot change the dimensions of the Tk() window, and also disables the maximise button.

import tkinter as tk

root = tk.Tk()
root.resizable(width=False, height=False)
root.mainloop()

Within the program you can change the window dimensions with @Carpetsmoker's answer, or by doing this:

root.geometry('{}x{}'.format(<widthpixels>, <heightpixels>))

It should be fairly easy for you to implement that into your code. :)

matplotlib has no attribute 'pyplot'

pyplot is a sub-module of matplotlib which doesn't get imported with a simple import matplotlib.

>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>> 

It seems customary to do: import matplotlib.pyplot as plt at which time you can use the various functions and classes it contains:

p = plt.plot(...)

Are there .NET implementation of TLS 1.2?

Yes, though you have to turn on TLS 1.2 manually at System.Net.ServicePointManager.SecurityProtocol

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; // comparable to modern browsers
var response = WebRequest.Create("https://www.howsmyssl.com/").GetResponse();
var body = new StreamReader(response.GetResponseStream()).ReadToEnd();

Your client is using TLS 1.2, the most modern version of the encryption protocol


Out the box, WebRequest will use TLS 1.0 or SSL 3.

Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

Jupyter is base on ipython, a permanent solution could be changing the ipython config options.

Create a config file

$ ipython profile create
$ ipython locate
/Users/username/.ipython

Edit the config file

$ cd /Users/username/.ipython
$ vi profile_default/ipython_config.py

The following lines allow you to add your module path to sys.path

c.InteractiveShellApp.exec_lines = [
    'import sys; sys.path.append("/path/to/your/module")'
]

At the jupyter startup the previous line will be executed

Here you can find more details about ipython config https://www.lucypark.kr/blog/2013/02/10/when-python-imports-and-ipython-does-not/

How to run cron job every 2 hours

To Enter into crontab :

crontab -e

write this into the file:

0 */2 * * * python/php/java yourfilepath

Example :0 */2 * * * python ec2-user/home/demo.py

and make sure you have keep one blank line after the last cron job in your crontab file

Where do I find the definition of size_t?

Practically speaking size_t represents the number of bytes you can address. On most modern architectures for the last 10-15 years that has been 32 bits which has also been the size of a unsigned int. However we are moving to 64bit addressing while the uint will most likely stay at 32bits (it's size is not guaranteed in the c++ standard). To make your code that depends on the memory size portable across architectures you should use a size_t. For example things like array sizes should always use size_t's. If you look at the standard containers the ::size() always returns a size_t.

Also note, visual studio has a compile option that can check for these types of errors called "Detect 64-bit Portability Issues".

How to avoid "Permission denied" when using pip with virtualenv

While creating virtualenv if you use sudo the directory is created with root privileges.So when you try to install a package with non-sudo user you won't have permission to install into it. So always create virtualenv without sudo and install without sudo.

You can also copy packages installed on global python to virtualenv.

cp -r /lib/python/site-packages/* virtualenv/lib/python/site-packages/

How do I install Python 3 on an AWS EC2 instance?

EC2 (on the Amazon Linux AMI) currently supports python3.4 and python3.5.

sudo yum install python35
sudo yum install python35-pip

String Padding in C

One thing that's definitely wrong in the function which forms the original question in this thread, which I haven't seen anyone mention, is that it is concatenating extra characters onto the end of the string literal that has been passed in as a parameter. This will give unpredictable results. In the example call of the function, the string literal "Hello" will be hard-coded into the program, so presumably concatenating onto the end of it will dangerously write over code. If you want to return a string which is bigger than the original then you need to make sure you allocate it dynamically and then delete it in the calling code when you're done.

How to call a function within class?

Since these are member functions, call it as a member function on the instance, self.

def isNear(self, p):
    self.distToPoint(p)
    ...

convert '1' to '0001' in JavaScript

I use the following object:

function Padder(len, pad) {
  if (len === undefined) {
    len = 1;
  } else if (pad === undefined) {
    pad = '0';
  }

  var pads = '';
  while (pads.length < len) {
    pads += pad;
  }

  this.pad = function (what) {
    var s = what.toString();
    return pads.substring(0, pads.length - s.length) + s;
  };
}

With it you can easily define different "paddings":

var zero4 = new Padder(4);
zero4.pad(12); // "0012"
zero4.pad(12345); // "12345"
zero4.pad("xx"); // "00xx"
var x3 = new Padder(3, "x");
x3.pad(12); // "x12"

CSS: transition opacity on mouse-out?

$(window).scroll(function() {    
    $('.logo_container, .slogan').css({
        "opacity" : ".1",
        "transition" : "opacity .8s ease-in-out"
    });
});

Check the fiddle: http://jsfiddle.net/2k3hfwo0/2/

How can I find the link URL by link text with XPath?

Too late for you, but for anyone else with the same question...

//a[contains(text(), 'programming')]/@href

Of course, 'programming' can be any text fragment.

failed to find target with hash string android-23

Update: Does not apply to the Android Studio released after this answer (April 2016)

Note: I think this might be a bug in Android Studio.

enter image description here

  1. Go to Project Structure
  2. Select App Module
  3. Under the first tab "Properties" change the Compile SDK Version to API XX from Google API xx (e.g. API 23 instead of Google API 23)
  4. Press OK
  5. Wait for the completion of on going process, in my case I did not get an error at this point.

Now revert Compiled Sdk Version back to Google API xx.

If this not work, then:

  1. With Google API (Google API xx instead of API xx), lower the build tool version (e.g. Google API 23 and build tool version 23.0.1)
  2. Press Ok and wait for completion of on going process
  3. Revert back your build tool version to what it was before you changed
  4. Press Ok
  5. Wait for the completion of process.
  6. Done!

How do I work with a git repository within another repository?

Consider using subtree instead of submodules, it will make your repo users life much easier. You may find more detailed guide in Pro Git book.

Browser: Identifier X has already been declared

But I have declared that var in the top of the other files.

That's the problem. After all, this makes multiple declarations for the same name in the same (global) scope - which will throw an error with const.

Instead, use var, use only one declaration in your main file, or only assign to window.APP exclusively.
Or use ES6 modules right away, and let your module bundler/loader deal with exposing them as expected.

duplicate 'row.names' are not allowed error

I used read_csv from the readr package

In my experience, the parameter row.names=NULL in the read.csv function will lead to a wrong reading of the file if a column name is missing, i.e. every column will be shifted.

read_csv solves this.

Android Studio: Can't start Git

Had to restart Android Studio after installing GIT for Windows.

Check if string has space in between (or anywhere)

This functions should help you...

bool isThereSpace(String s){
    return s.Contains(" ");
}

Can dplyr package be used for conditional mutating?

case_when is now a pretty clean implementation of the SQL-style case when:

structure(list(a = c(1, 3, 4, 6, 3, 2, 5, 1), b = c(1, 3, 4, 
2, 6, 7, 2, 6), c = c(6, 3, 6, 5, 3, 6, 5, 3), d = c(6, 2, 4, 
5, 3, 7, 2, 6), e = c(1, 2, 4, 5, 6, 7, 6, 3), f = c(2, 3, 4, 
2, 2, 7, 5, 2)), .Names = c("a", "b", "c", "d", "e", "f"), row.names = c(NA, 
8L), class = "data.frame") -> df


df %>% 
    mutate( g = case_when(
                a == 2 | a == 5 | a == 7 | (a == 1 & b == 4 )     ~   2,
                a == 0 | a == 1 | a == 4 |  a == 3 | c == 4       ~   3
))

Using dplyr 0.7.4

The manual: http://dplyr.tidyverse.org/reference/case_when.html

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

If you're using Webpack:

  1. Set up bootstrap-loader as described in docs;
  2. Install tether.js via npm;
  3. Add tether.js to the webpack ProvidePlugin plugin.

webpack.config.js:

plugins: [
        <... your plugins here>,
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery",
            "window.Tether": 'tether'
        })
    ]

Source

Recommended website resolution (width and height)?

Flexible or liquid layouts do restict design a little though, for example if you use background images that have to match the body background image.

I would rather make different css layouts for the site and have them apply depending on the user's resolution, or if that's not possible (have not digged into that yet), make it a choosable option.

Getting Current time to display in Label. VB.net

Use Date.Now instead of DateTime.Now

Get the size of a 2D array

In Java, 2D arrays are really arrays of arrays with possibly different lengths (there are no guarantees that in 2D arrays that the 2nd dimension arrays all be the same length)

You can get the length of any 2nd dimension array as z[n].length where 0 <= n < z.length.

If you're treating your 2D array as a matrix, you can simply get z.length and z[0].length, but note that you might be making an assumption that for each array in the 2nd dimension that the length is the same (for some programs this might be a reasonable assumption).

How to stop and restart memcached server?

sudo /etc/init.d/memcached restart

JQuery - File attributes

To get the filenames, use:

var files = document.getElementById('inputElementID').files;

Using jQuery (since you already are) you can adapt this to the following:

$('input[type="file"][multiple]').change(
    function(e){
        var files = this.files;
        for (i=0;i<files.length;i++){
            console.log(files[i].fileName + ' (' + files[i].fileSize + ').');
        }
        return false;
    });

JS Fiddle demo.

Adding link a href to an element using css

You cannot simply add a link using CSS. CSS is used for styling.

You can style your using CSS.

If you want to give a link dynamically to then I will advice you to use jQuery or Javascript.

You can accomplish that very easily using jQuery.

I have done a sample for you. You can refer that.

URL : http://jsfiddle.net/zyk9w/

$('#link').attr('href','http://www.google.com');

This single line will do the trick.

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

How to stop/terminate a python script from running?

  • To stop a python script just press Ctrl + C.
  • Inside a script with exit(), you can do it.
  • You can do it in an interactive script with just exit.
  • You can use pkill -f name-of-the-python-script.

Merge/flatten an array of arrays

You can use concat to merge arrays:

_x000D_
_x000D_
var arrays = [_x000D_
  ["$6"],_x000D_
  ["$12"],_x000D_
  ["$25"],_x000D_
  ["$25"],_x000D_
  ["$18"],_x000D_
  ["$22"],_x000D_
  ["$10"]_x000D_
];_x000D_
var merged = [].concat.apply([], arrays);_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

Using the apply method of concat will just take the second parameter as an array, so the last line is identical to this:

var merged2 = [].concat(["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]);

There is also the Array.prototype.flat() method (introduced in ES2019) which you could use to flatten the arrays, although it is only available in Node.js starting with version 11, and not at all in Internet Explorer.

_x000D_
_x000D_
const arrays = [_x000D_
      ["$6"],_x000D_
      ["$12"],_x000D_
      ["$25"],_x000D_
      ["$25"],_x000D_
      ["$18"],_x000D_
      ["$22"],_x000D_
      ["$10"]_x000D_
    ];_x000D_
const merge3 = arrays.flat(1); //The depth level specifying how deep a nested array structure should be flattened. Defaults to 1._x000D_
console.log(merge3);_x000D_
    
_x000D_
_x000D_
_x000D_

Set content of HTML <span> with Javascript

With modern browsers, you can set the textContent property, see Node.textContent:

var span = document.getElementById("myspan");
span.textContent = "some text";

UINavigationBar custom back button without title

I'm written an extension to make this easier:

extension UIViewController {

    /// Convenience for setting the back button, which will be used on any view controller that this one pushes onto the stack
    @objc var backButtonTitle: String? {
        get {
            return navigationItem.backBarButtonItem?.title
        }
        set {
            if let existingBackBarButtonItem = navigationItem.backBarButtonItem {
                existingBackBarButtonItem.title = newValue
            }
            else {
                let newNavigationItem = UIBarButtonItem(title: newValue, style:.plain, target: nil, action: nil)
                navigationItem.backBarButtonItem = newNavigationItem
            }
        }
    }

}

Android - How to achieve setOnClickListener in Kotlin?

Suppose you have textView to click

text_view.text = "Hello Kotlin";

text_view.setOnClickListener {
    val intent = Intent(this@MainActivity, SecondActivity::class.java)
    intent.putExtra("key", "Kotlin")
    startActivity(intent)
}

Set size on background image with CSS?

You can't set the size of your background image with the current version of CSS (2.1).

You can only set: position, fix, image-url, repeat-mode, and color.

How to SELECT in Oracle using a DBLINK located in a different schema?

I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.

Auto submit form on page load

This is the way it worked for me, because with other methods the form was sent empty:

<form name="yourform" id="yourform" method="POST" action="yourpage.html">
    <input type=hidden name="data" value="yourdata">
    <input type="submit" id="send" name="send" value="Send">
</form>
<script>            
    document.addEventListener("DOMContentLoaded", function(event) {
            document.createElement('form').submit.call(document.getElementById('yourform'));
            });         
</script>

How do I pass parameters into a PHP script through a webpage?

$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter

If you want to all the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

<?php
if ($_GET) {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
} else {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
?>

To call from command line chmod 755 /var/www/webroot/index.php and use

/usr/bin/php /var/www/webroot/index.php arg1 arg2

To call from the browser, use

http://www.mydomain.com/index.php?argument1=arg1&argument2=arg2

redirect COPY of stdout to log file from within bash script itself

Bash 4 has a coproc command which establishes a named pipe to a command and allows you to communicate through it.

Input jQuery get old value before onchange and get value after on change

The upvoted solution works for some situations but is not the ideal solution. The solution Bhojendra Rauniyar provided will only work in certain scenarios. The var inputVal will always remain the same, so changing the input multiple times would break the function.

The function may also break when using focus, because of the ?? (up/down) spinner on html number input. That is why J.T. Taylor has the best solution. By adding a data attribute you can avoid these problems:

<input id="my-textbox" type="text" data-initial-value="6" value="6" />

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

Since the question was asked the Angular team has solved this issue by making it possible to dynamically create input names.

With Angular version 1.3 and later you can now do this:

<form name="vm.myForm" novalidate>
  <div ng-repeat="p in vm.persons">
    <input type="text" name="person_{{$index}}" ng-model="p" required>
    <span ng-show="vm.myForm['person_' + $index].$invalid">Enter a name</span>
  </div>
</form>

Demo

Angular 1.3 also introduced ngMessages, a more powerful tool for form validation. You can use the same technique with ngMessages:

<form name="vm.myFormNgMsg" novalidate>
    <div ng-repeat="p in vm.persons">
      <input type="text" name="person_{{$index}}" ng-model="p" required>
      <span ng-messages="vm.myFormNgMsg['person_' + $index].$error">
        <span ng-message="required">Enter a name</span>
      </span>
    </div>
  </form>

Jackson overcoming underscores in favor of camel-case

You should use the @JsonProperty on the field you want to change the default name mapping.

class User{
    @JsonProperty("first_name")
    protected String firstName;
    protected String getFirstName(){return firstName;}
}

For more info: the API

AttributeError: 'module' object has no attribute 'model'

It's called models.Model and not models.model (case sensitive). Fix your Poll model like this -

class Poll(models.Model):
    question = models.CharField(max_length=200) 
    pub_date = models.DateTimeField('date published')

Combine two data frames by rows (rbind) when they have different sets of columns

gtools/smartbind didnt like working with Dates, probably because it was as.vectoring. So here's my solution...

sbind = function(x, y, fill=NA) {
    sbind.fill = function(d, cols){ 
        for(c in cols)
            d[[c]] = fill
        d
    }

    x = sbind.fill(x, setdiff(names(y),names(x)))
    y = sbind.fill(y, setdiff(names(x),names(y)))

    rbind(x, y)
}

Update int column in table with unique incrementing values

Assuming that you have a primary key for this table (you should have), as well as using a CTE or a WITH, it is also possible to use an update with a self-join to the same table:

UPDATE a
SET a.interfaceId = b.sequence
FROM prices a
INNER JOIN
(
   SELECT ROW_NUMBER() OVER ( ORDER BY b.priceId ) + ( SELECT MAX( interfaceId ) + 1 FROM prices ) AS sequence, b.priceId
   FROM prices b
   WHERE b.interfaceId IS NULL
) b ON b.priceId = a.priceId

I have assumed that the primary key is price-id.

The derived table, alias b, is used to generated the sequence via the ROW_NUMBER() function together with the primary key column(s). For each row where the column interface-id is NULL, this will generate a row with a unique sequence value together with the primary key value.

It is possible to order the sequence in some other order rather than the primary key.

The sequence is offset by the current MAX interface-id + 1 via a sub-query. The MAX() function ignores NULL values.

The WHERE clause limits the update to those rows that are NULL.

The derived table is then joined to the same table, alias a, joining on the primary key column(s) with the column to be updated set to the generated sequence.

Difference between _self, _top, and _parent in the anchor tag target attribute

target="_blank"

Opens a new window and show the related data.

target="_self"

Opens the window in the same frame, it means existing window itself.

target="_top"

Opens the linked document in the full body of the window.

target="_parent"

Opens data in the size of parent window.

Is the order of elements in a JSON list preserved?

Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine):

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

An array is an ordered sequence of zero or more values.

The terms "object" and "array" come from the conventions of JavaScript.

Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.

Initializing a struct to 0

I also thought this would work but it's misleading:

myStruct _m1 = {0};

When I tried this:

myStruct _m1 = {0xff};

Only the 1st byte was set to 0xff, the remaining ones were set to 0. So I wouldn't get into the habit of using this.

Merge two rows in SQL

There are a few ways depending on some data rules that you have not included, but here is one way using what you gave.

SELECT
    t1.Field1,
    t2.Field2
FROM Table1 t1
    LEFT JOIN Table1 t2 ON t1.FK = t2.FK AND t2.Field1 IS NULL

Another way:

SELECT
    t1.Field1,
    (SELECT Field2 FROM Table2 t2 WHERE t2.FK = t1.FK AND Field1 IS NULL) AS Field2
FROM Table1 t1

CMake output/build directory

There's little need to set all the variables you're setting. CMake sets them to reasonable defaults. You should definitely not modify CMAKE_BINARY_DIR or CMAKE_CACHEFILE_DIR. Treat these as read-only.

First remove the existing problematic cache file from the src directory:

cd src
rm CMakeCache.txt
cd ..

Then remove all the set() commands and do:

cd Compile && rm -rf *
cmake ../src

As long as you're outside of the source directory when running CMake, it will not modify the source directory unless your CMakeList explicitly tells it to do so.

Once you have this working, you can look at where CMake puts things by default, and only if you're not satisfied with the default locations (such as the default value of EXECUTABLE_OUTPUT_PATH), modify only those you need. And try to express them relative to CMAKE_BINARY_DIR, CMAKE_CURRENT_BINARY_DIR, PROJECT_BINARY_DIR etc.

If you look at CMake documentation, you'll see variables partitioned into semantic sections. Except for very special circumstances, you should treat all those listed under "Variables that Provide Information" as read-only inside CMakeLists.

How to switch to other branch in Source Tree to commit the code?

Hi I'm also relatively new but I can give you basic help.

  1. To switch to another branch use "Checkout". Just click on your branch and then on the button "checkout" at the top.

UPDATE 12.01.2016:

The bold line is the current branch.

You can also just double click a branch to use checkout.


  1. Your first answer I think depends on the repository you use (like github or bitbucket). Maybe the "Show hosted repository"-Button can help you (Left panel, bottom, right button = database with cog)

And here some helpful links:

Easy Git Guide

Git-flow - Git branching model

Tips on branching with sourcetree

Use PHP composer to clone git repo

At the time of writing in 2013, this was one way to do it. Composer has added support for better ways: See @igorw 's answer

DO YOU HAVE A REPOSITORY?

Git, Mercurial and SVN is supported by Composer.

DO YOU HAVE WRITE ACCESS TO THE REPOSITORY?

Yes?

DOES THE REPOSITORY HAVE A composer.json FILE

If you have a repository you can write to: Add a composer.json file, or fix the existing one, and DON'T use the solution below.

Go to @igorw 's answer

ONLY USE THIS IF YOU DON'T HAVE A REPOSITORY
OR IF THE REPOSITORY DOES NOT HAVE A composer.json AND YOU CANNOT ADD IT

This will override everything that Composer may be able to read from the original repository's composer.json, including the dependencies of the package and the autoloading.

Using the package type will transfer the burden of correctly defining everything onto you. The easier way is to have a composer.json file in the repository, and just use it.

This solution really only is for the rare cases where you have an abandoned ZIP download that you cannot alter, or a repository you can only read, but it isn't maintained anymore.

"repositories": [
    {
        "type":"package",
        "package": {
          "name": "l3pp4rd/doctrine-extensions",
          "version":"master",
          "source": {
              "url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
              "type": "git",
              "reference":"master"
            }
        }
    }
],
"require": {
    "l3pp4rd/doctrine-extensions": "master"
}

Android: making a fullscreen application

Update Answer I added android:windowIsTranslucent in case you have white screen in start of activity

just create new Style in values/styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <!-- to hide white screen in start of window -->
    <item name="android:windowIsTranslucent">true</item>
    </style>

</resources>

from your AndroidManifest.xml add style to your activity

android:theme="@style/AppTheme"

to be like this

<activity android:name=".Splash"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

eclipse stuck when building workspace

Unselect automatic build using Eclipse-> Windows->Preferences helps fixing this issue.

What Regex would capture everything from ' mark to the end of a line?

When I tried '.* in windows (Notepad ++) it would match everything after first ' until end of last line.

To capture everything until end of that line I typed the following:

'.*?\n

This would only capture everything from ' until end of that line.

Redirect echo output in shell script to logfile

#!/bin/sh
# http://www.tldp.org/LDP/abs/html/io-redirection.html
echo "Hello World"
exec > script.log 2>&1
echo "Start logging out from here to a file"
bad command
echo "End logging out from here to a file"
exec > /dev/tty 2>&1 #redirects out to controlling terminal
echo "Logged in the terminal"

Output:

> ./above_script.sh                                                                
Hello World
Not logged in the file
> cat script.log
Start logging out from here to a file
./logging_sample.sh: line 6: bad: command not found
End logging out from here to a file

Read more here: http://www.tldp.org/LDP/abs/html/io-redirection.html

jQuery ajax success callback function definition

In your component i.e angular JS code:

function getData(){
    window.location.href = 'http://localhost:1036/api/Employee/GetExcelData';
}

HTML Form: Select-Option vs Datalist-Option

To specifically answer a part of your question "Is there any situation in which it would be better to use one or the other?", consider a form with repeating sections. If the repeating section contains many select tags, then the options must be rendered for each select, for every row.

In such a case, I would consider using datalist with input, because the same datalist can be used for any number of inputs. This could potentially save a large amount of rendering time on the server, and would scale much better to any number of rows.

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

from pip.req import parse_requirements did not work for me and I think it's for the blank lines in my requirements.txt, but this function does work

def parse_requirements(requirements):
    with open(requirements) as f:
        return [l.strip('\n') for l in f if l.strip('\n') and not l.startswith('#')]

reqs = parse_requirements(<requirements_path>)

setup(
    ...
    install_requires=reqs,
    ...
)

How does one parse XML files?

Use XmlTextReader, XmlReader, XmlNodeReader and the System.Xml.XPath namespace. And (XPathNavigator, XPathDocument, XPathExpression, XPathnodeIterator).

Usually XPath makes reading XML easier, which is what you might be looking for.

I want to calculate the distance between two points in Java

Math.sqrt returns a double so you'll have to cast it to int as well

distance = (int)Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));

How to send multiple data fields via Ajax?

You can send data through JSON or via normal POST, here is an example for JSON.

 var value1 = 1;
 var value2 = 2;
 var value3 = 3;   
 $.ajax({
      type: "POST",
      contentType: "application/json; charset=utf-8",
      url: "yoururlhere",
      data: { data1: value1, data2: value2, data3: value3 },
      success: function (result) {
           // do something here
      }
 });

If you want to use it via normal post try this

 $.ajax({
      type: "POST",
      url: $('form').attr("action"),   
      data: $('#form0').serialize(),
      success: function (result) {
         // do something here
      }
 });

Sending an HTTP POST request on iOS

-(void)sendingAnHTTPPOSTRequestOniOSWithUserEmailId: (NSString *)emailId withPassword: (NSString *)password{
//Init the NSURLSession with a configuration
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

//Create an URLRequest
NSURL *url = [NSURL URLWithString:@"http://www.example.com/apis/login_api"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

//Create POST Params and add it to HTTPBody
NSString *params = [NSString stringWithFormat:@"email=%@&password=%@",emailId,password];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

//Create task
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    //Handle your response here
    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
     NSLog(@"%@",responseDict);
}];
   [dataTask resume];
}

How to remove white space characters from a string in SQL Server

There may be 2 spaces after the text, please confirm. You can use LTRIM and RTRIM functions also right?

LTRIM(RTRIM(ProductAlternateKey))

Maybe the extra space isn't ordinary spaces (ASCII 32, soft space)? Maybe they are "hard space", ASCII 160?

ltrim(rtrim(replace(ProductAlternateKey, char(160), char(32))))

What is the difference between the dot (.) operator and -> in C++?

Dot operator can't be overloaded, arrow operator can be overloaded. Arrow operator is generally meant to be applied to pointers (or objects that behave like pointers, like smart pointers). Dot operator can't be applied to pointers.

EDIT When applied to pointer arrow operator is equivalent to applying dot operator to pointee e.g. ptr->field is equivalent to (*ptr).field.

Richtextbox wpf binding

I have tuned up previous code a little bit. First of all range.Changed hasn't work for me. After I changed range.Changed to richTextBox.TextChanged it turns out that TextChanged event handler can invoke SetDocumentXaml recursively, so I've provided protection against it. I also used XamlReader/XamlWriter instead of TextRange.

public class RichTextBoxHelper : DependencyObject
{
    private static HashSet<Thread> _recursionProtection = new HashSet<Thread>();

    public static string GetDocumentXaml(DependencyObject obj)
    {
        return (string)obj.GetValue(DocumentXamlProperty);
    }

    public static void SetDocumentXaml(DependencyObject obj, string value)
    {
        _recursionProtection.Add(Thread.CurrentThread);
        obj.SetValue(DocumentXamlProperty, value);
        _recursionProtection.Remove(Thread.CurrentThread);
    }

    public static readonly DependencyProperty DocumentXamlProperty = DependencyProperty.RegisterAttached(
        "DocumentXaml", 
        typeof(string), 
        typeof(RichTextBoxHelper), 
        new FrameworkPropertyMetadata(
            "", 
            FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            (obj, e) => {
                if (_recursionProtection.Contains(Thread.CurrentThread))
                    return;

                var richTextBox = (RichTextBox)obj;

                // Parse the XAML to a document (or use XamlReader.Parse())

                try
                {
                    var stream = new MemoryStream(Encoding.UTF8.GetBytes(GetDocumentXaml(richTextBox)));
                    var doc = (FlowDocument)XamlReader.Load(stream);

                    // Set the document
                    richTextBox.Document = doc;
                }
                catch (Exception)
                {
                    richTextBox.Document = new FlowDocument();
                }

                // When the document changes update the source
                richTextBox.TextChanged += (obj2, e2) =>
                {
                    RichTextBox richTextBox2 = obj2 as RichTextBox;
                    if (richTextBox2 != null)
                    {
                        SetDocumentXaml(richTextBox, XamlWriter.Save(richTextBox2.Document));
                    }
                };
            }
        )
    );
}

How to dynamic new Anonymous Class?

You can create an ExpandoObject like this:

IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;

And after casting it to dynamic, those values will look like properties:

dynamic d = expando;
Console.WriteLine(d.Name);

However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:

d.GetType().GetProperty("Name") 

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Plugin with id 'com.google.gms.google-services' not found

In build.gradle(Module:app) add this code

dependencies {
    ……..
    compile 'com.google.android.gms:play-services:10.0.1’
    ……  
}

If you still have a problem after that, then add this code in build.gradle(Module:app)

defaultConfig {
    ….
    …...
    multiDexEnabled true
}


dependencies {
    …..
    compile 'com.google.android.gms:play-services:10.0.1'
    compile 'com.android.support:multidex:1.0.1'
}

Get names of all files from a folder with Ruby

You may also want to use Rake::FileList (provided you have rake dependency):

FileList.new('lib/*') do |file|
  p file
end

According to the API:

FileLists are lazy. When given a list of glob patterns for possible files to be included in the file list, instead of searching the file structures to find the files, a FileList holds the pattern for latter use.

https://docs.ruby-lang.org/en/2.1.0/Rake/FileList.html

Fixed page header overlaps in-page anchors

I think this approach is more useful:

<h2 id="bar" title="Bar">Bar</h2>

[id]:target {
    display: block;
    position: relative;
    top: -120px;
    visibility: hidden;
}

[id]:target::before {
    content: attr(title);
    top: 120px;
    position: relative;
    visibility: visible;
}

What is the best alternative IDE to Visual Studio

There are many alternatives, check this list: Alternative IDEs to Visual Studio.NET, mirrored on Web Archive because the original link is down.

How to get the jQuery $.ajax error response text?

For me, this simply works:

error: function(xhr, status, error) {
  alert(xhr.responseText);
}

Is recursion ever faster than looping?

Tail recursion is as fast as looping. Many functional languages have tail recursion implemented in them.

Twitter Bootstrap: div in container with 100% height

It is very simple. You can use

.fill .map 
{
  min-height: 100vh;
}

You can change height according to your requirement.

cannot download, $GOPATH not set

(for MAC)

I tried all these answers and, for some still unknown reason, none of them worked.

I had to "force feed" the GOPATH by setting the environment variable per every command that required it. For example:

sudo env GOPATH=$HOME/goWorkDirectory go build ...

Even glide was giving me the GOPATH not set error. Resolved it, again, by "force feeding": I tried all these answers and, for some still unknown reason, none of them worked.

I had to "force feed" the GOPATH by setting the environment variable per every command that required it.

sudo env GOPATH=$HOME/goWorkDirectory glide install

Hope this helps someone.

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

First off, if you're using savefig, be aware that it will override the figure's background color when saving unless you specify otherwise (e.g. fig.savefig('blah.png', transparent=True)).

However, to remove the axes' and figure's background on-screen, you'll need to set both ax.patch and fig.patch to be invisible.

E.g.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

for item in [fig, ax]:
    item.patch.set_visible(False)

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

(Of course, you can't tell the difference on SO's white background, but everything is transparent...)

If you don't want to show anything other than the line, turn the axis off as well using ax.axis('off'):

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

fig.patch.set_visible(False)
ax.axis('off')

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

In that case, though, you may want to make the axes take up the full figure. If you manually specify the location of the axes, you can tell it to take up the full figure (alternately, you can use subplots_adjust, but this is simpler for the case of a single axes).

import matplotlib.pyplot as plt

fig = plt.figure(frameon=False)
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

ax.plot(range(10))

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

Include files from parent or other directory

Any path beginning with a slash will be an absolute path. From the root-folder of the server and not the root-folder of your document root. You can use ../ to go into the parent directory.

Margin-Top not working for span element?

Always remember one thing we can not apply margin vertically to inline elements ,if you want to apply then change its display type to block or inline block.for example span{display:inline-block;}

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

I don't like all the solutions that use magic numbers like 97 or 36.

const A = 'A'.charCodeAt(0);

let numberToCharacter = number => String.fromCharCode(A + number);

let characterToNumber = character => character.charCodeAt(0) - A;

this assumes uppercase letters and starts 'A' at 0.

An error occurred while executing the command definition. See the inner exception for details

In my case, It was from Stored Producers. I was removed a field from table and forgotten to remove it from my SP.

How to make layout with View fill the remaining space?

Answer from woodshy worked for me, and it is simpler than the answer by Ungureanu Liviu since it does not use RelativeLayout. I am giving my layout for clarity:

<LinearLayout 
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal"
      >

     <Button
        android:layout_width = "80dp"
        android:layout_weight = "0"
        android:layout_height = "wrap_content"
        android:text="&lt;"/>
     <TextView
        android:layout_width = "fill_parent"
        android:layout_height = "wrap_content"
        android:layout_weight = "1"/>
     <Button
        android:layout_width = "80dp"
        android:layout_weight = "0"
        android:layout_height = "wrap_content"
        android:text="&gt;"/>   
 </LinearLayout>

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

Is there a 'foreach' function in Python 3?

The correct answer is "python collections do not have a foreach". In native python we need to resort to the external for _element_ in _collection_ syntax which is not what the OP is after.

Python is in general quite weak for functionals programming. There are a few libraries to mitigate a bit. I helped author one of these infixpy https://pypi.org/project/infixpy/

from infixpy import Seq
(Seq([1,2,3]).foreach(lambda x: print(x)))
1
2
3

Also see: Left to right application of operations on a list in Python 3

How to find the minimum value in an ArrayList, along with the index number? (Java)

There is an easier way to find a min integer in array list:

int min = array.get(0);
        for (int i : array){
            min = min < i ? min : i;
        }

How can I make Flexbox children 100% height of their parent?

.container { . . . . align-items: stretch; . . . . }

How to make a JFrame Modal in Swing java

The only code that have worked for me:

childFrame.setAlwaysOnTop(true);

This code should be called on the main/parent frame before making the child/modal frame visible. Your child/modal frame should also have this code:

parentFrame.setFocusableWindowState(false);
this.mainFrame.setEnabled(false);

Oracle query execution time

Use:

set serveroutput on
variable n number
exec :n := dbms_utility.get_time;
select ......
exec dbms_output.put_line( (dbms_utility.get_time-:n)/100) || ' seconds....' );

Or possibly:

SET TIMING ON;

-- do stuff

SET TIMING OFF;

...to get the hundredths of seconds that elapsed.

In either case, time elapsed can be impacted by server load/etc.

Reference:

What does string::npos mean in this code?

The document for string::npos says:

npos is a static member constant value with the greatest possible value for an element of type size_t.

As a return value it is usually used to indicate failure.

This constant is actually defined with a value of -1 (for any trait), which because size_t is an unsigned integral type, becomes the largest possible representable value for this type.

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

use this

<div id="date">23/05/2013</div>
<script type="text/javascript">
$(document).ready(function(){
  var x = $("#date").text();
    x.text(x.substring(0, 2) + '<br />'+x.substring(3));     
});
</script>

jQuery 'input' event

Be Careful while using INPUT. This event fires on focus and on blur in IE 11. But it is triggered on change in other browsers.

https://connect.microsoft.com/IE/feedback/details/810538/ie-11-fires-input-event-on-focus

How do I select an element in jQuery by using a variable for the ID?

The shortest way would be:

$("#" + row_id)

Limiting the search to the body doesn't have any benefit.

Also, you should consider renaming your ids to something more meaningful (and HTML compliant as per Paolo's answer), especially if you have another set of data that needs to be named as well.

Javascript - Get Image height

Try with JQuery:

<script type="text/javascript">
function jquery_get_width_height()
{
    var imgWidth = $("#img").width();
    var imgHeight = $("#img").height();
    alert("JQuery -- " + "imgWidth: " + imgWidth + " - imgHeight: " + imgHeight);
}
</script>

or

<script type="text/javascript">
function javascript_get_width_height()
{
    var img = document.getElementById('img');
    alert("JavaSript -- " + "imgWidth: " + img.width + " - imgHeight: " + img.height);
}
</script>

Dynamic constant assignment

Your problem is that each time you run the method you are assigning a new value to the constant. This is not allowed, as it makes the constant non-constant; even though the contents of the string are the same (for the moment, anyhow), the actual string object itself is different each time the method is called. For example:

def foo
  p "bar".object_id
end

foo #=> 15779172
foo #=> 15779112

Perhaps if you explained your use case—why you want to change the value of a constant in a method—we could help you with a better implementation.

Perhaps you'd rather have an instance variable on the class?

class MyClass
  class << self
    attr_accessor :my_constant
  end
  def my_method
    self.class.my_constant = "blah"
  end
end

p MyClass.my_constant #=> nil
MyClass.new.my_method

p MyClass.my_constant #=> "blah"

If you really want to change the value of a constant in a method, and your constant is a String or an Array, you can 'cheat' and use the #replace method to cause the object to take on a new value without actually changing the object:

class MyClass
  BAR = "blah"

  def cheat(new_bar)
    BAR.replace new_bar
  end
end

p MyClass::BAR           #=> "blah"
MyClass.new.cheat "whee"
p MyClass::BAR           #=> "whee"

CREATE TABLE LIKE A1 as A2

You can use below query to create table and insert distinct values into this table:

Select Distinct Column1, Column2, Column3 into New_Users from Old_Users

Shall we always use [unowned self] inside closure in Swift

I thought I would add some concrete examples specifically for a view controller. Many of the explanations, not just here on Stack Overflow, are really good, but I work better with real world examples (@drewag had a good start on this):

  • If you have a closure to handle a response from a network requests use weak, because they are long lived. The view controller could close before the request completes so self no longer points to a valid object when the closure is called.
  • If you have closure that handles an event on a button. This can be unowned because as soon as the view controller goes away, the button and any other items it may be referencing from self goes away at the same time. The closure block will also go away at the same time.

    class MyViewController: UIViewController {
          @IBOutlet weak var myButton: UIButton!
          let networkManager = NetworkManager()
          let buttonPressClosure: () -> Void // closure must be held in this class. 
    
          override func viewDidLoad() {
              // use unowned here
              buttonPressClosure = { [unowned self] in
                  self.changeDisplayViewMode() // won't happen after vc closes. 
              }
              // use weak here
              networkManager.fetch(query: query) { [weak self] (results, error) in
                  self?.updateUI() // could be called any time after vc closes
              }
          }
          @IBAction func buttonPress(self: Any) {
             buttonPressClosure()
          }
    
          // rest of class below.
     }
    

split string only on first instance of specified character

This should be quite fast

function splitOnFirst (str, sep) {
  const index = str.indexOf(sep);
  return index < 0 ? [str] : [str.slice(0, index), str.slice(index + sep.length)];
}

Unfamiliar symbol in algorithm: what does ? mean?

The upside-down A symbol is the universal quantifier from predicate logic. (Also see the more complete discussion of the first-order predicate calculus.) As others noted, it means that the stated assertions holds "for all instances" of the given variable (here, s). You'll soon run into its sibling, the backwards capital E, which is the existential quantifier, meaning "there exists at least one" of the given variable conforming to the related assertion.

If you're interested in logic, you might enjoy the book Logic and Databases: The Roots of Relational Theory by C.J. Date. There are several chapters covering these quantifiers and their logical implications. You don't have to be working with databases to benefit from this book's coverage of logic.

Construct pandas DataFrame from items in nested dictionary

A pandas MultiIndex consists of a list of tuples. So the most natural approach would be to reshape your input dict so that its keys are tuples corresponding to the multi-index values you require. Then you can just construct your dataframe using pd.DataFrame.from_dict, using the option orient='index':

user_dict = {12: {'Category 1': {'att_1': 1, 'att_2': 'whatever'},
                  'Category 2': {'att_1': 23, 'att_2': 'another'}},
             15: {'Category 1': {'att_1': 10, 'att_2': 'foo'},
                  'Category 2': {'att_1': 30, 'att_2': 'bar'}}}

pd.DataFrame.from_dict({(i,j): user_dict[i][j] 
                           for i in user_dict.keys() 
                           for j in user_dict[i].keys()},
                       orient='index')


               att_1     att_2
12 Category 1      1  whatever
   Category 2     23   another
15 Category 1     10       foo
   Category 2     30       bar

An alternative approach would be to build your dataframe up by concatenating the component dataframes:

user_ids = []
frames = []

for user_id, d in user_dict.iteritems():
    user_ids.append(user_id)
    frames.append(pd.DataFrame.from_dict(d, orient='index'))

pd.concat(frames, keys=user_ids)

               att_1     att_2
12 Category 1      1  whatever
   Category 2     23   another
15 Category 1     10       foo
   Category 2     30       bar

Android: Create spinner programmatically from array

In Kotlin language you can do it in this way:

val values = arrayOf(
    "cat",
    "dog",
    "chicken"
)

ArrayAdapter(
    this,
    android.R.layout.simple_spinner_item,
    values
).also {
    it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    spinner.adapter = it
}

Get input type="file" value when it has multiple files selected

You use input.files property. It's a collection of File objects and each file has a name property:

onmouseout="for (var i = 0; i < this.files.length; i++) alert(this.files[i].name);"

Send file via cURL from form POST in PHP

For my the @ symbol did not work, so I do some research and found this way and it work for me, I hope this help you.

    $target_url = "http://server:port/xxxxx.php";           
    $fname = 'file.txt';   
    $cfile = new CURLFile(realpath($fname));

        $post = array (
                  'file' => $cfile
                  );    

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $target_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");   
    curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);   
    curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 100);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

    $result = curl_exec ($ch);

    if ($result === FALSE) {
        echo "Error sending" . $fname .  " " . curl_error($ch);
        curl_close ($ch);
    }else{
        curl_close ($ch);
        echo  "Result: " . $result;
    }   

Which keycode for escape key with jQuery

Try with the keyup event:

$(document).keyup(function(e) {
  if (e.keyCode === 13) $('.save').click();     // enter
  if (e.keyCode === 27) $('.cancel').click();   // esc
});

Pandas DataFrame to List of Dictionaries

If you are interested in only selecting one column this will work.

df[["item1"]].to_dict("records")

The below will NOT work and produces a TypeError: unsupported type: . I believe this is because it is trying to convert a series to a dict and not a Data Frame to a dict.

df["item1"].to_dict("records")

I had a requirement to only select one column and convert it to a list of dicts with the column name as the key and was stuck on this for a bit so figured I'd share.

How to implement authenticated routes in React Router 4?

(Using Redux for state management)

If user try to access any url, first i am going to check if access token available, if not redirect to login page, Once user logs in using login page, we do store that in localstorage as well as in our redux state. (localstorage or cookies..we keep this topic out of context for now).
since redux state as updated and privateroutes will be rerendered. now we do have access token so we gonna redirect to home page.

Store the decoded authorization payload data as well in redux state and pass it to react context. (We dont have to use context but to access authorization in any of our nested child components it makes easy to access from context instead connecting each and every child component to redux)..

All the routes that don't need special roles can be accessed directly after login.. If it need role like admin (we made a protected route which checks whether he had desired role if not redirects to unauthorized component)

similarly in any of your component if you have to disable button or something based on role.

simply you can do in this way

const authorization = useContext(AuthContext);
const [hasAdminRole] = checkAuth({authorization, roleType:"admin"});
const [hasLeadRole] = checkAuth({authorization, roleType:"lead"});
<Button disable={!hasAdminRole} />Admin can access</Button>
<Button disable={!hasLeadRole || !hasAdminRole} />admin or lead can access</Button>

So what if user try to insert dummy token in localstorage. As we do have access token, we will redirect to home component. My home component will make rest call to grab data, since jwt token was dummy, rest call will return unauthorized user. So i do call logout (which will clear localstorage and redirect to login page again). If home page has static data and not making any api calls(then you should have token-verify api call in the backend so that you can check if token is REAL before loading home page)

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Switch } from 'react-router-dom';
import history from './utils/history';


import Store from './statemanagement/store/configureStore';
import Privateroutes from './Privateroutes';
import Logout from './components/auth/Logout';

ReactDOM.render(
  <Store>
    <Router history={history}>
      <Switch>
        <Route path="/logout" exact component={Logout} />
        <Route path="/" exact component={Privateroutes} />
        <Route path="/:someParam" component={Privateroutes} />
      </Switch>
    </Router>
  </Store>,
  document.querySelector('#root')
);

History.js

import { createBrowserHistory as history } from 'history';

export default history({});

Privateroutes.js

import React, { Fragment, useContext } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { AuthContext, checkAuth } from './checkAuth';
import App from './components/App';
import Home from './components/home';
import Admin from './components/admin';
import Login from './components/auth/Login';
import Unauthorized from './components/Unauthorized ';
import Notfound from './components/404';

const ProtectedRoute = ({ component: Component, roleType, ...rest })=> { 
const authorization = useContext(AuthContext);
const [hasRequiredRole] = checkAuth({authorization, roleType});
return (
<Route
  {...rest}
  render={props => hasRequiredRole ? 
  <Component {...props} /> :
   <Unauthorized {...props} />  } 
/>)}; 

const Privateroutes = props => {
  const { accessToken, authorization } = props.authData;
  if (accessToken) {
    return (
      <Fragment>
       <AuthContext.Provider value={authorization}>
        <App>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/login" render={() => <Redirect to="/" />} />
            <Route exact path="/home" component={Home} />
            <ProtectedRoute
            exact
            path="/admin"
            component={Admin}
            roleType="admin"
          />
            <Route path="/404" component={Notfound} />
            <Route path="*" render={() => <Redirect to="/404" />} />
          </Switch>
        </App>
        </AuthContext.Provider>
      </Fragment>
    );
  } else {
    return (
      <Fragment>
        <Route exact path="/login" component={Login} />
        <Route exact path="*" render={() => <Redirect to="/login" />} />
      </Fragment>
    );
  }
};

// my user reducer sample
// const accessToken = localStorage.getItem('token')
//   ? JSON.parse(localStorage.getItem('token')).accessToken
//   : false;

// const initialState = {
//   accessToken: accessToken ? accessToken : null,
//   authorization: accessToken
//     ? jwtDecode(JSON.parse(localStorage.getItem('token')).accessToken)
//         .authorization
//     : null
// };

// export default function(state = initialState, action) {
// switch (action.type) {
// case actionTypes.FETCH_LOGIN_SUCCESS:
//   let token = {
//                  accessToken: action.payload.token
//               };
//   localStorage.setItem('token', JSON.stringify(token))
//   return {
//     ...state,
//     accessToken: action.payload.token,
//     authorization: jwtDecode(action.payload.token).authorization
//   };
//    default:
//         return state;
//    }
//    }

const mapStateToProps = state => {
  const { authData } = state.user;
  return {
    authData: authData
  };
};

export default connect(mapStateToProps)(Privateroutes);

checkAuth.js

import React from 'react';

export const AuthContext = React.createContext();

export const checkAuth = ({ authorization, roleType }) => {
  let hasRequiredRole = false;

  if (authorization.roles ) {
    let roles = authorization.roles.map(item =>
      item.toLowerCase()
    );

    hasRequiredRole = roles.includes(roleType);
  }

  return [hasRequiredRole];
};

DECODED JWT TOKEN SAMPLE

{
  "authorization": {
    "roles": [
      "admin",
      "operator"
    ]
  },
  "exp": 1591733170,
  "user_id": 1,
  "orig_iat": 1591646770,
  "email": "hemanthvrm@stackoverflow",
  "username": "hemanthvrm"
}

Css Move element from left to right animated

It's because you aren't giving the un-hovered state a right attribute.

right isn't set so it's trying to go from nothing to 0px. Obviously because it has nothing to go to, it just 'warps' over.

If you give the unhovered state a right:90%;, it will transition how you like.

Just as a side note, if you still want it to be on the very left of the page, you can use the calc css function.

Example:

right: calc(100% - 100px)
                     ^ width of div

You don't have to use left then.

Also, you can't transition using left or right auto and will give the same 'warp' effect.

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
    background:red;_x000D_
    transition:2s;_x000D_
    -webkit-transition:2s;_x000D_
    -moz-transition:2s;_x000D_
    position:absolute;_x000D_
    right:calc(100% - 100px);_x000D_
}_x000D_
div:hover {_x000D_
  right:0;_x000D_
}
_x000D_
<p>_x000D_
  <b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions._x000D_
</p>_x000D_
<div></div>_x000D_
<p>Hover over the red square to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

CanIUse says that the calc() function only works on IE10+

Android: Changing Background-Color of the Activity (Main View)

Try creating a method in your Activity something like...

public void setActivityBackgroundColor(int color) {
    View view = this.getWindow().getDecorView();
    view.setBackgroundColor(color);
}

Then call it from your OnClickListener passing in whatever colour you want.

Android XXHDPI resources

The DPI of the screen of the Nexus 10 is ±300, which is in the unofficial xhdpi range of 280-400.

Usually, devices use resources designed for their density. But there are exceptions, and exceptions might be added in the future. The Nexus 10 uses xxhdpi resources when it comes to launcher icons.

The standard quantised DPI for xxhdpi is 480 (which means screens with a DPI somewhere in the range of 400-560 are probably xxhdpi).

How to check if a String contains any letter from a to z?

You can look for regular expression

Regex.IsMatch(str, @"^[a-zA-Z]+$");

How do I disable fail_on_empty_beans in Jackson?

In Jersey Rest Services just use the JacksonFeatures annotation ...

@JacksonFeatures(serializationDisable = {SerializationFeature.FAIL_ON_EMPTY_BEANS})
public Response getSomething() {
    Object entity = doSomething();
    return Response.ok(entity).build();
}

How to modify STYLE attribute of element with known ID using JQuery

Use the CSS function from jQuery to set styles to your items :

$('#buttonId').css({ "background-color": 'brown'});

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Another option would be using flexbox.

While it's not supported by IE8 and IE9, you could consider:

  • Not minding about those old IE versions
  • Providing a fallback
  • Using a polyfill

Despite some additional browser-specific style prefixing would be necessary for full cross-browser support, you can see the basic usage either on this fiddle and on the following snippet:

_x000D_
_x000D_
html {_x000D_
  height: 100%;_x000D_
}_x000D_
html body {_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
  width: 100%;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
    background-color: #4C4;_x000D_
    min-height: 50px;_x000D_
    width: 100%;_x000D_
}_x000D_
footer {_x000D_
    background-color: #4C4;_x000D_
    min-height: 30px;_x000D_
    width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
_x000D_
_x000D_

CSS background-image - What is the correct usage?

The path can either be full or relative (of course if the image is from another domain it must be full).

You don't need to use quotes in the URI; the syntax can either be:

background-image: url(image.jpg);

Or

background-image: url("image.jpg");

However, from W3:

Some characters appearing in an unquoted URI, such as parentheses, white space characters, single quotes (') and double quotes ("), must be escaped with a backslash so that the resulting URI value is a URI token: '\(', '\)'.

So in instances such as these it is either necessary to use quotes or double quotes, or escape the characters.

Does java have a int.tryparse that doesn't throw an exception for bad data?

No. You have to make your own like this:

boolean tryParseInt(String value) {  
     try {  
         Integer.parseInt(value);  
         return true;  
      } catch (NumberFormatException e) {  
         return false;  
      }  
}

...and you can use it like this:

if (tryParseInt(input)) {  
   Integer.parseInt(input);  // We now know that it's safe to parse
}

EDIT (Based on the comment by @Erk)

Something like follows should be better

public int tryParse(String value, int defaultVal) {
    try {
        return Integer.parseInt(value);
    } catch (NumberFormatException e) {
        return defaultVal;
    }
}

When you overload this with a single string parameter method, it would be even better, which will enable using with the default value being optional.

public int tryParse(String value) {
    return tryParse(value, 0)
}

Python: Removing spaces from list objects

for element in range(0,len(hello)):
      d[element] = hello[element].strip()

Angular is automatically adding 'ng-invalid' class on 'required' fields

Since the fields are empty they are not valid, so the ng-invalid and ng-invalid-required classes are added properly.

You can use the class ng-pristine to check out whether the fields have already been used or not.

Java Webservice Client (Best way)

What is the best approach to do this JAVA?

I would personally NOT use Axis 2, even for client side development only. Here is why I stay away from it:

  1. I don't like its architecture and hate its counter productive deployment model.
  2. I find it to be low quality project.
  3. I don't like its performances (see this benchmark against JAX-WS RI).
  4. It's always a nightmare to setup dependencies (I use Maven and I always have to fight with the gazillion of dependencies) (see #2)
  5. Axis sucked big time and Axis2 isn't better. No, this is not a personal opinion, there is a consensus.
  6. I suffered once, never again.

The only reason Axis is still around is IMO because it's used in Eclipse since ages. Thanks god, this has been fixed in Eclipse Helios and I hope Axis2 will finally die. There are just much better stacks.

I read about SAAJ, looks like that will be more granular level of approach?

To do what?

Is there any other way than using the WSDL2Java tool, to generate the code. Maybe wsimport in another option. What are the pros and cons?

Yes! Prefer a JAX-WS stack like CXF or JAX-WS RI (you might also read about Metro, Metro = JAX-WS RI + WSIT), they are just more elegant, simpler, easier to use. In your case, I would just use JAX-WS RI which is included in Java 6 and thus wsimport.

Can someone send the links for some good tutorials on these topics?

That's another pro, there are plenty of (good quality) tutorials for JAX-WS, see for example:

What are the options we need to use while generating the code using the WSDL2Java?

No options, use wsimport :)

See also

Related questions

Where is Xcode's build folder?

It should by located in: ~/Library/Developer/Xcode/DerivedData.

If you changed the defaults, you can see where the build directory is by going to File->Workspace Settings then look at Build Location

How to avoid page refresh after button click event in asp.net

Set MaintainScrollPositionOnPostBack="true" in the page declaration:

<%@ Page Language="C#" MaintainScrollPositionOnPostBack="true" Title="Home" %>

The apk must be signed with the same certificates as the previous version

My [silly] mistake was that i used app-debug.apk file instead of app-release.apk file. You need to to choose "release" in "Build Variants" frame when you generate signed APK. The app-release.apk file should be located under "app\release" folder in your project root.

How to copy a file to another path?

File.Move(@"c:\filename", @"c:\filenamet\filename.txt");

Command to get latest Git commit hash from a branch

git log -n 1 [branch_name]

branch_name (may be remote or local branch) is optional. Without branch_name, it will show the latest commit on the current branch.

For example:

git log -n 1
git log -n 1 origin/master
git log -n 1 some_local_branch

git log -n 1 --pretty=format:"%H"  #To get only hash value of commit

How do I clone a single branch in Git?

If you want a shallow clone, you can do this with:

git clone -b mybranch --depth=1 https://example.com/myproject.git localname

--depth=1 implies --single-branch.

How to refresh Android listview?

if you are not still satisfied with ListView Refreshment, you can look at this snippet,this is for loading the listView from DB, Actually what you have to do is simply reload the ListView,after you perform any CRUD Operation Its not a best way to code, but it will refresh the ListView as you wish..

It works for Me....if u find better solution,please Share...

.......
......
do your CRUD Operations..
......
.....
DBAdapter.open();
DBAdapter.insert_into_SingleList();
// Bring that DB_results and add it to list as its contents....
                                            ls2.setAdapter(new ArrayAdapter(DynTABSample.this,
    android.R.layout.simple_list_item_1,                        DBAdapter.DB_ListView));
                                            DBAdapter.close();

Create a dictionary with list comprehension

In fact, you don't even need to iterate over the iterable if it already comprehends some kind of mapping, the dict constructor doing it graciously for you:

>>> ts = [(1, 2), (3, 4), (5, 6)]
>>> dict(ts)
{1: 2, 3: 4, 5: 6}
>>> gen = ((i, i+1) for i in range(1, 6, 2))
>>> gen
<generator object <genexpr> at 0xb7201c5c>
>>> dict(gen)
{1: 2, 3: 4, 5: 6}

Receiving JSON data back from HTTP request

I think the shortest way is:

var client = new HttpClient();
string reqUrl = $"http://myhost.mydomain.com/api/products/{ProdId}";
var prodResp = await client.GetAsync(reqUrl);
if (!prodResp.IsSuccessStatusCode){
    FailRequirement();
}
var prods = await prodResp.Content.ReadAsAsync<Products>();

How can I deploy an iPhone application from Xcode to a real iPhone device?

You can't, not if you are talking about applications built with the official SDK and deploying straight from xcode.

HttpContext.Current.User.Identity.Name is Empty

I also had this problem recently. Working with a new client, trying to get a an old web forms app running from Visual Studio, with IISExpress using Windows Authentication. For me, the web.config was correctly configured

However, the IISExpress.config settings file had:

<windowsAuthentication enabled="false">

The user account the developer was logged in was very new, so unlikely it had been edited. Simple fix it turned out, change this to enabled=true and it all ran as it should then.

ImportError: No module named 'bottle' - PyCharm

In the case where you are able to import the module when using the CLI interpreter but not in PyCharm, make sure your project interpreter in PyCharm is set to an actual interpreter (eg. /usr/bin/python2.7) and not venv (~/PycharmProject/venv/...)

What are carriage return, linefeed, and form feed?

Apart from above information, there is still an interesting history of LF (\n) and CR (\r). [Original author : ??? Source : http://www.ruanyifeng.com/blog/2006/04/post_213.html] Before computer came out, there was a type of teleprinter called Teletype Model 33. It can print 10 characters each second. But there is one problem with this, after finishing printing each line, it will take 0.2 second to move to next line, which is time of printing 2 characters. If a new characters is transferred during this 0.2 second, then this new character will be lost.

So scientists found a way to solve this problem, they add two ending characters after each line, one is 'Carriage return', which is to tell the printer to bring the print head to the left.; the other one is 'Line feed', it tells the printer to move the paper up 1 line.

Later, computer became popular, these two concepts are used on computers. At that time, the storage device was very expensive, so some scientists said that it was expensive to add two characters at the end of each line, one is enough, so there are some arguments about which one to use.

In UNIX/Mac and Linux, '\n' is put at the end of each line, in Windows, '\r\n' is put at the end of each line. The consequence of this use is that files in UNIX/Mac will be displayed in one line if opened in Windows. While file in Windows will have one ^M at the end of each line if opened in UNIX or Mac.

Connect with SSH through a proxy

If your SSH proxy connection is going to be used often, you don't have to pass them as parameters each time. you can add the following lines to ~/.ssh/config

Host foobar.example.com
    ProxyCommand          nc -X connect -x proxyhost:proxyport %h %p
    ServerAliveInterval   10

then to connect use

ssh foobar.example.com

Source:

http://www.perkin.org.uk/posts/ssh-via-http-proxy-in-osx.html

JavaScript: Check if mouse button down?

I think the best approach to this is to keep your own record of the mouse button state, as follows:

var mouseDown = 0;
document.body.onmousedown = function() { 
    mouseDown = 1;
}
document.body.onmouseup = function() {
    mouseDown = 0;
}

and then, later in your code:

if (mouseDown == 1) {
    // the mouse is down, do what you have to do.
}

CSS scrollbar style cross browser

jScrollPane is a good solution to cross browser scrollbars and degrades nicely.

Stop executing further code in Java

You can just use return to end the method's execution

Smart way to truncate long strings

Use either lodash's truncate

_.truncate('hi-diddly-ho there, neighborino');
// ? 'hi-diddly-ho there, neighbo…'

or underscore.string's truncate.

_('Hello world').truncate(5); => 'Hello...'

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

open looks in the current working directory, which in your case is ~, since you are calling your script from the ~ directory.

You can fix the problem by either

  • cding to the directory containing data.csv before executing the script, or

  • by using the full path to data.csv in your script, or

  • by calling os.chdir(...) to change the current working directory from within your script. Note that all subsequent commands that use the current working directory (e.g. open and os.listdir) may be affected by this.

What is the difference between DAO and Repository patterns?

Frankly, this looks like a semantic distinction, not a technical distinction. The phrase Data Access Object doesn't refer to a "database" at all. And, although you could design it to be database-centric, I think most people would consider doing so a design flaw.

The purpose of the DAO is to hide the implementation details of the data access mechanism. How is the Repository pattern different? As far as I can tell, it isn't. Saying a Repository is different to a DAO because you're dealing with/return a collection of objects can't be right; DAOs can also return collections of objects.

Everything I've read about the repository pattern seems rely on this distinction: bad DAO design vs good DAO design (aka repository design pattern).

Populate nested array in mongoose

For someone who has the problem with populate and also wants to do this:

  • chat with simple text & quick replies (bubbles)
  • 4 database collections for chat: clients, users, rooms, messasges.
  • same message DB structure for 3 types of senders: bot, users & clients
  • refPath or dynamic reference
  • populate with path and model options
  • use findOneAndReplace/replaceOne with $exists
  • create a new document if the fetched document doesn't exist

CONTEXT

Goal

  1. Save a new simple text message to the database & populate it with the user or client data (2 different models).
  2. Save a new quickReplies message to the database and populate it with the user or client data.
  3. Save each message its sender type: clients, users & bot.
  4. Populate only the messages who have the sender clients or users with its Mongoose Models. _sender type client models is clients, for user is users.

Message schema:

const messageSchema = new Schema({
    room: {
        type: Schema.Types.ObjectId,
        ref: 'rooms',
        required: [true, `Room's id`]
    },
    sender: {
         _id: { type: Schema.Types.Mixed },
        type: {
            type: String,
            enum: ['clients', 'users', 'bot'],
            required: [true, 'Only 3 options: clients, users or bot.']
        }
    },
    timetoken: {
        type: String,
        required: [true, 'It has to be a Nanosecond-precision UTC string']
    },
    data: {
        lang: String,
        // Format samples on https://docs.chatfuel.com/api/json-api/json-api
        type: {
            text: String,
            quickReplies: [
                {
                    text: String,
                    // Blocks' ids.
                    goToBlocks: [String]
                }
            ]
        }
    }

mongoose.model('messages', messageSchema);

SOLUTION

My server side API request

My code

Utility function (on chatUtils.js file) to get the type of message that you want to save:

/**
 * We filter what type of message is.
 *
 * @param {Object} message
 * @returns {string} The type of message.
 */
const getMessageType = message => {
    const { type } = message.data;
    const text = 'text',
        quickReplies = 'quickReplies';

    if (type.hasOwnProperty(text)) return text;
    else if (type.hasOwnProperty(quickReplies)) return quickReplies;
};

/**
 * Get the Mongoose's Model of the message's sender. We use
 * the sender type to find the Model.
 *
 * @param {Object} message - The message contains the sender type.
 */
const getSenderModel = message => {
    switch (message.sender.type) {
        case 'clients':
            return 'clients';
        case 'users':
            return 'users';
        default:
            return null;
    }
};

module.exports = {
    getMessageType,
    getSenderModel
};

My server side (using Nodejs) to get the request of saving the message:

app.post('/api/rooms/:roomId/messages/new', async (req, res) => {
        const { roomId } = req.params;
        const { sender, timetoken, data } = req.body;
        const { uuid, state } = sender;
        const { type } = state;
        const { lang } = data;

        // For more info about message structure, look up Message Schema.
        let message = {
            room: new ObjectId(roomId),
            sender: {
                _id: type === 'bot' ? null : new ObjectId(uuid),
                type
            },
            timetoken,
            data: {
                lang,
                type: {}
            }
        };

        // ==========================================
        //          CONVERT THE MESSAGE
        // ==========================================
        // Convert the request to be able to save on the database.
        switch (getMessageType(req.body)) {
            case 'text':
                message.data.type.text = data.type.text;
                break;
            case 'quickReplies':
                // Save every quick reply from quickReplies[].
                message.data.type.quickReplies = _.map(
                    data.type.quickReplies,
                    quickReply => {
                        const { text, goToBlocks } = quickReply;

                        return {
                            text,
                            goToBlocks
                        };
                    }
                );
                break;
            default:
                break;
        }

        // ==========================================
        //           SAVE THE MESSAGE
        // ==========================================
        /**
         * We save the message on 2 ways:
         * - we replace the message type `quickReplies` (if it already exists on database) with the new one.
         * - else, we save the new message.
         */
        try {
            const options = {
                // If the quickRepy message is found, we replace the whole document.
                overwrite: true,
                // If the quickRepy message isn't found, we create it.
                upsert: true,
                // Update validators validate the update operation against the model's schema.
                runValidators: true,
                // Return the document already updated.
                new: true
            };

            Message.findOneAndUpdate(
                { room: roomId, 'data.type.quickReplies': { $exists: true } },
                message,
                options,
                async (err, newMessage) => {
                    if (err) {
                        throw Error(err);
                    }

                    // Populate the new message already saved on the database.
                    Message.populate(
                        newMessage,
                        {
                            path: 'sender._id',
                            model: getSenderModel(newMessage)
                        },
                        (err, populatedMessage) => {
                            if (err) {
                                throw Error(err);
                            }

                            res.send(populatedMessage);
                        }
                    );
                }
            );
        } catch (err) {
            logger.error(
                `#API Error on saving a new message on the database of roomId=${roomId}. ${err}`,
                { message: req.body }
            );

            // Bad Request
            res.status(400).send(false);
        }
    });

TIPs:

For the database:

  • Every message is a document itself.
  • Instead of using refPath, we use the util getSenderModel that is used on populate(). This is because of the bot. The sender.type can be: users with his database, clients with his database and bot without a database. The refPath needs true Model reference, if not, Mongooose throw an error.
  • sender._id can be type ObjectId for users and clients, or null for the bot.

For API request logic:

  • We replace the quickReply message (Message DB has to have only one quickReply, but as many simple text messages as you want). We use the findOneAndUpdate instead of replaceOne or findOneAndReplace.
  • We execute the query operation (the findOneAndUpdate) and the populate operation with the callback of each one. This is important if you don't know if use async/await, then(), exec() or callback(err, document). For more info look the Populate Doc.
  • We replace the quick reply message with the overwrite option and without $set query operator.
  • If we don't find the quick reply, we create a new one. You have to tell to Mongoose this with upsert option.
  • We populate only one time, for the replaced message or the new saved message.
  • We return to callbacks, whatever is the message we've saved with findOneAndUpdate and for the populate().
  • In populate, we create a custom dynamic Model reference with the getSenderModel. We can use the Mongoose dynamic reference because the sender.type for bot hasn't any Mongoose Model. We use a Populating Across Database with model and path optins.

I've spend a lot of hours solving little problems here and there and I hope this will help someone!

Different class for the last element in ng-repeat

You can use $last variable within ng-repeat directive. Take a look at doc.

You can do it like this:

 <div ng-repeat="file in files" ng-class="computeCssClass($last)">
 {{file.name}}
 </div>

Where computeCssClass is function of controller which takes sole argument and returns 'last' or null.

Or

  <div ng-repeat="file in files" ng-class="{'last':$last}">
  {{file.name}}
  </div>

How do I pass options to the Selenium Chrome driver using Python?

Found the chrome Options class in the Selenium source code.

Usage to create a Chrome driver instance:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=chrome_options)

Multiple "style" attributes in a "span" tag: what's supposed to happen?

In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.

So your example:

<span style="color:blue" style="font-style:italic">Test</span>

is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.


Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.

(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:

Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)

CSS transition fade on hover

This will do the trick

.gallery-item
{
  opacity:1;
}

.gallery-item:hover
{
  opacity:0;
  transition: opacity .2s ease-out;
  -moz-transition: opacity .2s ease-out;
  -webkit-transition: opacity .2s ease-out;
  -o-transition: opacity .2s ease-out;
}

Detecting a long press with Android

The solution by MSquare works only if you hold a specific pixel, but that's an unreasonable expectation for an end user unless they use a mouse (which they don't, they use fingers).

So I added a bit of a threshold for the distance between the DOWN and the UP action in case there was a MOVE action inbetween.

final Handler longPressHandler = new Handler();
Runnable longPressedRunnable = new Runnable() {
    public void run() {
        Log.e(TAG, "Long press detected in long press Handler!");
        isLongPressHandlerActivated = true;
    }
};

private boolean isLongPressHandlerActivated = false;

private boolean isActionMoveEventStored = false;
private float lastActionMoveEventBeforeUpX;
private float lastActionMoveEventBeforeUpY;

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if(event.getAction() == MotionEvent.ACTION_DOWN) {
        longPressHandler.postDelayed(longPressedRunnable, 1000);
    }
    if(event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_HOVER_MOVE) {
        if(!isActionMoveEventStored) {
            isActionMoveEventStored = true;
            lastActionMoveEventBeforeUpX = event.getX();
            lastActionMoveEventBeforeUpY = event.getY();
        } else {
            float currentX = event.getX();
            float currentY = event.getY();
            float firstX = lastActionMoveEventBeforeUpX;
            float firstY = lastActionMoveEventBeforeUpY;
            double distance = Math.sqrt(
                    (currentY - firstY) * (currentY - firstY) + ((currentX - firstX) * (currentX - firstX)));
            if(distance > 20) {
                longPressHandler.removeCallbacks(longPressedRunnable);
            }
        }
    }
    if(event.getAction() == MotionEvent.ACTION_UP) {
        isActionMoveEventStored = false;
        longPressHandler.removeCallbacks(longPressedRunnable);
        if(isLongPressHandlerActivated) {
            Log.d(TAG, "Long Press detected; halting propagation of motion event");
            isLongPressHandlerActivated = false;
            return false;
        }
    }
    return super.dispatchTouchEvent(event);
}

onclick event function in JavaScript

Try this

<input type="button" onClick="return click();">button text</input>  

How to get id from URL in codeigniter?

View page

  <a href="<?php echo base_url();?>products_controller/delete_controller/<?php echo $product_id;?>"><?php echo $name; ?></a>

controller page

  function delete_controller( $product_id) {

         echo $product_id;
         //add your logic

  }

How to import a csv file into MySQL workbench?

In the navigator under SCHEMAS, right click your schema/database and select "Table Data Import Wizard"

Works for mac too.

How can I create an MSI setup?

Look for Windows Installer XML (WiX)