Programs & Examples On #Beaker

Beaker is a library for caching and sessions for use with web applications and stand-alone Python scripts and applications. It comes with WSGI middleware for easy drop-in use with WSGI based web applications, and caching decorators for ease of use with any Python based application.

how to deal with google map inside of a hidden div (Updated picture)

I didn't like that the map would load only after the hidden div had become visible. In a carousel, for example, that doesn't really work.

This my solution is to add class to the hidden element to unhide it and hide it with position absolute instead, then render the map, and remove the class after map load.

Tested in Bootstrap Carousel.

HTML

<div class="item loading"><div id="map-canvas"></div></div>

CSS

.loading { display: block; position: absolute; }

JS

$(document).ready(function(){
    // render map //
    google.maps.event.addListenerOnce(map, 'idle', function(){
        $('.loading').removeClass('loading');
    });
}

How to add hours to current date in SQL Server?

declare @hours int = 5;

select dateadd(hour,@hours,getdate())

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

Go to config.inc.php file using terminal by typing the following:

sudo gedit /opt/lampp/phpmyadmin/config.inc.php

The file will open in gedit.

Now open the file and edit

$cfg['Servers'][$i]['auth_type'] = 'localhost';

to

$cfg['Servers'][$i]['auth_type'] = 'cookie';

and keep the username as: root password:

Also make sure that the lines with username and password are not commented:

//$cfg['Servers'][$i]['user'] = 'root'; //$cfg['Servers'][$i]['password'] = '';

Make sure that // is removed from the above lines.

How can you profile a Python script?

A while ago I made pycallgraph which generates a visualisation from your Python code. Edit: I've updated the example to work with 3.3, the latest release as of this writing.

After a pip install pycallgraph and installing GraphViz you can run it from the command line:

pycallgraph graphviz -- ./mypythonscript.py

Or, you can profile particular parts of your code:

from pycallgraph import PyCallGraph
from pycallgraph.output import GraphvizOutput

with PyCallGraph(output=GraphvizOutput()):
    code_to_profile()

Either of these will generate a pycallgraph.png file similar to the image below:

enter image description here

How to change the color of header bar and address bar in newest Chrome version on Lollipop?

You actually need 3 meta tags to support Android, iPhone and Windows Phone

<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#4285f4">
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-status-bar-style" content="#4285f4">

Check last modified date of file in C#

Be aware that the function File.GetLastWriteTime does not always work as expected, the values are sometimes not instantaneously updated by the OS. You may get an old Timestamp, even if the file has been modified right before.

The behaviour may vary between OS versions. For example, this unit test worked well every time on my developer machine, but it always fails on our build server.

  [TestMethod]
  public void TestLastModifiedTimeStamps()
  {
     var tempFile = Path.GetTempFileName();
     var lastModified = File.GetLastWriteTime(tempFile);
     using (new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
     {

     }
     Assert.AreNotEqual(lastModified, File.GetLastWriteTime(tempFile));
  }

See File.GetLastWriteTime seems to be returning 'out of date' value

Your options:

a) live with the occasional omissions.

b) Build up an active component realising the observer pattern (eg. a tcp server client structure), communicating the changes directly instead of writing / reading files. Fast and flexible, but another dependency and a possible point of failure (and some work, of course).

c) Ensure the signalling process by replacing the content of a dedicated signal file that other processes regularly read. It´s not that smart as it´s a polling procedure and has a greater overhead than calling File.GetLastWriteTime, but if not checking the content from too many places too often, it will do the work.

/// <summary>
/// type to set signals or check for them using a central file 
/// </summary>
public class FileSignal
{
    /// <summary>
    /// path to the central file for signal control
    /// </summary>
    public string FilePath { get; private set; }

    /// <summary>
    /// numbers of retries when not able to retrieve (exclusive) file access
    /// </summary>
    public int MaxCollisions { get; private set; }

    /// <summary>
    /// timespan to wait until next try
    /// </summary>
    public TimeSpan SleepOnCollisionInterval { get; private set; }

    /// <summary>
    /// Timestamp of the last signal
    /// </summary>
    public DateTime LastSignal { get; private set; }

    /// <summary>
    /// constructor
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>
    /// <param name="sleepOnCollisionInterval">timespan to wait until next try </param>
    public FileSignal(string filePath, int maxCollisions, TimeSpan sleepOnCollisionInterval)
    {
        FilePath = filePath;
        MaxCollisions = maxCollisions;
        SleepOnCollisionInterval = sleepOnCollisionInterval;
        LastSignal = GetSignalTimeStamp();
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>        
    public FileSignal(string filePath, int maxCollisions): this (filePath, maxCollisions, TimeSpan.FromMilliseconds(50))
    {
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval and a default value of 10 for maxCollisions
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>        
    public FileSignal(string filePath) : this(filePath, 10)
    {
    }

    private Stream GetFileStream(FileAccess fileAccess)
    {
        var i = 0;
        while (true)
        {
            try
            {
                return new FileStream(FilePath, FileMode.Create, fileAccess, FileShare.None);
            }
            catch (Exception e)
            {
                i++;
                if (i >= MaxCollisions)
                {
                    throw e;
                }
                Thread.Sleep(SleepOnCollisionInterval);
            };
        };
    }

    private DateTime GetSignalTimeStamp()
    {
        if (!File.Exists(FilePath))
        {
            return DateTime.MinValue;
        }
        using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            if(stream.Length == 0)
            {
                return DateTime.MinValue;
            }
            using (var reader = new BinaryReader(stream))
            {
                return DateTime.FromBinary(reader.ReadInt64());
            };                
        }
    }

    /// <summary>
    /// overwrites the existing central file and writes the current time into it.
    /// </summary>
    public void Signal()
    {
        LastSignal = DateTime.Now;
        using (var stream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            using (var writer = new BinaryWriter(stream))
            {
                writer.Write(LastSignal.ToBinary());
            }
        }
    }

    /// <summary>
    /// returns true if the file signal has changed, otherwise false.
    /// </summary>        
    public bool CheckIfSignalled()
    {
        var signal = GetSignalTimeStamp();
        var signalTimestampChanged = LastSignal != signal;
        LastSignal = signal;
        return signalTimestampChanged;
    }
}

Some tests for it:

    [TestMethod]
    public void TestSignal()
    {
        var fileSignal = new FileSignal(Path.GetTempFileName());
        var fileSignal2 = new FileSignal(fileSignal.FilePath);
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        fileSignal.Signal();
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.AreNotEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsTrue(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
    }

Changing precision of numeric column in Oracle

If the table is compressed this will work:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES move nocompress;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

alter table EVAPP_FEES compress;

Bootstrap modal link

Please remove . from your target it should be a id

<a href="#bannerformmodal" data-toggle="modal" data-target="#bannerformmodal">Load me</a>

Also you have to give your modal id like below

<div class="modal fade bannerformmodal" tabindex="-1" role="dialog" aria-labelledby="bannerformmodal" aria-hidden="true" id="bannerformmodal">

Here is the solution in a fiddle.

Bloomberg BDH function with ISIN

I had the same problem. Here's what I figured out:

=BDP(A1&"@BGN Corp", "Issuer_parent_eqy_ticker")

A1 being the ISINs. This will return the ticker number. Then just use the ticker number to get the price.

How do I convert from stringstream to string in C++?

std::stringstream::str() is the method you are looking for.

With std::stringstream:

template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
    std::stringstream ss;
    ss << NumericValue;
    return ss.str();
}

std::stringstream is a more generic tool. You can use the more specialized class std::ostringstream for this specific job.

template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
    std::ostringstream oss;
    oss << NumericValue;
    return oss.str();
}

If you are working with std::wstring type of strings, you must prefer std::wstringstream or std::wostringstream instead.

template <class T>
std::wstring YourClass::NumericToString(const T & NumericValue)
{
    std::wostringstream woss;
    woss << NumericValue;
    return woss.str();
}

if you want the character type of your string could be run-time selectable, you should also make it a template variable.

template <class CharType, class NumType>
std::basic_string<CharType> YourClass::NumericToString(const NumType & NumericValue)
{
    std::basic_ostringstream<CharType> oss;
    oss << NumericValue;
    return oss.str();
}

For all the methods above, you must include the following two header files.

#include <string>
#include <sstream>

Note that, the argument NumericValue in the examples above can also be passed as std::string or std::wstring to be used with the std::ostringstream and std::wostringstream instances respectively. It is not necessary for the NumericValue to be a numeric value.

Spring's overriding bean

Not sure if that's exactly what you need, but we are using profiles to define the environment we are running at and specific bean for each environment, so it's something like that:

<bean name="myBean" class="myClass">
    <constructor-arg name="name" value="originalValue" />
</bean>
<beans profile="DEV, default">
     <!-- Specific DEV configurations, also default if no profile defined -->
    <bean name="myBean" class="myClass">
        <constructor-arg name="name" value="overrideValue" />
    </bean>
</beans>
<beans profile="CI, UAT">
     <!-- Specific CI / UAT configurations -->
</beans>
<beans profile="PROD">
     <!-- Specific PROD configurations -->
</beans>

So in this case, if I don't define a profile or if I define it as "DEV" myBean will get "overrideValue" for it's name argument. But if I set the profile to "CI", "UAT" or "PROD" it will get "originalValue" as the value.

Putting HTML inside Html.ActionLink(), plus No Link Text?

It's very simple.

If you want to have something like a glyphicon icon and then "Wish List",

<span class="glyphicon-heart"></span> @Html.ActionLink("Wish List (0)", "Index", "Home")

How to set underline text on textview?

Android supports string formatting using HTML tags in the strings xml. So the following would work:

<string name="label_testinghtmltags"><u>This text has an underscore</u></string>

Then you just use it as you normally would. You can see more in the documentation here

Update:

To further expand on the answer, the documentation says:

... the format(String, Object...) and getString(int, Object...) methods strip all the style information from the string. . The work-around to this is to write the HTML tags with escaped entities, which are then recovered with fromHtml(String), after the formatting takes place

For example, the resulting string from the following code snippet will not show up as containing underscored elements:

<string name="html_bold_test">This <u>%1$s</u> has an underscore</string>
String result = getString(R.string.html_bold_test, "text")

However the result from the following snippet would contain underscores:

<string name="html_bold_test">This &lt;u> %1$s &lt;/u> has an underscore</string>
String result = Html.fromHtml(getString(R.string.html_bold_test, "text"))

Google Chrome display JSON AJAX response as tree and not as a plain text

I've found the answer:

You MUST encode your json like this: {"c":21001,"m":"p"} but not {c:21001,m:"p"} or {'c':21001,'m':'p'}

Thus, the key of a dict must be wrapped in double quotes:", then chrome will preview it as json rather than plain text.

Accessing inventory host variable in Ansible playbook

[host_group]
host-1 ansible_ssh_host=192.168.0.21 node_name=foo
host-2 ansible_ssh_host=192.168.0.22 node_name=bar

[host_group:vars]
custom_var=asdasdasd

You can access host group vars using:

{{ hostvars['host_group'].custom_var }}

If you need a specific value from specific host, you can use:

{{ hostvars[groups['host_group'][0]].node_name }}

Best way to do multi-row insert in Oracle?

you can insert using loop if you want to insert some random values.

BEGIN 
    FOR x IN 1 .. 1000 LOOP
         INSERT INTO MULTI_INSERT_DEMO (ID, NAME)
         SELECT x, 'anyName' FROM dual;
    END LOOP;
END;

Any implementation of Ordered Set in Java?

treeset is an ordered set, but you can't access via an items index, just iterate through or go to beginning/end.

Java for loop multiple variables

Instead of this : for(int a = 0, b = 1; a<cards.length-1; b=a+1; a++;){

It should be

for(int a = 0, b = 1; a<cards.length()-1; b=a+1, a++){
                                     ^         ^    ^  
                                     |         |    |  
                                     |         |    |  
            -------------------------------------------Note the changes
           |                    
           v                                                  |
   if(rank==cards.substring(a,b){                             |
-------------------------------------------------------------                                  
|
v
System.out.println(c); //capital S in system

Determine installed PowerShell version

Since the most helpful answer didn't address the if exists portion, I thought I'd give one take on it via a quick-and-dirty solution. It relies on PowerShell being in the path environment variable which is likely what you want. (Hat tip to the top answer as I didn't know that.) Paste this into a text file and name it

Test Powershell Version.cmd

or similar.

@echo off
echo Checking powershell version...
del "%temp%\PSVers.txt" 2>nul
powershell -command "[string]$PSVersionTable.PSVersion.Major +'.'+ [string]$PSVersionTable.PSVersion.Minor | Out-File ([string](cat env:\temp) + '\PSVers.txt')" 2>nul
if errorlevel 1 (
 echo Powershell is not installed. Please install it from download.Microsoft.com; thanks.
) else (
 echo You have installed Powershell version:
 type "%temp%\PSVers.txt"
 del "%temp%\PSVers.txt" 2>nul
)
timeout 15

Forbidden: You don't have permission to access / on this server, WAMP Error

Adding Allow from All didn't worked for me. Then I tried this and it worked.

OS: Windows 8.1
Wamp : 2.5

I added this in the file C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "c:/wamp/www/"
    ServerName localhost
    ServerAlias localhost
    ErrorLog "logs/localhost-error.log"
    CustomLog "logs/localhost-access.log" common
</VirtualHost>

System.Collections.Generic.List does not contain a definition for 'Select'

You need to have the System.Linq namespace included in your view since Select is an extension method. You have a couple of options on how to do this:

Add @using System.Linq to the top of your cshtml file.

If you find that you will be using this namespace often in many of your views, you can do this for all views by modifying the web.config inside of your Views folder (not the one at the root). You should see a pages/namespace XML element, create a new add child that adds System.Linq. Here is an example:

<configuration>
    <system.web.webPages.razor>
        <pages>
            <namespaces>
                <add namespace="System.Linq" />
            </namespaces>
        </pages>
    </system.web.webPages.razor>
</configuration>

While loop in batch

@echo off

set countfiles=10

:loop

set /a countfiles -= 1

echo hi

if %countfiles% GTR 0 goto loop

pause

on the first "set countfiles" the 10 you see is the amount it will loop the echo hi is the thing you want to loop

...i'm 5 years late

How to create empty folder in java?

You can create folder using the following Java code:

File dir = new File("nameoffolder");
dir.mkdir();

By executing above you will have folder 'nameoffolder' in current folder.

How can I pad a String in Java?

In Guava, this is easy:

Strings.padStart("string", 10, ' ');
Strings.padEnd("string", 10, ' ');

Finding duplicate values in MySQL

The following will find all product_id that are used more than once. You only get a single record for each product_id.

SELECT product_id FROM oc_product_reward GROUP BY product_id HAVING count( product_id ) >1

Code taken from : http://chandreshrana.blogspot.in/2014/12/find-duplicate-records-based-on-any.html

How to make a 3-level collapsing menu in Bootstrap?

Bootstrap 2.3.x and later supports the dropdown-submenu..

<ul class="dropdown-menu">
            <li><a href="#">Login</a></li>
            <li class="dropdown-submenu">
                <a tabindex="-1" href="#">More options</a>
                <ul class="dropdown-menu">
                    <li><a tabindex="-1" href="#">Second level</a></li>
                    <li><a href="#">Second level</a></li>
                    <li><a href="#">Second level</a></li>
                </ul>
            </li>
            <li><a href="#">Logout</a></li>
</ul>

Working demo on Bootply.com

hide div tag on mobile view only?

The solution given didn't work for me on the desktop, it just showed both divs, although the mobile only showed the mobile div. So I did a little search and found the min-width option. I updated my code to the following and it works fine now :)

CSS:

    @media all and (min-width: 480px) {
    .deskContent {display:block;}
    .phoneContent {display:none;}
}

@media all and (max-width: 479px) {
    .deskContent {display:none;}
    .phoneContent {display:block;}
}

HTML:

<div class="deskContent">Content for desktop</div>
<div class="phoneContent">Content for mobile</div>

GCC -fPIC option

The link to a function in a dynamic library is resolved when the library is loaded or at run time. Therefore, both the executable file and dynamic library are loaded into memory when the program is run. The memory address at which a dynamic library is loaded cannot be determined in advance, because a fixed address might clash with another dynamic library requiring the same address.


There are two commonly used methods for dealing with this problem:

1.Relocation. All pointers and addresses in the code are modified, if necessary, to fit the actual load address. Relocation is done by the linker and the loader.

2.Position-independent code. All addresses in the code are relative to the current position. Shared objects in Unix-like systems use position-independent code by default. This is less efficient than relocation if program run for a long time, especially in 32-bit mode.


The name "position-independent code" actually implies following:

  • The code section contains no absolute addresses that need relocation, but only self relative addresses. Therefore, the code section can be loaded at an arbitrary memory address and shared between multiple processes.

  • The data section is not shared between multiple processes because it often contains writeable data. Therefore, the data section may contain pointers or addresses that need relocation.

  • All public functions and public data can be overridden in Linux. If a function in the main executable has the same name as a function in a shared object, then the version in main will take precedence, not only when called from main, but also when called from the shared object. Likewise, when a global variable in main has the same name as a global variable in the shared object, then the instance in main will be used, even when accessed from the shared object.


This so-called symbol interposition is intended to mimic the behavior of static libraries.

A shared object has a table of pointers to its functions, called procedure linkage table (PLT) and a table of pointers to its variables called global offset table (GOT) in order to implement this "override" feature. All accesses to functions and public variables go through this tables.

p.s. Where dynamic linking cannot be avoided, there are various ways to avoid the timeconsuming features of the position-independent code.

You can read more from this article: http://www.agner.org/optimize/optimizing_cpp.pdf

Simplest way to detect keypresses in javascript

Don't over complicate.

  document.addEventListener('keydown', logKey);
    function logKey(e) {
      if (`${e.code}` == "ArrowRight") {
        //code here
      }
          if (`${e.code}` == "ArrowLeft") {
        //code here
      }
          if (`${e.code}` == "ArrowDown") {
        //code here
      }
          if (`${e.code}` == "ArrowUp") {
        //code here
      }
    }

upgade python version using pip

Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.

Why does my 'git branch' have no master?

master is just the name of a branch, there's nothing magic about it except it's created by default when a new repository is created.

You can add it back with git checkout -b master.

How can I capture the right-click event in JavaScript?

Use the oncontextmenu event.

Here's an example:

<div oncontextmenu="javascript:alert('success!');return false;">
    Lorem Ipsum
</div>

And using event listeners (credit to rampion from a comment in 2011):

el.addEventListener('contextmenu', function(ev) {
    ev.preventDefault();
    alert('success!');
    return false;
}, false);

Don't forget to return false, otherwise the standard context menu will still pop up.

If you are going to use a function you've written rather than javascript:alert("Success!"), remember to return false in BOTH the function AND the oncontextmenu attribute.

How to copy and paste worksheets between Excel workbooks?

I'm using this code, hope this helps!

Application.ScreenUpdating = False
Application.EnableEvents = False

Dim destination_wb As Workbook
Set destination_wb = Workbooks.Open(DESTINATION_WORKBOOK_NAME)

worksheet_to_copy.Copy Before:=destination_wb.Worksheets(1)
destination_wb.Worksheets(1).Name = worksheet_to_copy.Name
'Add the sheets count to the name to avoid repeated worksheet names error
'& destination_wb.Worksheets.Count


'optional
destination_wb.Worksheets(1).UsedRange.Columns.AutoFit

'I use this to avoid macro errors in destination_wb
Call DeleteAllVBACode(destination_wb)

'Delete source worksheet
Application.DisplayAlerts = False
worksheet_to_copy.Delete
Application.DisplayAlerts = True

destination_wb.Save
destination_wb.Close

Application.EnableEvents = True
Application.ScreenUpdating = True

' From http://www.cpearson.com/Excel/vbe.aspx           

Public Sub DeleteAllVBACode(libro As Workbook)
    Dim VBProj As VBProject
    Dim VBComp As VBComponent
    Dim CodeMod As CodeModule

    Set VBProj = libro.VBProject

    For Each VBComp In VBProj.VBComponents
        If VBComp.Type = vbext_ct_Document Then
            Set CodeMod = VBComp.CodeModule
            With CodeMod
                .DeleteLines 1, .CountOfLines
            End With
        Else
            VBProj.VBComponents.Remove VBComp
        End If
    Next VBComp
End Sub

Achieving white opacity effect in html/css

Try RGBA, e.g.

div { background-color: rgba(255, 255, 255, 0.5); }

As always, this won't work in every single browser ever written.

Print range of numbers on same line

str.join would be appropriate in this case

>>> print ' '.join(str(x) for x in xrange(1,11))
1 2 3 4 5 6 7 8 9 10 

Spring @Transactional - isolation, propagation

I have run outerMethod,method_1 and method_2 with different propagation mode.

Below is the output for different propagation mode.

  • Outer Method

    @Transactional
    @Override
    public void outerMethod() {
        customerProfileDAO.method_1();
        iWorkflowDetailDao.method_2();
    }
    
  • Method_1

    @Transactional(propagation=Propagation.MANDATORY)
    public void method_1() {
        Session session = null;
        try {
            session = getSession();
            Temp entity = new Temp(0l, "XXX");
            session.save(entity);
            System.out.println("Method - 1 Id "+entity.getId());
        } finally {
            if (session != null && session.isOpen()) {
            }
        }
    }
    
  • Method_2

    @Transactional()
    @Override
    public void method_2() {
        Session session = null;
        try {
            session = getSession();
            Temp entity = new Temp(0l, "CCC");
            session.save(entity);
            int i = 1/0;
            System.out.println("Method - 2 Id "+entity.getId());
        } finally {
            if (session != null && session.isOpen()) {
            }
        }
    }
    
      • outerMethod - Without transaction
      • method_1 - Propagation.MANDATORY) -
      • method_2 - Transaction annotation only
      • Output: method_1 will throw exception that no existing transaction
      • outerMethod - Without transaction
      • method_1 - Transaction annotation only
      • method_2 - Propagation.MANDATORY)
      • Output: method_2 will throw exception that no existing transaction
      • Output: method_1 will persist record in database.
      • outerMethod - With transaction
      • method_1 - Transaction annotation only
      • method_2 - Propagation.MANDATORY)
      • Output: method_2 will persist record in database.
      • Output: method_1 will persist record in database. -- Here Main Outer existing transaction used for both method 1 and 2
      • outerMethod - With transaction
      • method_1 - Propagation.MANDATORY) -
      • method_2 - Transaction annotation only and throws exception
      • Output: no record persist in database means rollback done.
      • outerMethod - With transaction
      • method_1 - Propagation.REQUIRES_NEW)
      • method_2 - Propagation.REQUIRES_NEW) and throws 1/0 exception
      • Output: method_2 will throws exception so method_2 record not persisted.
      • Output: method_1 will persist record in database.
      • Output: There is no rollback for method_1

Java ArrayList - how can I tell if two lists are equal, order not mattering?

I'd say these answers miss a trick.

Bloch, in his essential, wonderful, concise Effective Java, says, in item 47, title "Know and use the libraries", "To summarize, don't reinvent the wheel". And he gives several very clear reasons why not.

There are a few answers here which suggest methods from CollectionUtils in the Apache Commons Collections library but none has spotted the most beautiful, elegant way of answering this question:

Collection<Object> culprits = CollectionUtils.disjunction( list1, list2 );
if( ! culprits.isEmpty() ){
  // ... do something with the culprits, i.e. elements which are not common

}

Culprits: i.e. the elements which are not common to both Lists. Determining which culprits belong to list1 and which to list2 is relatively straightforward using CollectionUtils.intersection( list1, culprits ) and CollectionUtils.intersection( list2, culprits ).
However it tends to fall apart in cases like { "a", "a", "b" } disjunction with { "a", "b", "b" } ... except this is not a failing of the software, but inherent to the nature of the subtleties/ambiguities of the desired task.

You can always examine the source code (l. 287) for a task like this, as produced by the Apache engineers. One benefit of using their code is that it will have been thoroughly tried and tested, with many edge cases and gotchas anticipated and dealt with. You can copy and tweak this code to your heart's content if need be.


NB I was at first disappointed that none of the CollectionUtils methods provides an overloaded version enabling you to impose your own Comparator (so you can redefine equals to suit your purposes).

But from collections4 4.0 there is a new class, Equator which "determines equality between objects of type T". On examination of the source code of collections4 CollectionUtils.java they seem to be using this with some methods, but as far as I can make out this is not applicable to the methods at the top of the file, using the CardinalityHelper class... which include disjunction and intersection.

I surmise that the Apache people haven't got around to this yet because it is non-trivial: you would have to create something like an "AbstractEquatingCollection" class, which instead of using its elements' inherent equals and hashCode methods would instead have to use those of Equator for all the basic methods, such as add, contains, etc. NB in fact when you look at the source code, AbstractCollection does not implement add, nor do its abstract subclasses such as AbstractSet... you have to wait till the concrete classes such as HashSet and ArrayList before add is implemented. Quite a headache.

In the mean time watch this space, I suppose. The obvious interim solution would be to wrap all your elements in a bespoke wrapper class which uses equals and hashCode to implement the kind of equality you want... then manipulate Collections of these wrapper objects.

Purpose of __repr__ method?

This is explained quite well in the Python documentation:

repr(object): Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

So what you're seeing here is the default implementation of __repr__, which is useful for serialization and debugging.

SonarQube not picking up Unit Test Coverage

Include the sunfire and jacoco plugins in the pom.xml and Run the maven command as given below.

mvn jacoco:prepare-agent jacoco:report sonar:sonar

<properties>
    <surefire.version>2.17</surefire.version>
    <jacoco.version>0.7.2.201409121644</jacoco.version>

<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>${surefire.version}</version>
        </plugin> 

        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>${jacoco.version}</version>

            <executions>
                <execution>
                    <id>default-prepare-agent</id>
                    <goals><goal>prepare-agent</goal></goals>
                </execution>
                <execution>
                    <id>default-report</id>
                    <phase>prepare-package</phase>
                    <goals><goal>report</goal></goals>
                </execution>
            </executions>
        </plugin>
    </plugins>

HTML: Changing colors of specific words in a string of text

You could use the longer boringer way

_x000D_
_x000D_
<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">Enter the competition by</p><p style="font-size:14px; color:#ff00; font-weight:bold; font-style:italic;">summer</p> 
_x000D_
_x000D_
_x000D_

you get the point for the rest

Returning binary file from controller in ASP.NET Web API

While the suggested solution works fine, there is another way to return a byte array from the controller, with response stream properly formatted :

  • In the request, set header "Accept: application/octet-stream".
  • Server-side, add a media type formatter to support this mime type.

Unfortunately, WebApi does not include any formatter for "application/octet-stream". There is an implementation here on GitHub: BinaryMediaTypeFormatter (there are minor adaptations to make it work for webapi 2, method signatures changed).

You can add this formatter into your global config :

HttpConfiguration config;
// ...
config.Formatters.Add(new BinaryMediaTypeFormatter(false));

WebApi should now use BinaryMediaTypeFormatter if the request specifies the correct Accept header.

I prefer this solution because an action controller returning byte[] is more comfortable to test. Though, the other solution allows you more control if you want to return another content-type than "application/octet-stream" (for example "image/gif").

ImportError: No module named model_selection

Your sklearn version is too low, model_selection is imported by 0.18.1, so please update the sklearn version.

Angular.js How to change an elements css class on click and to remove all others

Typically with Angular you would be outputting these spans using the ngRepeat directive and (like in your case) each item would have an id. I know this is not true for all situations but it is typical if requesting data from a backend - objects in an array tend to have unique identifiers.

You can use this id to facilitate the toggling of classes on items in your list (see plunkr or code below).

Using the objects id's can also eliminate the undesirable effect when the $index (described in other answers) is messed up due to sorting in Angular.

Example Plunkr: http://plnkr.co/edit/na0gUec6cdMABK9L6drV

(basically apply the .active-selection class if the person.id is equal to $scope.activeClass - which we set when the user clicks an item.

Hope this helps someone, I've found expressions in ng-class to be very useful!

HTML

<ul>
  <li ng-repeat="person in people" 
  data-ng-class="{'active-selection': person.id == activeClass}">
    <a data-ng-click="selectPerson(person.id)">
      {{person.name}}
    </a>
  </li>
</ul>

JS

app.controller('MainCtrl', function($scope) {
  $scope.people = [{
    id: "1",
    name: "John",
  }, {
    id: "2",
    name: "Lucy"
  }, {
    id: "3",
    name: "Mark"
  }, {
    id: "4",
    name: "Sam"
  }];

  $scope.selectPerson = function(id) {
    $scope.activeClass = id;
    console.log(id);
  };
});    

CSS:

.active-selection {
  background-color: #eee;
}

How to sort a file, based on its numerical values for a field?

You must do the following command:

sort -n -k1 filename

That should do it :)

C# how to create a Guid value?

Alternately, if you are using SQL Server as your database you can get your GUID from the server instead. In TSQL:

//Retrive your key ID on the bases of GUID 

declare @ID as uniqueidentifier

SET @ID=NEWID()
insert into Sector(Sector,CID)

Values ('Diry7',@ID)


select SECTORID from sector where CID=@ID

JSON character encoding - is UTF-8 well-supported by browsers or should I use numeric escape sequences?

I had a similar problem with é char... I think the comment "it's possible that the text you're feeding it isn't UTF-8" is probably close to the mark here. I have a feeling the default collation in my instance was something else until I realized and changed to utf8... problem is the data was already there, so not sure if it converted the data or not when i changed it, displays fine in mysql workbench. End result is that php will not json encode the data, just returns false. Doesn't matter what browser you use as its the server causing my issue, php will not parse the data to utf8 if this char is present. Like i say not sure if it is due to converting the schema to utf8 after data was present or just a php bug. In this case use json_encode(utf8_encode($string));

How does true/false work in PHP?

This is covered in the PHP documentation for booleans and type comparison tables.

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string '0'
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Every other value is considered TRUE.

How to use nan and inf in C?

A compiler independent way, but not processor independent way to get these:

int inf = 0x7F800000;
return *(float*)&inf;

int nan = 0x7F800001;
return *(float*)&nan;

This should work on any processor which uses the IEEE 754 floating point format (which x86 does).

UPDATE: Tested and updated.

Embed website into my site

You can embed websites into another website using the <embed> tag, like so:

<embed src="http://www.example.com" style="width:500px; height: 300px;">

You can change the height, width, and URL to suit your needs.

The <embed> tag is the most up-to-date way to embed websites, as it was introduced with HTML5.

Single quotes vs. double quotes in Python

I use double quotes in general, but not for any specific reason - Probably just out of habit from Java.

I guess you're also more likely to want apostrophes in an inline literal string than you are to want double quotes.

Get week of year in JavaScript like in PHP

getWeekOfYear: function(date) {
        var target = new Date(date.valueOf()),
            dayNumber = (date.getUTCDay() + 6) % 7,
            firstThursday;

        target.setUTCDate(target.getUTCDate() - dayNumber + 3);
        firstThursday = target.valueOf();
        target.setUTCMonth(0, 1);

        if (target.getUTCDay() !== 4) {
            target.setUTCMonth(0, 1 + ((4 - target.getUTCDay()) + 7) % 7);
        }

        return Math.ceil((firstThursday - target) /  (7 * 24 * 3600 * 1000)) + 1;
    }

Following code is timezone-independent (UTC dates used) and works according to the https://en.wikipedia.org/wiki/ISO_8601

(Mac) -bash: __git_ps1: command not found

You should

$ brew install bash bash-completion git

Then source "$(brew --prefix)/etc/bash_completion" in your .bashrc.

Get a timestamp in C in microseconds?

First we need to know on the range of microseconds i.e. 000_000 to 999_999 (1000000 microseconds is equal to 1second). tv.tv_usec will return value from 0 to 999999 not 000000 to 999999 so when using it with seconds we might get 2.1seconds instead of 2.000001 seconds because when only talking about tv_usec 000001 is essentially 1. Its better if you insert

if(tv.tv_usec<10)
{
 printf("00000");
} 
else if(tv.tv_usec<100&&tv.tv_usec>9)// i.e. 2digits
{
 printf("0000");
}

and so on...

Find everything between two XML tags with RegEx

In our case, we receive an XML as a String and need to get rid of the values that have some "special" characters, like &<> etc. Basically someone can provide an XML to us in this form:

<notes>
  <note>
     <to>jenice & carl </to>
     <from>your neighbor <; </from>
  </note>
</notes>

So I need to find in that String the values jenice & carl and your neighbor <; and properly escape & and < (otherwise this is an invalid xml if you later pass it to an engine that shall rename unnamed).

Doing this with regex is a rather dumb idea to begin with, but it's cheap and easy. So the brave ones that would like to do the same thing I did, here you go:

    String xml = ...
    Pattern p = Pattern.compile("<(.+)>(?!\\R<)(.+)</(\\1)>");
    Matcher m = p.matcher(xml);
    String result = m.replaceAll(mr -> {
        if (mr.group(2).contains("&")) {
            return "<" + m.group(1) + ">" + m.group(2) + "+ some change" + "</" + m.group(3) + ">";
        }
        return "<" + m.group(1) + ">" + mr.group(2) + "</" + m.group(3) + ">";
    });

How do I apply the for-each loop to every character in a String?

Unfortunately Java does not make String implement Iterable<Character>. This could easily be done. There is StringCharacterIterator but that doesn't even implement Iterator... So make your own:

public class CharSequenceCharacterIterable implements Iterable<Character> {
    private CharSequence cs;

    public CharSequenceCharacterIterable(CharSequence cs) {
        this.cs = cs;
    }

    @Override
    public Iterator<Character> iterator() {
        return new Iterator<Character>() {
            private int index = 0;

            @Override
            public boolean hasNext() {
                return index < cs.length();
            }

            @Override
            public Character next() {
                return cs.charAt(index++);
            }
        };
    }
}

Now you can (somewhat) easily run for (char c : new CharSequenceCharacterIterable("xyz"))...

Replace all whitespace characters

We can also use this if we want to change all multiple joined blank spaces with a single character:

str.replace(/\s+/g,'X');

See it in action here: https://regex101.com/r/d9d53G/1

Explanation

/ \s+ / g

  • \s+ matches any whitespace character (equal to [\r\n\t\f\v ])
  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

  • Global pattern flags
    • g modifier: global. All matches (don't return after first match)

How to make a parent div auto size to the width of its children divs

The parent div (I assume the outermost div) is display: block and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block is probably what you are going for:

http://jsfiddle.net/a78xy/

Python: importing a sub-package or sub-module

You seem to be misunderstanding how import searches for modules. When you use an import statement it always searches the actual module path (and/or sys.modules); it doesn't make use of module objects in the local namespace that exist because of previous imports. When you do:

import package.subpackage.module
from package.subpackage import module
from module import attribute1

The second line looks for a package called package.subpackage and imports module from that package. This line has no effect on the third line. The third line just looks for a module called module and doesn't find one. It doesn't "re-use" the object called module that you got from the line above.

In other words from someModule import ... doesn't mean "from the module called someModule that I imported earlier..." it means "from the module named someModule that you find on sys.path...". There is no way to "incrementally" build up a module's path by importing the packages that lead to it. You always have to refer to the entire module name when importing.

It's not clear what you're trying to achieve. If you only want to import the particular object attribute1, just do from package.subpackage.module import attribute1 and be done with it. You need never worry about the long package.subpackage.module once you've imported the name you want from it.

If you do want to have access to the module to access other names later, then you can do from package.subpackage import module and, as you've seen you can then do module.attribute1 and so on as much as you like.

If you want both --- that is, if you want attribute1 directly accessible and you want module accessible, just do both of the above:

from package.subpackage import module
from package.subpackage.module import attribute1
attribute1 # works
module.someOtherAttribute # also works

If you don't like typing package.subpackage even twice, you can just manually create a local reference to attribute1:

from package.subpackage import module
attribute1 = module.attribute1
attribute1 # works
module.someOtherAttribute #also works

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Or, alternatively, you could use Operator module. More detailed information is here Python docs

import operator
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame(np.random.randn(5,3), columns=list('ABC'))
df.loc[operator.or_(df.C > 0.25, df.C < -0.25)]

          A         B         C
0  1.764052  0.400157  0.978738
1  2.240893  1.867558 -0.977278
3  0.410599  0.144044  1.454274
4  0.761038  0.121675  0.4438

Git "error: The branch 'x' is not fully merged"

Note Wording changed in response to the commments. Thanks @slekse
That is not an error, it is a warning. It means the branch you are about to delete contains commits that are not reachable from any of: its upstream branch, or HEAD (currently checked out revision). In other words, when you might lose commits¹.

In practice it means that you probably amended, rebased or filtered commits and they don't seem identical.

Therefore you could avoid the warning by checking out a branch that does contain the commits that you're about un-reference by deleting that other branch.²

You will want to verify that you in fact aren't missing any vital commits:

git log --graph --left-right --cherry-pick --oneline master...experiment

This will give you a list of any nonshared between the branches. In case you are curious, there might be a difference without --cherry-pick and this difference could well be the reason for the warning you get:

--cherry-pick

Omit any commit that introduces the same change as another commit on the "other side" when the set of commits are limited with symmetric difference. For example, if you have two branches, A and B, a usual way to list all commits on only one side of them is with --left-right, like the example above in the description of that option. It however shows the commits that were cherry-picked from the other branch (for example, "3rd on b" may be cherry-picked from branch A). With this option, such pairs of commits are excluded from the output.


¹ they're really only garbage collected after a while, by default. Also, the git-branch command does not check the revision tree of all branches. The warning is there to avoid obvious mistakes.

² (My preference here is to just force the deletion instead, but you might want to have the extra reassurance).

How to start automatic download of a file in Internet Explorer?

For those trying to trigger the download using a dynamic link it's tricky to get it working consistently across browsers.

I had trouble in IE10+ downloading a PDF and used @dandavis' download function (https://github.com/rndme/download).

IE10+ needs msSaveBlob.

draw diagonal lines in div background with CSS

You can use SVG to draw the lines.

_x000D_
_x000D_
.diag {_x000D_
    background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' preserveAspectRatio='none' viewBox='0 0 100 100'><path d='M1 0 L0 1 L99 100 L100 99' fill='black' /><path d='M0 99 L99 0 L100 1 L1 100' fill='black' /></svg>");_x000D_
    background-repeat:no-repeat;_x000D_
    background-position:center center;_x000D_
    background-size: 100% 100%, auto;_x000D_
}
_x000D_
<div class="diag" style="width: 300px; height: 100px;"></div>
_x000D_
_x000D_
_x000D_

Have a play here: http://jsfiddle.net/tyw7vkvm

What exactly are iterator, iterable, and iteration?

Before dealing with the iterables and iterator the major factor that decide the iterable and iterator is sequence

Sequence: Sequence is the collection of data

Iterable: Iterable are the sequence type object that support __iter__ method.

Iter method: Iter method take sequence as an input and create an object which is known as iterator

Iterator: Iterator are the object which call next method and transverse through the sequence. On calling the next method it returns the object that it traversed currently.

example:

x=[1,2,3,4]

x is a sequence which consists of collection of data

y=iter(x)

On calling iter(x) it returns a iterator only when the x object has iter method otherwise it raise an exception.If it returns iterator then y is assign like this:

y=[1,2,3,4]

As y is a iterator hence it support next() method

On calling next method it returns the individual elements of the list one by one.

After returning the last element of the sequence if we again call the next method it raise an StopIteration error

example:

>>> y.next()
1
>>> y.next()
2
>>> y.next()
3
>>> y.next()
4
>>> y.next()
StopIteration

Tree implementation in Java (root, parents and children)

The process of assembling tree nodes is similar to the process of assembling lists. We have a constructor for tree nodes that initializes the instance variables.

public Tree (Object cargo, Tree left, Tree right) { 
    this.cargo = cargo; 
    this.left = left; 
    this.right = right; 
} 

We allocate the child nodes first:

Tree left = new Tree (new Integer(2), null, null); 
Tree right = new Tree (new Integer(3), null, null); 

We can create the parent node and link it to the children at the same time:

Tree tree = new Tree (new Integer(1), left, right); 

How do you force a makefile to rebuild a target

make clean deletes all the already compiled object files.

TypeError: method() takes 1 positional argument but 2 were given

In my case, I forgot to add the ()

I was calling the method like this

obj = className.myMethod

But it should be is like this

obj = className.myMethod()

How to filter data in dataview

Eg:

Datatable newTable =  new DataTable();

            foreach(string s1 in list)
            {
                if (s1 != string.Empty) {
                    dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
                    foreach(DataRow dr in dvProducts.ToTable().Rows)
                    {
                       newTable.ImportRow(dr);
                    }
                }
            }
ListView1.DataSource = newTable;
ListView1.DataBind();

Converting a String to Object

A Java String is an Object. (String extends Object.)

So you can get an Object reference via assignment/initialisation:

String a = "abc";
Object b = a;

Uninstall Node.JS using Linux command line?

To uninstall node I followed the accepted answer by @George, as I no longer have the sources, but before doing so I ran:

sudo npm rm npm -g

That seemed to get rid of npm from the system directories such as /usr/bin/npm and /usr/lib/npm. I got the command from here. I then found a ~/.npm directory, which I deleted manually. Honestly I don't know if every trace of npm has been removed, but I can't find anything else.

Make anchor link go some pixels above where it's linked to

<a href="#anchor">Click me!</a>

<div style="margin-top: -100px; padding-top: 100px;" id="anchor"></div>
<p>I should be 100px below where I currently am!</p>

When would you use the different git merge strategies?

Actually the only two strategies you would want to choose are ours if you want to abandon changes brought by branch, but keep the branch in history, and subtree if you are merging independent project into subdirectory of superproject (like 'git-gui' in 'git' repository).

octopus merge is used automatically when merging more than two branches. resolve is here mainly for historical reasons, and for when you are hit by recursive merge strategy corner cases.

How to use Google App Engine with my own naked domain (not subdomain)?

[Update April 2016] This answer is now outdated, custom naked domain mapping is supported, see Lawrence Mok's answer.

See http://www.google.com/support/a/bin/answer.py?hl=en&answer=91077 for the details. Once you have signed up for Google Apps for Your Domain:

# Sign in to the Google App Engine admin console.
# Go to Administration > Versions
# Click the 'Add Domain...' button under Domain Setup.
# Enter your domain name in the 'Domain Name:' field
# Click 'Add Domain'. You will be directed to the Google Apps administrator console to complete the process.
# Log in to the Google Apps control panel with your administrator account.
# Accept the terms and specify the access URL you'd like to provide for your application.
# Click 'Accept

You can't use a naked domain, though, such as whatever.com (but www.whatever.com does work), because:

Due to recent changes, Google App Engine no longer supports mapping your app to a naked domain. If your domain registrar supports URL redirects, you can redirect from http://yourdomain.com to your app, which can be served from domains like http://www.yourdomain.com or http://appid.yourdomain.com.

as specified at http://www.google.com/support/a/bin/answer.py?answer=91080

How can I reload .emacs after changing it?

solution

M-: (load user-init-file)


notes

  • you type it in Eval: prompt (including the parentheses)
  • user-init-file is a variable holding the ~/.emacs value (pointing to the configuration file path) by default
  • (load) is shorter, older, and non-interactive version of (load-file); it is not an emacs command (to be typed in M-x) but a mere elisp function

conclusion

M-: > M-x

Asp.net - Add blank item at top of dropdownlist

it looks like you are adding a blank item, and then databinding, which would empty the list; try inserting the blank item after databinding

Can Windows Containers be hosted on linux?

Windows containers are not running on Linux and also You can't run Linux containers on Windows directly.

Set selected radio from radio group with a value

There is a better way of checking radios and checkbox; you have to pass an array of values to the val method instead of a raw value

Note: If you simply pass the value by itself (without being inside an array), that will result in all values of "mygroup" being set to the value.

$("input[name=mygroup]").val([5]);

Here is the jQuery doc that explains how it works: http://api.jquery.com/val/#val-value

And .val([...]) also works with form elements like <input type="checkbox">, <input type="radio">, and <option>s inside of a <select>.

The inputs and the options having a value that matches one of the elements of the array will be checked or selected, while those having a value that don't match one of the elements of the array will be unchecked or unselected

Fiddle demonstrating this working: https://jsfiddle.net/92nekvp3/

Using pointer to char array, values in that array can be accessed?

When you want to access an element, you have to first dereference your pointer, and then index the element you want (which is also dereferncing). i.e. you need to do:

printf("\nvalue:%c", (*ptr)[0]); , which is the same as *((*ptr)+0)

Note that working with pointer to arrays are not very common in C. instead, one just use a pointer to the first element in an array, and either deal with the length as a separate element, or place a senitel value at the end of the array, so one can learn when the array ends, e.g.

char arr[5] = {'a','b','c','d','e',0}; 
char *ptr = arr; //same as char *ptr = &arr[0]

printf("\nvalue:%c", ptr[0]);

parseInt with jQuery

var test = parseInt($("#testid").val(), 10);

You have to tell it you want the value of the input you are targeting.

And also, always provide the second argument (radix) to parseInt. It tries to be too clever and autodetect it if not provided and can lead to unexpected results.

Providing 10 assumes you are wanting a base 10 number.

Google Chrome form autofill and its yellow background

Here's the MooTools version of Jason's. Fixes it in Safari too.

window.addEvent('domready',function() { 
    $('username').focus();

    if ((navigator.userAgent.toLowerCase().indexOf(\"chrome\") >= 0)||(navigator.userAgent.toLowerCase().indexOf(\"safari\") >= 0))
    {

        var _interval = window.setInterval(function ()
        {
            var autofills = $$('input:-webkit-autofill');
            if (autofills.length > 0)
            {

                window.clearInterval(_interval); // stop polling
                autofills.each(function(el)
                {
                    var clone = el.clone(true,true).inject(el,'after');;
                    el.dispose();
                });
            }
        }, 20);                                               


    }
});

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

opencv has changed some functions and moved them to their opencv_contrib repo so you have to call the mentioned method with:

recognizer = cv2.face.createLBPHFaceRecognizer()

Note: You can see this issue about missing docs. Try using help function help(cv2.face.createLBPHFaceRecognizer) for more details.

Authentication plugin 'caching_sha2_password' cannot be loaded

Downloading a development release of 8.0.11-rc worked for me on a mac. with the following docker commands:

docker run --name mysql -p 3406:3306 -e MYSQL_ROOT_PASSWORD=mypassword -d mysql

Loading a properties file from Java package

public class Test{  
  static {
    loadProperties();
}
   static Properties prop;
   private static void loadProperties() {
    prop = new Properties();
    InputStream in = Test.class
            .getResourceAsStream("test.properties");
    try {
        prop.load(in);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

How can I inspect element in an Android browser?

You can inspect elements of a website in your Android device using Chrome browser.

Open your Chrome browser and go to the website you want to inspect.

Go to the address bar and type "view-source:" before the "HTTP" and reload the page.

The whole elements of the page will be shown.

How to remove jar file from local maven repository which was added with install:install-file?

While there is a maven command you can execute to do this, it's easier to just delete the files manually from the repository.

Like this on windows Documents and Settings\your username\.m2 or $HOME/.m2 on Linux

C++ IDE for Macs

Xcode is free and good, which is lucky because it's pretty much the only option on the Mac.

Can I have multiple Xcode versions installed?

Install Multiple Versions Of Xcode using the Xcode-Install Ruby Gem

You can do this whole process a lot easier if you use the xcode-install RubyGem.

If you already have a working installation of the Xcode CommandLineTools and Ruby (I'd suggest using Homebrew for installing Ruby) but I think it works with the Ruby supplied by macOS as well if you install the Gem either using sudo or as a user install. (Details on the GitHub page) Basically:

    $ gem install xcode-install
    $ xcversion list
    6.0.1
    6.1
    6.1.1
    6.2 (installed)
    6.3
    $ xcversion install 8
    ######################################################################## 100.0%
    Please authenticate for Xcode installation...

    Xcode 8
    Build version 6D570

To select a version as active, you'll run:
$ xcversion select 8

To select a version as active and change the symlink at /Applications/Xcode, you'll run:
$ xcversion select 8 --symlink

xcode-install can also manage your local simulators using the simulators command.

Read the instructions on the GitHub Project page for more info.

<Django object > is not JSON serializable

Another great way of solving it while using a model is by using the values() function.

def returnResponse(date):
    response = ScheduledDate.objects.filter(date__startswith=date).values()
    return Response(response)

Convert a dta file to csv without Stata software

For those who have Stata (even though the asker does not) you can use this:

outsheet produces a tab-delimited file so you need to specify the comma option like below

outsheet [varlist] using file.csv , comma

also, if you want to remove labels (which are included by default

outsheet [varlist] using file.csv, comma nolabel

hat tip to:

http://www.ats.ucla.edu/stat/stata/faq/outsheet.htm

HTML anchor tag with Javascript onclick event

You can even try below option:

<a href="javascript:show_more_menu();">More >>></a>

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

@bku_drytt's solution didn't do it for me.

I solved it by additionally changing every occurence of 14.0 to 12.0 and v140 to v120 manually in the .vcxproj files.

Then it compiled!

Call angularjs function using jquery/javascript

You can use following:

angular.element(domElement).scope() to get the current scope for the element

angular.element(domElement).injector() to get the current app injector

angular.element(domElement).controller() to get a hold of the ng-controller instance.

Hope that might help

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

In my case i have included jdbc api dependencies in the project so the "Hello World" not printed. After removing the below dependency it works like a charm.

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

Function vs. Stored Procedure in SQL Server

  • Functions can be used in a select statement where as procedures cannot.

  • Stored procedure takes both input and output parameters but Functions takes only input parameters.

  • Functions cannot return values of type text, ntext, image & timestamps where as procedures can.

  • Functions can be used as user defined datatypes in create table but procedures cannot.

***Eg:-create table <tablename>(name varchar(10),salary getsal(name))

Here getsal is a user defined function which returns a salary type, when table is created no storage is allotted for salary type, and getsal function is also not executed, But when we are fetching some values from this table, getsal function get’s executed and the return Type is returned as the result set.

PHP Regex to check date is in YYYY-MM-DD format

This method can be useful to validate date in PHP. Current method is for mm/dd/yyyy format. You have to update parameter sequence in checkdate as per your format and delimiter in explode .

    function isValidDate($dt)
    {
        $dtArr = explode('/', $dt);
        if (!empty($dtArr[0]) && !empty($dtArr[1]) && !empty($dtArr[2])) {
            return checkdate((int) $dtArr[0], (int) $dtArr[1], (int) $dtArr[2]);
        } else {
            return false;
        }
    }

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

If you need to allow html input for action-method parameter (opposed to "model property") there's no built-in way to do that but you can easily achieve this using a custom model binder:

public ActionResult AddBlogPost(int userId,
    [ModelBinder(typeof(AllowHtmlBinder))] string htmlBody)
{
    //...
}

The AllowHtmlBinder code:

public class AllowHtmlBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;
        var name = bindingContext.ModelName;
        return request.Unvalidated[name]; //magic happens here
    }
}

Find the complete source code and the explanation in my blog post: https://www.jitbit.com/alexblog/273-aspnet-mvc-allowing-html-for-particular-action-parameters/

How to write a JSON file in C#?

The example in Liam's answer saves the file as string in a single line. I prefer to add formatting. Someone in the future may want to change some value manually in the file. If you add formatting it's easier to do so.

The following adds basic JSON indentation:

 string json = JsonConvert.SerializeObject(_data.ToArray(), Formatting.Indented);

Multiplication on command line terminal

I use this function which uses bc and thus supports floating point calculations:

c () { 
    local a
    (( $# > 0 )) && a="$@" || read -r -p "calc: " a
    bc -l <<< "$a"
}

Example:

$ c '5*5'
25
$ c 5/5
1.00000000000000000000
$ c 3.4/7.9
.43037974683544303797

Bash's arithmetic expansion doesn't support floats (but Korn shell and zsh do).

Example:

$ ksh -c 'echo "$((3.0 / 4))"'
0.75

Writing Unicode text to a text file?

How to print unicode characters into a file:

Save this to file: foo.py:

#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import codecs
import sys 
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
print(u'e with obfuscation: é')

Run it and pipe output to file:

python foo.py > tmp.txt

Open tmp.txt and look inside, you see this:

el@apollo:~$ cat tmp.txt 
e with obfuscation: é

Thus you have saved unicode e with a obfuscation mark on it to a file.

jQuery AJAX Call to PHP Script with JSON Return

Use parseJSON jquery method to covert string into object

var objData = jQuery.parseJSON(data);

Now you can write code

$('#result').html(objData .status +':' + objData .message);

Experimental decorators warning in TypeScript compilation

Open entire project's folder instead of project-name/src

tsconfig.json is out of src folder

Read Variable from Web.Config

Assuming the key is contained inside the <appSettings> node:

ConfigurationSettings.AppSettings["theKey"];

As for "writing" - put simply, dont.

The web.config is not designed for that, if you're going to be changing a value constantly, put it in a static helper class.

Why is there no Constant feature in Java?

The C++ semantics of const are very different from Java final. If the designers had used const it would have been unnecessarily confusing.

The fact that const is a reserved word suggests that the designers had ideas for implementing const, but they have since decided against it; see this closed bug. The stated reasons include that adding support for C++ style const would cause compatibility problems.

How can I process each letter of text using Javascript?

You can get an array of the individual characters like so

var test = "test string",
    characters = test.split('');

and then loop using regular Javascript, or else you can iterate over the string's characters using jQuery by

var test = "test string";

$(test.split('')).each(function (index,character) {
    alert(character);
});

Remove a character at a certain position in a string - javascript

If you omit the particular index character then use this method

function removeByIndex(str,index) {
      return str.slice(0,index) + str.slice(index+1);
}
    
var str = "Hello world", index=3;
console.log(removeByIndex(str,index));

// Output: "Helo world"

How I can get and use the header file <graphics.h> in my C++ program?

<graphics.h> is very old library. It's better to use something that is new

Here are some 2D libraries (platform independent) for C/C++

SDL

GTK+

Qt

Also there is a free very powerful 3D open source graphics library for C++

OGRE

How to check if a string in Python is in ASCII?

Your question is incorrect; the error you see is not a result of how you built python, but of a confusion between byte strings and unicode strings.

Byte strings (e.g. "foo", or 'bar', in python syntax) are sequences of octets; numbers from 0-255. Unicode strings (e.g. u"foo" or u'bar') are sequences of unicode code points; numbers from 0-1112064. But you appear to be interested in the character é, which (in your terminal) is a multi-byte sequence that represents a single character.

Instead of ord(u'é'), try this:

>>> [ord(x) for x in u'é']

That tells you which sequence of code points "é" represents. It may give you [233], or it may give you [101, 770].

Instead of chr() to reverse this, there is unichr():

>>> unichr(233)
u'\xe9'

This character may actually be represented either a single or multiple unicode "code points", which themselves represent either graphemes or characters. It's either "e with an acute accent (i.e., code point 233)", or "e" (code point 101), followed by "an acute accent on the previous character" (code point 770). So this exact same character may be presented as the Python data structure u'e\u0301' or u'\u00e9'.

Most of the time you shouldn't have to care about this, but it can become an issue if you are iterating over a unicode string, as iteration works by code point, not by decomposable character. In other words, len(u'e\u0301') == 2 and len(u'\u00e9') == 1. If this matters to you, you can convert between composed and decomposed forms by using unicodedata.normalize.

The Unicode Glossary can be a helpful guide to understanding some of these issues, by pointing how how each specific term refers to a different part of the representation of text, which is far more complicated than many programmers realize.

Create a jTDS connection string

jdbc:jtds:sqlserver://x.x.x.x/database replacing x.x.x.x with the IP or hostname of your SQL Server machine.

jdbc:jtds:sqlserver://MYPC/Blog;instance=SQLEXPRESS

or

jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS

If you are wanting to set the username and password in the connection string too instead of against a connection object separately:

jdbc:jtds:sqlserver://MYPC/Blog;instance=SQLEXPRESS;user=foo;password=bar

(Updated my incorrect information and add reference to the instance syntax)

How to use sessions in an ASP.NET MVC 4 application?

U can store any value in session like Session["FirstName"] = FirstNameTextBox.Text; but i will suggest u to take as static field in model assign value to it and u can access that field value any where in application. U don't need session. session should be avoided.

public class Employee
{
   public int UserId { get; set; }
   public string EmailAddress { get; set; }
   public static string FullName { get; set; }
}

on controller - Employee.FullName = "ABC"; Now u can access this full Name anywhere in application.

How to create a folder with name as current date in batch (.bat) files

If your locale has date format "DDMMYYYY" you'll have to set it this way:

set datestr=%date:~-4,4%%date:~3,2%%date:~-10,2%
mkdir %datestr%

How to truncate float values?

def trunc(f,n):
  return ('%.16f' % f)[:(n-16)]

How to get certain commit from GitHub project

write this to see your commits

git log --oneline

copy the name of the commit you want to go back to. then write:

git checkout "name of the commit"

when you do this, the files of that commit will be replaced with your current files. then you can do whatever you want to these and once you're done, you can write the following command to extract the current files into another newly created branch so whatever you make doesn't have any danger for the previous branch that you extracted a commit from

git checkout -b "name of a branch to extract the files to"

right now, you have the content of a specified commit, into another branch .

git ahead/behind info between master and branch?

With Git 2.5+, you now have another option to see ahead/behind for all branches which are configured to push to a branch.

git for-each-ref --format="%(push:track)" refs/heads

See more at "Viewing Unpushed Git Commits"

Using a list as a data source for DataGridView

this Func may help you . it add every list object to grid view

private void show_data()
        {
            BindingSource Source = new BindingSource();

            for (int i = 0; i < CC.Contects.Count; i++)
            {
                Source.Add(CC.Contects.ElementAt(i));
            };


            Data_View.DataSource = Source;

        }

I write this for simple database app

Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
    private JLabel label;
    private JTextField field;
    public Test()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        btn.setActionCommand("myButton");
        btn.addActionListener(this);
        label = new JLabel("flag");
        field = new JTextField(5);
        add(field);
        add(btn);
        add(label);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("myButton"))
        {
            label.setText(field.getText());
        }
    }
    public static void main(String[] args)
    {
        new Test();
    }
}

Refreshing data in RecyclerView and keeping its scroll position

I have not used Recyclerview but I did it on ListView. Sample code in Recyclerview:

setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        rowPos = mLayoutManager.findFirstVisibleItemPosition();

It is the listener when user is scrolling. The performance overhead is not significant. And the first visible position is accurate this way.

Press any key to continue

Here is what I use.

Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

jQuery '.each' and attaching '.click' event

One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.

For example:

HTML:

<body>
<div id="dog" class="selected" data-selected="false">dog</div>
<div id="cat" class="selected" data-selected="true">cat</div>
<div id="mouse" class="selected" data-selected="false">mouse</div>

<div class="dog"><img/></div>
<div class="cat"><img/></div>
<div class="mouse"><img/></div>
</body>

JS:

$( ".selected" ).each(function(index) {
    $(this).on("click", function(){
        // For the boolean value
        var boolKey = $(this).data('selected');
        // For the mammal value
        var mammalKey = $(this).attr('id'); 
    });
});

How to return a PNG image from Jersey REST service method to the browser

If you have a number of image resource methods, it is well worth creating a MessageBodyWriter to output the BufferedImage:

@Produces({ "image/png", "image/jpg" })
@Provider
public class BufferedImageBodyWriter implements MessageBodyWriter<BufferedImage>  {
  @Override
  public boolean isWriteable(Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
    return type == BufferedImage.class;
  }

  @Override
  public long getSize(BufferedImage t, Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
    return -1; // not used in JAX-RS 2
  }

  @Override
  public void writeTo(BufferedImage image, Class<?> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, Object> mm, OutputStream out) throws IOException, WebApplicationException {
    ImageIO.write(image, mt.getSubtype(), out);
  } 
}

This MessageBodyWriter will be used automatically if auto-discovery is enabled for Jersey, otherwise it needs to be returned by a custom Application sub-class. See JAX-RS Entity Providers for more info.

Once this is set up, simply return a BufferedImage from a resource method and it will be be output as image file data:

@Path("/whatever")
@Produces({"image/png", "image/jpg"})
public Response getFullImage(...) {
  BufferedImage image = ...;
  return Response.ok(image).build();
}

A couple of advantages to this approach:

  • It writes to the response OutputSteam rather than an intermediary BufferedOutputStream
  • It supports both png and jpg output (depending on the media types allowed by the resource method)

How to copy a char array in C?

You can't directly do array2 = array1, because in this case you manipulate the addresses of the arrays (char *) and not of their inner values (char).

What you, conceptually, want is to do is iterate through all the chars of your source (array1) and copy them to the destination (array2). There are several ways to do this. For example you could write a simple for loop, or use memcpy.

That being said, the recommended way for strings is to use strncpy. It prevents common errors resulting in, for example, buffer overflows (which is especially dangerous if array1 is filled from user input: keyboard, network, etc). Like so:

// Will copy 18 characters from array1 to array2
strncpy(array2, array1, 18);

As @Prof. Falken mentioned in a comment, strncpy can be evil. Make sure your target buffer is big enough to contain the source buffer (including the \0 at the end of the string).

How to force a line break in a long word in a DIV?

just try this in our style

white-space: normal;

maxlength ignored for input type="number" in Chrome

Max length will not work with <input type="number" the best way i know is to use oninput event to limit the maxlength. Please see the below code.

<input name="somename"
    oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    type = "number"
    maxlength = "6"
 />

Stop UIWebView from "bouncing" vertically?

I was looking at a project that makes it easy to create web apps as full fledged installable applications on the iPhone called QuickConnect, and found a solution that works, if you don't want your screen to be scrollable at all, which in my case I didn't.

In the above mentioned project/blog post, they mention a javascript function you can add to turn off the bouncing, which essentially boils down to this:

    document.ontouchmove = function(event){
        event.preventDefault();
    }

If you want to see more about how they implement it, simply download QuickConnect and check it out.... But basically all it does is call that javascript on page load... I tried just putting it in the head of my document, and it seems to work fine.

Exit Shell Script Based on Process Exit Code

http://cfaj.freeshell.org/shell/cus-faq-2.html#11

  1. How do I get the exit code of cmd1 in cmd1|cmd2

    First, note that cmd1 exit code could be non-zero and still don't mean an error. This happens for instance in

    cmd | head -1
    

    You might observe a 141 (or 269 with ksh93) exit status of cmd1, but it's because cmd was interrupted by a SIGPIPE signal when head -1 terminated after having read one line.

    To know the exit status of the elements of a pipeline cmd1 | cmd2 | cmd3

    a. with Z shell (zsh):

    The exit codes are provided in the pipestatus special array. cmd1 exit code is in $pipestatus[1], cmd3 exit code in $pipestatus[3], so that $? is always the same as $pipestatus[-1].

    b. with Bash:

    The exit codes are provided in the PIPESTATUS special array. cmd1 exit code is in ${PIPESTATUS[0]}, cmd3 exit code in ${PIPESTATUS[2]}, so that $? is always the same as ${PIPESTATUS: -1}.

    ...

    For more details see Z shell.

Positioning <div> element at center of screen

Set the width and height and you're good.

div {
  position: absolute;
  margin: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 200px;
  height: 200px;
}

If you want the element dimensions to be flexible (and don't care about legacy browsers), go with XwipeoutX's answer.

Convert a Unix timestamp to time in JavaScript

The modern solution that doesn't need a 40 KB library:

Intl.DateTimeFormat is the non-culturally imperialistic way to format a date/time.

// Setup once
var options = {
    //weekday: 'long',
    //month: 'short',
    //year: 'numeric',
    //day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric'
},
intlDate = new Intl.DateTimeFormat( undefined, options );

// Reusable formatter
var timeStamp = 1412743273;
console.log( intlDate.format( new Date( 1000 * timeStamp ) ) );

Parsing JSON giving "unexpected token o" error

Using JSON.stringify(data);:

$.ajax({
    url: ...
    success:function(data){
        JSON.stringify(data); //to string
        alert(data.you_value); //to view you pop up
    }
});

Check if program is running with bash shell script?

PROCESS="process name shown in ps -ef"
START_OR_STOP=1        # 0 = start | 1 = stop

MAX=30
COUNT=0

until [ $COUNT -gt $MAX ] ; do
        echo -ne "."
        PROCESS_NUM=$(ps -ef | grep "$PROCESS" | grep -v `basename $0` | grep -v "grep" | wc -l)
        if [ $PROCESS_NUM -gt 0 ]; then
            #runs
            RET=1
        else
            #stopped
            RET=0
        fi

        if [ $RET -eq $START_OR_STOP ]; then
            sleep 5 #wait...
        else
            if [ $START_OR_STOP -eq 1 ]; then
                    echo -ne " stopped"
            else
                    echo -ne " started"
            fi
            echo
            exit 0
        fi
        let COUNT=COUNT+1
done

if [ $START_OR_STOP -eq 1 ]; then
    echo -ne " !!$PROCESS failed to stop!! "
else
    echo -ne " !!$PROCESS failed to start!! "
fi
echo
exit 1

Python integer incrementing with ++

Python doesn't support ++, but you can do:

number += 1

Fake "click" to activate an onclick method

For IE there is fireEvent() method. Don't know if that works for other browsers.

How can I insert new line/carriage returns into an element.textContent?

nelek's answer is the best one posted so far, but it relies on setting the css value: white-space: pre, which might be undesirable.

I'd like to offer a different solution, which tries to tackle the real question that should've been asked here:

"How to insert untrusted text into a DOM element?"

If you trust the text, why not just use innerHTML?

domElement.innerHTML = trustedText.replace(/\r/g, '').replace(/\n/g, '<br>');

should be sufficient for all the reasonable cases.

If you decided you should use .textContent instead of .innerHTML, it means you don't trust the text that you're about to insert, right? This is a reasonable concern.

For example, you have a form where the user can create a post, and after posting it, the post text is stored in your database, and later on appended to pages whenever other users visit the relevant page.

If you use innerHTML here, you get a security breach. i.e., a user can post something like

[script]alert(1);[/script]

(try to imagine that [] are <>, apparently stack overflow is appending text in unsafe ways!)

which won't trigger an alert if you use innerHTML, but it should give you an idea why using innerHTML can have issues. a smarter user would post

[img src="invalid_src" onerror="alert(1)"]

which would trigger an alert for every other user that visits the page. Now we have a problem. An even smarter user would put display: none on that img style, and make it post the current user's cookies to a cross domain site. Congratulations, all your user login details are now exposed on the internet.

So, the important thing to understand is, using innerHTML isn't wrong, it's perfect if you're just using it to build templates using only your own trusted developer code. The real question should've been "how do I append untrusted user text that has newlines to my HTML document".

This raises a question: which strategy do we use for newlines? do we use [br] elements? [p]s or [div]s?

Here is a short function that solves the problem:

function insertUntrustedText(domElement, untrustedText, newlineStrategy) {
    domElement.innerHTML = '';
    var lines = untrustedText.replace(/\r/g, '').split('\n');
    var linesLength = lines.length;
    if(newlineStrategy === 'br') {
        for(var i = 0; i < linesLength; i++) {
            domElement.appendChild(document.createTextNode(lines[i]));
            domElement.appendChild(document.createElement('br'));
        }
    }
    else {
        for(var i = 0; i < linesLength; i++) {
            var lineElement = document.createElement(newlineStrategy);
            lineElement.textContent = lines[i];
            domElement.appendChild(lineElement);
        }
    }
}

You can basically throw this somewhere in your common_functions.js file and then just fire and forget whenever you need to append any user/api/etc -> untrusted text (i.e. not-written-by-your-own-developer-team) to your html pages.

usage example:

insertUntrustedText(document.querySelector('.myTextParent'), 'line1\nline2\r\nline3', 'br');

the parameter newlineStrategy accepts only valid dom element tags, so if you want [br] newlines, pass 'br', if you want each line in a [p] element, pass 'p', etc.

Writing new lines to a text file in PowerShell

`n is a line feed character. Notepad (prior to Windows 10) expects linebreaks to be encoded as `r`n (carriage return + line feed, CR-LF). Open the file in some useful editor (SciTE, Notepad++, UltraEdit-32, Vim, ...) and convert the linebreaks to CR-LF. Or use PowerShell:

(Get-Content $logpath | Out-String) -replace "`n", "`r`n" | Out-File $logpath

Getting 400 bad request error in Jquery Ajax POST

You need to build query from "data" object using the following function

function buildQuery(obj) {
        var Result= '';
        if(typeof(obj)== 'object') {
            jQuery.each(obj, function(key, value) {
                Result+= (Result) ? '&' : '';
                if(typeof(value)== 'object' && value.length) {
                    for(var i=0; i<value.length; i++) {
                        Result+= [key+'[]', encodeURIComponent(value[i])].join('=');
                    }
                } else {
                    Result+= [key, encodeURIComponent(value)].join('=');
                }
            });
        }
        return Result;
    }

and then proceed with

var data= {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work, facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: buildQuery(data),
  error: function(e) {
    console.log(e);
  }
});

Call Jquery function

To call the function on click of some html element (control).

$('#controlID').click(myFunction);

You will need to ensure you bind the event when your html element is ready on which you binding the event. You can put the code in document.ready

$(document).ready(function(){
    $('#controlID').click(myFunction);
});

You can use anonymous function to bind the event to the html element.

$(document).ready(function(){
    $('#controlID').click(function(){
         $.messager.show({  
            title:'My Title',  
            msg:'The message content',  
            showType:'fade',  
            style:{  
                right:'',  
                bottom:''  
            }  
        });  
    });
});

If you want to bind click with many elements you can use class selector

$('.someclass').click(myFunction);

Edit based on comments by OP, If you want to call function under some condition

You can use if for conditional execution, for example,

if(a == 3)
     myFunction();

Integrating CSS star rating into an HTML form

This is very easy to use, just copy-paste the code. You can use your own star image in background.

I have created a variable var userRating. you can use this variable to get value from stars.

Enjoy!! :)

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    // Check Radio-box_x000D_
    $(".rating input:radio").attr("checked", false);_x000D_
_x000D_
    $('.rating input').click(function () {_x000D_
        $(".rating span").removeClass('checked');_x000D_
        $(this).parent().addClass('checked');_x000D_
    });_x000D_
_x000D_
    $('input:radio').change(_x000D_
      function(){_x000D_
        var userRating = this.value;_x000D_
        alert(userRating);_x000D_
    }); _x000D_
});
_x000D_
.rating {_x000D_
    float:left;_x000D_
    width:300px;_x000D_
}_x000D_
.rating span { float:right; position:relative; }_x000D_
.rating span input {_x000D_
    position:absolute;_x000D_
    top:0px;_x000D_
    left:0px;_x000D_
    opacity:0;_x000D_
}_x000D_
.rating span label {_x000D_
    display:inline-block;_x000D_
    width:30px;_x000D_
    height:30px;_x000D_
    text-align:center;_x000D_
    color:#FFF;_x000D_
    background:#ccc;_x000D_
    font-size:30px;_x000D_
    margin-right:2px;_x000D_
    line-height:30px;_x000D_
    border-radius:50%;_x000D_
    -webkit-border-radius:50%;_x000D_
}_x000D_
.rating span:hover ~ span label,_x000D_
.rating span:hover label,_x000D_
.rating span.checked label,_x000D_
.rating span.checked ~ span label {_x000D_
    background:#F90;_x000D_
    color:#FFF;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="rating">_x000D_
    <span><input type="radio" name="rating" id="str5" value="5"><label for="str5"></label></span>_x000D_
    <span><input type="radio" name="rating" id="str4" value="4"><label for="str4"></label></span>_x000D_
    <span><input type="radio" name="rating" id="str3" value="3"><label for="str3"></label></span>_x000D_
    <span><input type="radio" name="rating" id="str2" value="2"><label for="str2"></label></span>_x000D_
    <span><input type="radio" name="rating" id="str1" value="1"><label for="str1"></label></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Deny all, allow only one IP through htaccess

Just in addition to @David Brown´s answer, if you want to block an IP, you must first allow all then block the IPs as such:

    <RequireAll>
      Require all granted
      Require not ip 10.0.0.0/255.0.0.0
      Require not ip 172.16.0.0/12
      Require not ip 192.168
    </RequireAll>

First line allows all
Second line blocks from 10.0.0.0 to 10.255.255.255
Third line blocks from 172.16.0.0 to 172.31.255.255
Fourth line blocks from 192.168.0.0 to 192.168.255.255

You may use any of the notations mentioned above to suit you CIDR needs.

The difference between "require(x)" and "import x"

Not an answer here and more like a comment, sorry but I can't comment.

In node V10, you can use the flag --experimental-modules to tell Nodejs you want to use import. But your entry script should end with .mjs.

Note this is still an experimental thing and should not be used in production.

// main.mjs
import utils from './utils.js'
utils.print();
// utils.js
module.exports={
    print:function(){console.log('print called')}
}

Ref 1 - Nodejs Doc

Ref 2 - github issue

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

Android Layout Weight

Think it that way, will be simpler

If you have 3 buttons and their weights are 1,3,1 accordingly, it will work like table in HTML

Provide 5 portions for that line: 1 portion for button 1, 3 portion for button 2 and 1 portion for button 1

How to force garbage collection in Java?

If you are using JUnit and Spring, try adding this in every test class:

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)

"Sources directory is already netbeans project" error when opening a project from existing sources

On Windows at least none of these answers work (for me anyway!). I have found the only way is to copy an existing netbeans project folder in to your new project and manually edit the xml project name.

I also opened the private/private.xml and removed the open files xml just incase these caused problems.

Once I'd done this the project works as normal.

Auto expand a textarea using jQuery

I wrote this jquery function that seems to work.

You need to specify min-height in css though, and unless you want to do some coding, it needs to be two digits long. ie 12px;

$.fn.expand_ta = function() {

var val = $(this).val();
val = val.replace(/</g, "&lt;");
val = val.replace(/>/g, "&gt;");
val += "___";

var ta_class = $(this).attr("class");
var ta_width = $(this).width();

var min_height = $(this).css("min-height").substr(0, 2);
min_height = parseInt(min_height);

$("#pixel_height").remove();
$("body").append('<pre class="'+ta_class+'" id="pixel_height" style="position: absolute; white-space: pre-wrap; visibility: hidden; word-wrap: break-word; width: '+ta_width+'px; height: auto;"></pre>');
$("#pixel_height").html(val);

var height = $("#pixel_height").height();
if (val.substr(-6) == "<br />"){
    height = height + min_height;
};
if (height >= min_height) $(this).css("height", height+"px");
else $(this).css("height", min_height+"px");
}

Android Studio was unable to find a valid Jvm (Related to MAC OS)

i'm dealing with the same problem and i get it worked.

it is probably that your jdk version is not right.

now i installed jdk1.8 and it is ok now.

Self-reference for cell, column and row in worksheet functions

I don't see the need for Indirect, especially for conditional formatting.

The simplest way to self-reference a cell, row or column is to refer to it normally, e.g., "=A1" in cell A1, and make the reference partly or completely relative. For example, in a conditional formatting formula for checking whether there's a value in the first column of various cells' rows, enter the following with A1 highlighted and copy as necessary. The conditional formatting will always refer to column A for the row of each cell:

= $A1 <> ""

Is there any boolean type in Oracle databases?

A common space-saving trick is storing boolean values as an Oracle CHAR, rather than NUMBER:

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

This can also happen when the log file is restricted in size.

Right click database in Object Explorer

Select Properties

Select Files

On the log line, click the ellipsis in the Autogrowth / Maxsize column

Change/verify Maximum File Size is Unlimited.

enter image description here

After chaning to unlimited, database came back to life.

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

Yes. I don't have any examples that I've done personally available right now. I'll post later when I find some. Basically you'll use reflection to load the assembly and then to pull whatever types you need for it.

In the meantime, this link should get you started:

Using reflection to load unreferenced assemblies at runtime

Tooltip with HTML content without JavaScript

This one is very interesting,

HTML and CSS only

_x000D_
_x000D_
.help-tip {_x000D_
  position: absolute;_x000D_
  top: 18px;_x000D_
  left: 18px;_x000D_
  text-align: center;_x000D_
  background-color: #BCDBEA;_x000D_
  border-radius: 50%;_x000D_
  width: 24px;_x000D_
  height: 24px;_x000D_
  font-size: 14px;_x000D_
  line-height: 26px;_x000D_
  cursor: default;_x000D_
}_x000D_
_x000D_
.help-tip:before {_x000D_
  content: '?';_x000D_
  font-weight: bold;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.help-tip:hover span {_x000D_
  display: block;_x000D_
  transform-origin: 100% 0%;_x000D_
  -webkit-animation: fadeIn 0.3s ease-in-out;_x000D_
  animation: fadeIn 0.3s ease-in-out;_x000D_
}_x000D_
_x000D_
.help-tip span {_x000D_
  display: none;_x000D_
  text-align: left;_x000D_
  background-color: #1E2021;_x000D_
  padding: 5px;_x000D_
  width: 200px;_x000D_
  position: absolute;_x000D_
  border-radius: 3px;_x000D_
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.2);_x000D_
  left: -4px;_x000D_
  color: #FFF;_x000D_
  font-size: 13px;_x000D_
  line-height: 1.4;_x000D_
}_x000D_
_x000D_
.help-tip span:before {_x000D_
  position: absolute;_x000D_
  content: '';_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
  border: 6px solid transparent;_x000D_
  border-bottom-color: #1E2021;_x000D_
  left: 10px;_x000D_
  top: -12px;_x000D_
}_x000D_
_x000D_
.help-tip span:after {_x000D_
  width: 100%;_x000D_
  height: 40px;_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  top: -40px;_x000D_
  left: 0;_x000D_
}
_x000D_
<span class="help-tip">_x000D_
     <span > This is the inline help tip! </span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

Timing a command's execution in PowerShell

Just a word on drawing (incorrect) conclusions from any of the performance measurement commands referred to in the answers. There are a number of pitfalls that should taken in consideration aside from looking to the bare invocation time of a (custom) function or command.

Sjoemelsoftware

'Sjoemelsoftware' voted Dutch word of the year 2015
Sjoemelen means cheating, and the word sjoemelsoftware came into being due to the Volkswagen emissions scandal. The official definition is "software used to influence test results".

Personally, I think that "Sjoemelsoftware" is not always deliberately created to cheat test results but might originate from accommodating practical situation that are similar to test cases as shown below.

As an example, using the listed performance measurement commands, Language Integrated Query (LINQ)(1), is often qualified as the fasted way to get something done and it often is, but certainly not always! Anybody who measures a speed increase of a factor 40 or more in comparison with native PowerShell commands, is probably incorrectly measuring or drawing an incorrect conclusion.

The point is that some .Net classes (like LINQ) using a lazy evaluation (also referred to as deferred execution(2)). Meaning that when assign an expression to a variable, it almost immediately appears to be done but in fact it didn't process anything yet!

Let presume that you dot-source your . .\Dosomething.ps1 command which has either a PowerShell or a more sophisticated Linq expression (for the ease of explanation, I have directly embedded the expressions directly into the Measure-Command):

$Data = @(1..100000).ForEach{[PSCustomObject]@{Index=$_;Property=(Get-Random)}}

(Measure-Command {
    $PowerShell = $Data.Where{$_.Index -eq 12345}
}).totalmilliseconds
864.5237

(Measure-Command {
    $Linq = [Linq.Enumerable]::Where($Data, [Func[object,bool]] { param($Item); Return $Item.Index -eq 12345})
}).totalmilliseconds
24.5949

The result appears obvious, the later Linq command is a about 40 times faster than the first PowerShell command. Unfortunately, it is not that simple...

Let's display the results:

PS C:\> $PowerShell

Index  Property
-----  --------
12345 104123841

PS C:\> $Linq

Index  Property
-----  --------
12345 104123841

As expected, the results are the same but if you have paid close attention, you will have noticed that it took a lot longer to display the $Linq results then the $PowerShell results.
Let's specifically measure that by just retrieving a property of the resulted object:

PS C:\> (Measure-Command {$PowerShell.Property}).totalmilliseconds
14.8798
PS C:\> (Measure-Command {$Linq.Property}).totalmilliseconds
1360.9435

It took about a factor 90 longer to retrieve a property of the $Linq object then the $PowerShell object and that was just a single object!

Also notice an other pitfall that if you do it again, certain steps might appear a lot faster then before, this is because some of the expressions have been cached.

Bottom line, if you want to compare the performance between two functions, you will need to implement them in your used case, start with a fresh PowerShell session and base your conclusion on the actual performance of the complete solution.

(1) For more background and examples on PowerShell and LINQ, I recommend tihis site: High Performance PowerShell with LINQ
(2) I think there is a minor difference between the two concepts as with lazy evaluation the result is calculated when needed as apposed to deferred execution were the result is calculated when the system is idle

Google Chrome Full Black Screen

You didn't mention anything about the environment you're running. This problem occurs on VirtualBox when running on Windows 10. One thing you can try is disabling 3D Acceleration on your VM, this is a known issue.

https://www.virtualbox.org/ticket/14985

open program minimized via command prompt

Local Windows 10 ActiveMQ server :

@echo off
start /min "" "C:\Install\apache-activemq\5.15.10\bin\win64\activemq.bat" start

How do I restrict a float value to only two places after the decimal point in C?

Code definition :

#define roundz(x,d) ((floor(((x)*pow(10,d))+.5))/pow(10,d))

Results :

a = 8.000000
sqrt(a) = r = 2.828427
roundz(r,2) = 2.830000
roundz(r,3) = 2.828000
roundz(r,5) = 2.828430

Show pop-ups the most elegant way

See http://adamalbrecht.com/2013/12/12/creating-a-simple-modal-dialog-directive-in-angular-js/ for a simple way of doing modal dialog with Angular and without needing bootstrap

Edit: I've since been using ng-dialog from http://likeastore.github.io/ngDialog which is flexible and doesn't have any dependencies.

Updating a date in Oracle SQL table

If this SQL is being used in any peoplesoft specific code (Application Engine, SQLEXEC, SQLfetch, etc..) you could use %Datein metaSQL. Peopletools automatically converts the date to a format which would be accepted by the database platform the application is running on.

In case this SQL is being used to perform a backend update from a query analyzer (like SQLDeveloper, SQLTools), the date format that is being used is wrong. Oracle expects the date format to be DD-MMM-YYYY, where MMM could be JAN, FEB, MAR, etc..

Adding external library in Android studio

1.Goto File -> New -> Import Module
   2.Source Directory -> Browse the project path.
   3.Specify the Module Name – it is used for internal project reference.

Open build.gradle (Module:app) file.

 implementation project(':library')

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

I had a similar issues once. I deleted the primary key from TABLE A but when I was trying to delete the foreign key column from table B I was shown the above same error.

You can't drop the foreign key using the column name and to bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming or deleting the attribute.

Checkbox value true/false

Try this

_x000D_
_x000D_
$("#checkbox1").is(':checked', function(){_x000D_
  $("#checkbox1").prop('checked', true);_x000D_
});_x000D_
      
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="acceptRules" class="inline checkbox" id="checkbox1" value="false">
_x000D_
_x000D_
_x000D_

How to output a multiline string in Bash?

Also with indented source code you can use <<- (with a trailing dash) to ignore leading tabs (but not leading spaces).

For example this:

if [ some test ]; then
    cat <<- xx
        line1
        line2
xx
fi

Outputs indented text without the leading whitespace:

line1
line2

How do I get Flask to run on port 80?

you can easily disable any process running on port 80 and then run this command

flask run --host 0.0.0.0 --port 80

or if u prefer running it within the .py file

if __name__ == "__main__":
    app.run(host=0.0.0.0, port=80)

I need to convert an int variable to double

You have to cast one (or both) of the arguments to the division operator to double:

double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);

Since you are performing the same calculation twice I'd recommend refactoring your code:

double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;

This works in the same way, but now there is an implicit cast to double. This conversion from int to double is an example of a widening primitive conversion.

Primitive type 'short' - casting in Java

What language are you using?

Many C based languages have a rule that any mathematical expression is performed in size int or larger. Because of this, once you add two shorts the result is of type int. This causes the need for a cast.

Find the index of a dict within a list, by matching the dict's value

For a given iterable, more_itertools.locate yields positions of items that satisfy a predicate.

import more_itertools as mit


iterable = [
    {"id": "1234", "name": "Jason"},
    {"id": "2345", "name": "Tom"},
    {"id": "3456", "name": "Art"}
]

list(mit.locate(iterable, pred=lambda d: d["name"] == "Tom"))
# [1]

more_itertools is a third-party library that implements itertools recipes among other useful tools.

What is logits, softmax and softmax_cross_entropy_with_logits?

Tensorflow 2.0 Compatible Answer: The explanations of dga and stackoverflowuser2010 are very detailed about Logits and the related Functions.

All those functions, when used in Tensorflow 1.x will work fine, but if you migrate your code from 1.x (1.14, 1.15, etc) to 2.x (2.0, 2.1, etc..), using those functions result in error.

Hence, specifying the 2.0 Compatible Calls for all the functions, we discussed above, if we migrate from 1.x to 2.x, for the benefit of the community.

Functions in 1.x:

  1. tf.nn.softmax
  2. tf.nn.softmax_cross_entropy_with_logits
  3. tf.nn.sparse_softmax_cross_entropy_with_logits

Respective Functions when Migrated from 1.x to 2.x:

  1. tf.compat.v2.nn.softmax
  2. tf.compat.v2.nn.softmax_cross_entropy_with_logits
  3. tf.compat.v2.nn.sparse_softmax_cross_entropy_with_logits

For more information about migration from 1.x to 2.x, please refer this Migration Guide.

What are App Domains in Facebook Apps?

I think it is the domain that you run your app.

For example, your canvas URL is facebook.yourdomain.com, you should give App domain as .yourdomain.com

Sibling package imports

  1. Project

1.1 User

1.1.1 about.py

1.1.2 init.py

1.2 Tech

1.2.1 info.py

1.1.2 init.py

Now, if you want to access about.py module in the User package, from the info.py module in Tech package then you have to bring the cmd (in windows) path to Project i.e. **C:\Users\Personal\Desktop\Project>**as per the above Package example. And from this path you have to enter, python -m Package_name.module_name For example for the above Package we have to do,

C:\Users\Personal\Desktop\Project>python -m Tech.info

Imp Points

  1. Don't use .py extension after info module i.e. python -m Tech.info.py
  2. Enter this, where the siblings packages are in the same level.
  3. -m is the flag, to check about it you can type from the cmd python --help

Django - taking values from POST request

For django forms you can do this;

form = UserLoginForm(data=request.POST) #getting the whole data from the user.
user = form.save() #saving the details obtained from the user.
username = user.cleaned_data.get("username") #where "username" in parenthesis is the name of the Charfield (the variale name i.e, username = forms.Charfield(max_length=64))

How to scroll the page when a modal dialog is longer than the screen?

fixed positioning alone should have fixed that problem but another good workaround to avoid this issue is to place your modal divs or elements at the bottom of the page not within your sites layout. Most modal plugins give their modal positioning absolute to allow the user keep main page scrolling.

<html>
        <body>
        <!-- Put all your page layouts and elements


        <!-- Let the last element be the modal elemment  -->
        <div id="myModals">
        ...
        </div>

        </body>
</html>

Java String to SHA1

As mentioned before use apache commons codec. It's recommended by Spring guys as well (see DigestUtils in Spring doc). E.g.:

DigestUtils.sha1Hex(b);

Definitely wouldn't use the top rated answer here.

Execute bash script from URL

You can also do this:

wget -O - https://raw.github.com/luismartingil/commands/master/101_remote2local_wireshark.sh | bash

Python - How do you run a .py file?

use IDLE Editor {You may already have it} it has interactive shell for python and it will show you execution and result.

How can I render Partial views in asp.net mvc 3?

Create your partial view something like:

@model YourModelType
<div>
  <!-- HTML to render your object -->
</div>

Then in your view use:

@Html.Partial("YourPartialViewName", Model)

If you do not want a strongly typed partial view remove the @model YourModelType from the top of the partial view and it will default to a dynamic type.

Update

The default view engine will search for partial views in the same folder as the view calling the partial and then in the ~/Views/Shared folder. If your partial is located in a different folder then you need to use the full path. Note the use of ~/ in the path below.

@Html.Partial("~/Views/Partials/SeachResult.cshtml", Model)

Converting a string to a date in JavaScript

Timestamps should be casted to a Number

var ts = '1471793029764';
ts = Number(ts); // cast it to a Number
var date = new Date(ts); // works

var invalidDate = new Date('1471793029764'); // does not work. Invalid Date

SQLite in Android How to update a specific row

you can try this...

db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");

jQuery: Can I call delay() between addClass() and such?

You can create a new queue item to do your removing of the class:

$("#div").addClass("error").delay(1000).queue(function(next){
    $(this).removeClass("error");
    next();
});

Or using the dequeue method:

$("#div").addClass("error").delay(1000).queue(function(){
    $(this).removeClass("error").dequeue();
});

The reason you need to call next or dequeue is to let jQuery know that you are done with this queued item and that it should move on to the next one.

submitting a GET form with query string params and hidden params disappear

This is in response to the above post by Efx:

If the URL already contains the var you want to change, then it is added yet again as a hidden field.

Here is a modification of that code as to prevent duplicating vars in the URL:

foreach ($_GET as $key => $value) {
    if ($key != "my_key") {
        echo("<input type='hidden' name='$key' value='$value'/>");
    }
}

unsigned int vs. size_t

size_t is the size of a pointer.

So in 32 bits or the common ILP32 (integer, long, pointer) model size_t is 32 bits. and in 64 bits or the common LP64 (long, pointer) model size_t is 64 bits (integers are still 32 bits).

There are other models but these are the ones that g++ use (at least by default)

How can I add a vertical scrollbar to my div automatically?

Since OS X Lion, the scrollbar on websites are hidden by default and only visible once you start scrolling. Personally, I prefer the hidden scrollbar, but in case you really need it, you can overwrite the default and force the scrollbar in WebKit browsers back like this:

_x000D_
_x000D_
::-webkit-scrollbar {
    -webkit-appearance: none;
    width: 7px;
}
::-webkit-scrollbar-thumb {
    border-radius: 4px;
    background-color: rgba(0,0,0,.5);
    -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}
_x000D_
_x000D_
_x000D_

Jquery Ajax Posting json to webservice

I tried Dave Ward's solution. The data part was not being sent from the browser in the payload part of the post request as the contentType is set to "application/json". Once I removed this line everything worked great.

var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },

               { "position": "235.1944023323615", "markerPosition": "19" },

               { "position": "42.5978231292517", "markerPosition": "-3" }];

$.ajax({

    type: "POST",
    url: "/webservices/PodcastService.asmx/CreateMarkers",
    // The key needs to match your method's input parameter (case-sensitive).
    data: JSON.stringify({ Markers: markers }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){alert(data);},
    failure: function(errMsg) {
        alert(errMsg);
    }
});

Creating a textarea with auto-resize

Native Javascript solution without flickering in Firefox and faster than method withclientHeight...

1) Add div.textarea selector to all your selectors containing textarea. Do not forget to add box-sizing: border-box;

2) Include this script:

function resizeAll()
{
   var textarea=document.querySelectorAll('textarea');
   for(var i=textarea.length-1; i>=0; i--)
      resize(textarea[i]);
}

function resize(textarea)
{
   var div = document.createElement("div");
   div.setAttribute("class","textarea");
   div.innerText=textarea.value+"\r\n";
   div.setAttribute("style","width:"+textarea.offsetWidth+'px;display:block;height:auto;left:0px;top:0px;position:fixed;z-index:-200;visibility:hidden;word-wrap:break-word;overflow:hidden;');
   textarea.form.appendChild(div);
   var h=div.offsetHeight;
   div.parentNode.removeChild(div);
   textarea.style.height=h+'px';
}

function resizeOnInput(e)
{
   var textarea=document.querySelectorAll('textarea');
   for(var i=textarea.length-1; i>=0; i--)
      textarea[i].addEventListener("input",function(e){resize(e.target); return false;},false);
}

window.addEventListener("resize",function(){resizeAll();}, false);
window.addEventListener("load",function(){resizeAll();}, false);
resizeOnInput();

Tested on IE11, Firefox and Chrome.

This solution creates div similar to your textarea including internal text and measures height.

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

Capitalize the first letter of both words in a two word string

Alternative:

library(stringr)
a = c("capitalise this", "and this")
a
[1] "capitalise this" "and this"       
str_to_title(a)
[1] "Capitalise This" "And This"   

Host binding and Host listening

@HostListener is a decorator for the callback/event handler method, so remove the ; at the end of this line:

@HostListener('click', ['$event.target']);

Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick() method on the same line for clarity:

import {Component, HostListener, Directive} from 'angular2/core';

@Directive({selector: 'button[counting]'})
class CountClicks {
  numberOfClicks = 0;
  @HostListener('click', ['$event.target']) onClick(btn) {
    console.log("button", btn, "number of clicks:", this.numberOfClicks++);
  }
}
@Component({
  selector: 'my-app',
  template: `<button counting>Increment</button>`,
  directives: [CountClicks]
})
export class AppComponent {
  constructor() { console.clear(); }
}

Host binding can also be used to listen to global events:

To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)

@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }

Detecting endianness programmatically in a C++ program

while there is no quick and standard way to determine it, this will output it:

#include <stdio.h> 
int main()  
{ 
   unsigned int i = 1; 
   char *c = (char*)&i; 
   if (*c)     
       printf("Little endian"); 
   else
       printf("Big endian"); 
   getchar(); 
   return 0; 
} 

Vuex - Computed property "name" was assigned to but it has no setter

If you're going to v-model a computed, it needs a setter. Whatever you want it to do with the updated value (probably write it to the $store, considering that's what your getter pulls it from) you do in the setter.

If writing it back to the store happens via form submission, you don't want to v-model, you just want to set :value.

If you want to have an intermediate state, where it's saved somewhere but doesn't overwrite the source in the $store until form submission, you'll need to create such a data item.

Using Java with Microsoft Visual Studio 2012

Java Language Support extension provides basic features for the Java programming language. Current editing features include:

  • Syntax highlighting and brace matching
  • Outlining support for quickly collapsing classes and functions
  • Dropdown bars listing classes, enums, interfaces, fields, and methods within the current document

And if you wish to contribute then the project has been moved to its own GitHub repository

Using "word-wrap: break-word" within a table

You can try this:

td p {word-break:break-all;}

This, however, makes it appear like this when there's enough space, unless you add a <br> tag:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

So, I would then suggest adding <br> tags where there are newlines, if possible.

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

http://jsfiddle.net/LLyH3/3/

Also, if this doesn't solve your problem, there's a similar thread here.

Get the index of the object inside an array, matching a condition

Try this code

var x = [{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"}]
let index = x.findIndex(x => x.prop1 === 'zxvz')

Function to convert timestamp to human date in javascript

To calculate date in timestamp from the given date

//To get the timestamp date from normal date: In format - 1560105000000

//input date can be in format : "2019-06-09T18:30:00.000Z"

this.calculateDateInTimestamp = function (inputDate) {
    var date = new Date(inputDate);
    return date.getTime();
}

output : 1560018600000

Maximum call stack size exceeded error

In my case, I basically forget to get the value of input.

Wrong

let name=document.getElementById('name');
param={"name":name}

Correct

let name=document.getElementById('name').value;
param={"name":name}

How to avoid Sql Query Timeout

While I would be tempted to blame my issues - I'm getting the same error with my query, which is much, much bigger and involves a lot of loops - on the network, I think this is not the case.

Unfortunately it's not that simple. Query runs for 3+ hours before getting that error and apparently it crashes at the same time if it's just a query in SSMS and a job on SQL Server (did not look into details of that yet, so not sure if it's the same error; definitely same spot, though).

So just in case someone comes here with similar problem, this thread: https://www.sqlservercentral.com/Forums/569962/The-semaphore-timeout-period-has-expired

suggest that it may equally well be a hardware issue or actual timeout.

My loops aren't even (they depend on sales level in given month) in terms of time required for each, so good month takes about 20 mins to calculate (query looks at 4 years).

That way it's entirely possible I need to optimise my query. I would even say it's likely, as some changes I did included new tables, which are heaps... So another round of indexing my data before tearing into VM config and hardware tests.

Being aware that this is old question: I'm on SQL Server 2012 SE, SSMS is 2018 Beta and VM the SQL Server runs on has exclusive use of 132GB of RAM (30% total), 8 cores, and 2TB of SSD SAN.

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

Fastest way to determine if record exists

SELECT CASE WHEN EXISTS (SELECT TOP 1 *
                         FROM dbo.[YourTable] 
                         WHERE [YourColumn] = [YourValue]) 
            THEN CAST (1 AS BIT) 
            ELSE CAST (0 AS BIT) END

This approach returns a boolean for you.

How to find if an array contains a specific string in JavaScript/jQuery?

I don't like $.inArray(..), it's the kind of ugly, jQuery-ish solution that most sane people wouldn't tolerate. Here's a snippet which adds a simple contains(str) method to your arsenal:

$.fn.contains = function (target) {
  var result = null;
  $(this).each(function (index, item) {
    if (item === target) {
      result = item;
    }
  });
  return result ? result : false;
}

Similarly, you could wrap $.inArray in an extension:

$.fn.contains = function (target) {
  return ($.inArray(target, this) > -1);
}