Programs & Examples On #Application verifier

Microsoft Application Verifier is a runtime verification tool for unmanaged code.

Show a leading zero if a number is less than 10

Try this

function pad (str, max) {
  return str.length < max ? pad("0" + str, max) : str;
}

alert(pad("5", 2));

Example

http://jsfiddle.net/

Or

var number = 5;
var i;
if (number < 10) {
    alert("0"+number);
}

Example

http://jsfiddle.net/

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

Using the "Update project configuartion" messed up the build path of the project.

Fix: Open the "configure build path..." menu (right click on the project) and fix the Included/Excluded options for each source folder. That worked for me.

how to get program files x86 env variable?

On a 64-bit Windows system, the reading of the various environment variables and some Windows Registry keys is redirected to different sources, depending whether the process doing the reading is 32-bit or 64-bit.

The table below lists these data sources:

X = HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion
Y = HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion
Z = HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
     
READING ENVIRONMENT VARIABLES:    Source for 64-bit process               Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
                %ProgramFiles% :  X\ProgramW6432Dir                       X\ProgramFilesDir (x86)
           %ProgramFiles(x86)% :  X\ProgramFilesDir (x86)                 X\ProgramFilesDir (x86)
                %ProgramW6432% :  X\ProgramW6432Dir                       X\ProgramW6432Dir
     
          %CommonProgramFiles% :  X\CommonW6432Dir                        X\CommonFilesDir (x86)
     %CommonProgramFiles(x86)% :  X\CommonFilesDir (x86)                  X\CommonFilesDir (x86)
          %CommonProgramW6432% :  X\CommonW6432Dir                        X\CommonW6432Dir
     
                 %ProgramData% :  Z\ProgramData                           Z\ProgramData


      READING REGISTRY VALUES:    Source for 64-bit process               Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
             X\ProgramFilesDir :  X\ProgramFilesDir                       Y\ProgramFilesDir
       X\ProgramFilesDir (x86) :  X\ProgramFilesDir (x86)                 Y\ProgramFilesDir (x86)
            X\ProgramFilesPath :  X\ProgramFilesPath = %ProgramFiles%     Y\ProgramFilesPath = %ProgramFiles(x86)%
             X\ProgramW6432Dir :  X\ProgramW6432Dir                       Y\ProgramW6432Dir
     
              X\CommonFilesDir :  X\CommonFilesDir                        Y\CommonFilesDir
        X\CommonFilesDir (x86) :  X\CommonFilesDir (x86)                  Y\CommonFilesDir (x86)
              X\CommonW6432Dir :  X\CommonW6432Dir                        Y\CommonW6432Dir
     

So for example, for a 32-bit process, the source of the data for the %ProgramFiles% and %ProgramFiles(x86)% environment variables is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86).

However, for a 64-bit process, the source of the data for the %ProgramFiles% environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir ...and the source of the data for the %ProgramFiles(x86)% environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)

Most default Windows installation put a string like C:\Program Files (x86) into the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86) but this (and others) can be changed.

Whatever is entered into these Windows Registry values will be read by Windows Explorer into respective Environment Variables upon login and then copied to any child process that it subsequently spawns.

The registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesPath is especially noteworthy because most Windows installations put the string %ProgramFiles% into it, to be read by 64-bit processes. This string refers to the environment variable %ProgramFiles% which in turn, takes its data from the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir ...unless some program changes the value of this environment variable apriori.

I have written a small utility, which displays these environment variables for 64-bit and 32-bit processes. You can download it here.
The source code for VisualStudio 2017 is included and the compiled 64-bit and 32-bit binary executables are in the directories ..\x64\Release and ..\x86\Release, respectively.

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

numba

For recursive calculations which are not vectorisable, numba, which uses JIT-compilation and works with lower level objects, often yields large performance improvements. You need only define a regular for loop and use the decorator @njit or (for older versions) @jit(nopython=True):

For a reasonable size dataframe, this gives a ~30x performance improvement versus a regular for loop:

from numba import jit

@jit(nopython=True)
def calculator_nb(a, b, d):
    res = np.empty(d.shape)
    res[0] = d[0]
    for i in range(1, res.shape[0]):
        res[i] = res[i-1] * a[i] + b[i]
    return res

df['C'] = calculator_nb(*df[list('ABD')].values.T)

n = 10**5
df = pd.concat([df]*n, ignore_index=True)

# benchmarking on Python 3.6.0, Pandas 0.19.2, NumPy 1.11.3, Numba 0.30.1
# calculator() is same as calculator_nb() but without @jit decorator
%timeit calculator_nb(*df[list('ABD')].values.T)  # 14.1 ms per loop
%timeit calculator(*df[list('ABD')].values.T)     # 444 ms per loop

How to set the height and the width of a textfield in Java?

What type of LayoutManager are you using for the panel you're adding the JTextField to?

Different layout managers approach sizing elements on them in different ways, some respect SetPreferredSize(), while others will scale the compoenents to fit their container.

See: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

ps. this has nothing to do with eclipse, its java.

What is the difference between \r and \n?

In short \r has ASCII value 13 (CR) and \n has ASCII value 10 (LF). Mac uses CR as line delimiter (at least, it did before, I am not sure for modern macs), *nix uses LF and Windows uses both (CRLF).

Sum columns with null values in oracle

Without group by SUM(NVL(regular, 0) + NVL(overtime, 0)) will thrown an error and to avoid this we can simply use NVL(regular, 0) + NVL(overtime, 0)

Jquery open popup on button click for bootstrap

Give an ID to uniquely identify the button, lets say myBtn

// when DOM is ready
$(document).ready(function () {

     // Attach Button click event listener 
    $("#myBtn").click(function(){

         // show Modal
         $('#myModal').modal('show');
    });
});

JSFIDDLE

Sending JSON object to Web API

I believe you need quotes around the model:

JSON.stringify({ "model": source })

Execute a batch file on a remote PC using a batch file on local PC

Use microsoft's tool for remote commands executions: PsExec

If there isn't your bat-file on remote host, copy it first. For example:

copy D:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat \\RemoteServerNameOrIP\d$\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\

And then execute:

psexec \\RemoteServerNameOrIP d:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat

Note: filepath for psexec is path to file on remote server, not your local.

Detecting TCP Client Disconnect

In TCP there is only one way to detect an orderly disconnect, and that is by getting zero as a return value from read()/recv()/recvXXX() when reading.

There is also only one reliable way to detect a broken connection: by writing to it. After enough writes to a broken connection, TCP will have done enough retries and timeouts to know that it's broken and will eventually cause write()/send()/sendXXX() to return -1 with an errno/WSAGetLastError() value of ECONNRESET, or in some cases 'connection timed out'. Note that the latter is different from 'connect timeout', which can occur in the connect phase.

You should also set a reasonable read timeout, and drop connections that fail it.

The answer here about ioctl() and FIONREAD is compete nonsense. All that does is tell you how many bytes are presently in the socket receive buffer, available to be read without blocking. If a client doesn't send you anything for five minutes that doesn't constitute a disconnect, but it does cause FIONREAD to be zero. Not the same thing: not even close.

Open a new tab in the background?

THX for this question! Works good for me on all popular browsers:

function openNewBackgroundTab(){
    var a = document.createElement("a");
    a.href = window.location.pathname;
    var evt = document.createEvent("MouseEvents");
    //the tenth parameter of initMouseEvent sets ctrl key
    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                                true, false, false, false, 0, null);
    a.dispatchEvent(evt);
}

var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(!is_chrome)
{
    var url = window.location.pathname;
    var win = window.open(url, '_blank');
} else {
    openNewBackgroundTab();
}

Java: Convert String to TimeStamp

I'm sure the solution is that your oldDateString is something like "2009-10-20". Obviously this does not contain any time data lower than days. If you format this string with your new formatter where should it get the minutes, seconds and milliseconds from?

So the result is absolutely correct: 2009-10-20 00:00:00.000

What you'll need to solve this, is the original timestamp (incl. time data) before your first formatting.

Does a finally block always get executed in Java?

The finally block is always executed unless there is abnormal program termination, either resulting from a JVM crash or from a call to System.exit(0).

On top of that, any value returned from within the finally block will override the value returned prior to execution of the finally block, so be careful of checking all exit points when using try finally.

How to hide "Showing 1 of N Entries" with the dataTables.js library

If you also need to disable the drop-down (not to hide the text) then set the lengthChange option to false

$('#datatable').dataTable( {
  "lengthChange": false
} );

Works for DataTables 1.10+

Read more in the official documentation

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

This generally raises when the client sends a burst of requests to the server, next to a client side event.

This is generally a sign of "bad" programming in client side.

Imagine I am updating all lines of a table.

The bad way is to send a request to update each row (many requests in rafale without waiting for request complete). To correct it , be sure, the request is complete, before sending another one.

The good way would be to send a request with all updated rows. (one request)

So, at first, look at what is happening client side and refactoring code if necessary.

Use wireshark to identify what goes wrong in requests.

Can I have multiple Xcode versions installed?

Whatever advice path you go down, make a copy of your project folder, and rename the external most one to reflect what XCode version it is being opened in. Your choice on whether you want it to update syntax or not, but the main reason for all this bovver is your storyboard will be altered just by looking. It may be resolved by the time a new reader coming across this in the future, or

Sort Dictionary by keys

"sorted" in iOS 9 & xcode 7.3, swift 2.2 is impossible, change "sorted" to "sort", like this:

let dictionary = ["main course": 10.99, "dessert": 2.99, "salad": 5.99]
let sortedKeysAndValues = Array(dictionary).sort({ $0.0 < $1.0 })
print(sortedKeysAndValues)

//sortedKeysAndValues = ["desert": 2.99, "main course": 10.99, "salad": 5.99]

Find the last time table was updated

SELECT so.name,so.modify_date

FROM sys.objects as so

INNER JOIN INFORMATION_SCHEMA.TABLES as ist

ON ist.TABLE_NAME=so.name where ist.TABLE_TYPE='BASE TABLE' AND 

TABLE_CATALOG='DbName' order by so.modify_date desc;

this is help to get table modify with table name

Tesseract OCR simple example

I had same problem, now its resolved. I have tesseract2, under this folders for 32 bit and 64 bit, I copied files 64 bit folder(as my system is 64 bit) to main folder ("Tesseract2") and under bin/Debug folder. Now my solution is working fine.

What is the difference between Document style and RPC style communication?

The main scenario where JAX-WS RPC and Document style are used as follows:

  • The Remote Procedure Call (RPC) pattern is used when the consumer views the web service as a single logical application or component with encapsulated data. The request and response messages map directly to the input and output parameters of the procedure call.

    Examples of this type the RPC pattern might include a payment service or a stock quote service.

  • The document-based pattern is used in situations where the consumer views the web service as a longer running business process where the request document represents a complete unit of information. This type of web service may involve human interaction for example as with a credit application request document with a response document containing bids from lending institutions. Because longer running business processes may not be able to return the requested document immediately, the document-based pattern is more commonly found in asynchronous communication architectures. The Document/literal variation of SOAP is used to implement the document-based web service pattern.

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Instead of adding EntityFramework.SqlServer to host project you can ensure a static reference to it from your Model/entity project like this

static MyContext()
{
    var type = typeof(System.Data.Entity.SqlServer.SqlProviderServices);
    if(type == null)
        throw new Exception("Do not remove, ensures static reference to System.Data.Entity.SqlServer");
}

This will make the build process include the assembly with the host project.

More info on my blog http://andersmalmgren.com/2014/08/20/implicit-dependencies-and-copy-local-fails-to-copy/

How to get an IFrame to be responsive in iOS Safari?

I needed a cross-browser solution. Requirements were:

  • needed to work on both iOS and elsewhere
  • don't have access to the content in the iFrame
  • need it to scroll!

Building off what I learned from @Idra regarding scrolling="no" on iOS and this post about fitting iFrame content to the screen in iOS here's what I ended up with. Hope it helps someone =)

HTML

<div id="url-wrapper"></div>

CSS

html, body{
    height: 100%;
}

#url-wrapper{
    margin-top: 51px;
    height: 100%;
}

#url-wrapper iframe{
    height: 100%;
    width: 100%;
}

#url-wrapper.ios{
    overflow-y: auto;
    -webkit-overflow-scrolling:touch !important;
    height: 100%;
}

#url-wrapper.ios iframe{
    height: 100%;
    min-width: 100%;
    width: 100px;
    *width: 100%;
}

JS

function create_iframe(url){

    var wrapper = jQuery('#url-wrapper');

    if(navigator.userAgent.match(/(iPod|iPhone|iPad)/)){
        wrapper.addClass('ios');
        var scrolling = 'no';
    }else{
        var scrolling = 'yes';
    }

    jQuery('<iframe>', {
        src: url,
        id:  'url',
        frameborder: 0,
        scrolling: scrolling
    }).appendTo(wrapper);

}

Cross domain POST request is not sending cookie Ajax Jquery

You cannot set or read cookies on CORS requests through JavaScript. Although CORS allows cross-origin requests, the cookies are still subject to the browser's same-origin policy, which means only pages from the same origin can read/write the cookie. withCredentials only means that any cookies set by the remote host are sent to that remote host. You will have to set the cookie from the remote server by using the Set-Cookie header.

How to open warning/information/error dialog in Swing?

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ErrorDialog {

  public static void main(String argv[]) {
    String message = "\"The Comedy of Errors\"\n"
        + "is considered by many scholars to be\n"
        + "the first play Shakespeare wrote";
    JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",
        JOptionPane.ERROR_MESSAGE);
  }
}

How to check if a process is running via a batch script

I don't know how to do so with built in CMD but if you have grep you can try the following:

tasklist /FI "IMAGENAME eq myApp.exe" | grep myApp.exe
if ERRORLEVEL 1 echo "myApp is not running"

Opening Chrome From Command Line

Have a look into the start command. It should do what you're trying to achieve.

Also, you might be able to leave out path to chrome. The following works on Windows 7:

start chrome "site1.com" "site2.com"

Equivalent of SQL ISNULL in LINQ?

Since aa is the set/object that might be null, can you check aa == null ?

(aa / xx might be interchangeable (a typo in the question); the original question talks about xx but only defines aa)

i.e.

select new {
    AssetID = x.AssetID,
    Status = aa == null ? (bool?)null : aa.Online; // a Nullable<bool>
}

or if you want the default to be false (not null):

select new {
    AssetID = x.AssetID,
    Status = aa == null ? false : aa.Online;
}

Update; in response to the downvote, I've investigated more... the fact is, this is the right approach! Here's an example on Northwind:

        using(var ctx = new DataClasses1DataContext())
        {
            ctx.Log = Console.Out;
            var qry = from boss in ctx.Employees
                      join grunt in ctx.Employees
                          on boss.EmployeeID equals grunt.ReportsTo into tree
                      from tmp in tree.DefaultIfEmpty()
                      select new
                             {
                                 ID = boss.EmployeeID,
                                 Name = tmp == null ? "" : tmp.FirstName
                        };
            foreach(var row in qry)
            {
                Console.WriteLine("{0}: {1}", row.ID, row.Name);
            }
        }

And here's the TSQL - pretty much what we want (it isn't ISNULL, but it is close enough):

SELECT [t0].[EmployeeID] AS [ID],
    (CASE
        WHEN [t2].[test] IS NULL THEN CONVERT(NVarChar(10),@p0)
        ELSE [t2].[FirstName]
     END) AS [Name]
FROM [dbo].[Employees] AS [t0]
LEFT OUTER JOIN (
    SELECT 1 AS [test], [t1].[FirstName], [t1].[ReportsTo]
    FROM [dbo].[Employees] AS [t1]
    ) AS [t2] ON ([t0].[EmployeeID]) = [t2].[ReportsTo]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

QED?

Pythonic way to return list of every nth item in a larger list

Here is a better implementation of an "every 10th item" list comprehension, that does not use the list contents as part of the membership test:

>>> l = range(165)
>>> [ item for i,item in enumerate(l) if i%10==0 ]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]
>>> l = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
>>> [ item for i,item in enumerate(l) if i%10==0 ]
['A', 'K', 'U']

But this is still far slower than just using list slicing.

Convert Difference between 2 times into Milliseconds?

Try the following:

   DateTime dtStart;
   DateTime dtEnd;

   if (DateTime.TryParse( tb1.Text, out dtStart ) && DateTime.TryParse(tb2.Text, out dtEnd ))
   {
      TimeSpan ts = dtStart - dtEnd;
      double difference = ts.TotalMilliseconds;
   }

MySQL: #126 - Incorrect key file for table

I fixed this issue with:

ALTER TABLE table ENGINE MyISAM;
ALTER IGNORE TABLE table ADD UNIQUE INDEX dupidx (field);
ALTER TABLE table ENGINE InnoDB;

May helps

typeof operator in C

It's a GNU extension. In a nutshell it's a convenient way to declare an object having the same type as another. For example:

int x;         /* Plain old int variable. */
typeof(x) y;   /* Same type as x. Plain old int variable. */

It works entirely at compile-time and it's primarily used in macros. One famous example of macro relying on typeof is container_of.

How to open .dll files to see what is written inside?

*.dll files are archive files open with winzip/7zip etc. That isnt to say that all .dll files are archives you can save anything with the .dll extension however most windows .dll files are generated to be archives examples of this are windows>twain_32.dll which is an archive file however twain.dll is not if you look at twain.dll you will see an MZŽ as the first three notepad characters which denotes a Compiled C file/program or part of a program. Whereas MZ seems to be an archive.

Also most .exe files are archives mostly containing an icon image etc for the file and the windows installer packages as well they contain all the information the program needs to run images,movies etc and also directories including installation information and plain text file.

I have a game here game.exe and it contains java class files an image a pointer directing the .exe to run a .bat file. Obviously your .bat file will run a javac call from the archive and run the game there is also a few .dll archives containing java class files also.

[autorun]
ICON=AUTORUN\MINCRAFTLOGO.ICO

standard icon redirect here .ico is an image file within a .dll file within a .exe file. So the image seen on the .exe file is the minecraft logo. This is in a file called autorun.inf. Second example

[discstarter]
    startpage=Autostart\Disk1.html
    uselanguagestartpage=1
    windowcaption=Solid Edge
    licensee=Siemens PLM Software
    productguid=05B227DF-DB00-4934-B3C8-40B7D8FAA54A
    singleinstance=1
    hidesplashscreen=1
    noscrollbars=0
    showstatusbar=1
    splashscreentime=0
    windowwidth=750
    windowheight=775
    buttondir=Autostart
    toolbarcolor=16777215
    toolbar=goback,goforward,gohome,print,exit
    [autorun]
    open=autostart.exe
    icon=Autostart\ENGINE.ICO

This is the solid edge autorun.inf file contained in solidedge.exe Autostart\ is the Autostart.dll directory. open=autostart.exe specifies the autostart.exe file to run from within the original solidedge.exe archive. Here is a sample program using the .dll (dynamic link library) files http://www.flipcode.com/archives/Creating_And_Using_DLLs.shtml.

It also shows how they are created. As you can see the contents of the dll file is called by an exe file as I previously explained also there is a tutorial here http://msdn.microsoft.com/en-us/library/ms235636.aspx and as i said before 7zip or winzip will open a dynamic link library as an archive as long as you have the .dll file. If the contents of the dynamic link library have been compiled obviously you need a program which can read the file.

However since .dll files are by definition just archive library files the dll itself should be readable and not a compiled C,C# file etc etc Basically .dll files are archives well should be when a .dll file is created in visual studio the dll is created and any information you store in the dll file is encrypted. Mostly this encryption is handled by visual studio itself and generally isn't edited by hand. When you read a .dll file contents as a .exe the contents are automatically decrypted. Now when we talk about compiling a program we are changing the contents into bytecode the machine easily interprets.

This filesize would be smaller than the original file of the same contents. However the filesize is larger suggesting that the file has actually been encrypted. Probably to stop people reading their code. As a result the reading of .dll contents is termed decryption and not decompilation. Decompilation would convert the already compiled txt files to unreadable byte code. The use of standard .dll files is by definition not opensource because it involves the deliberate obfuscation of byte code.

Daemon Threads Explanation

Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These are only useful when the main program is running, and it's okay to kill them off once the other, non-daemon, threads have exited.

Without daemon threads, you'd have to keep track of them, and tell them to exit, before your program can completely quit. By setting them as daemon threads, you can let them run and forget about them, and when your program quits, any daemon threads are killed automatically.

How do I compile the asm generated by GCC?

If you have main.s file. you can generate object file by GCC and also as

# gcc -c main.s
# as main.s -o main.o

check this link, it will help you learn some binutils of GCC http://www.thegeekstuff.com/2017/01/gnu-binutils-commands/

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

After spending lot of time on internet. I found that NONE of the option worked for I tried Right click on the server -> Clean. didn't work.

What worked is:

You just to add<absolute-ordering/> tag to your web.xml just under the <display-name> tag and it should work.for more detail click here

Laravel 5.2 - pluck() method returns array

laravel pluck returns an array

if your query is:

 $name = DB::table('users')->where('name', 'John')->pluck('name');

then the array is like this (key is the index of the item. auto incremented value):

[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

but if you do like this:

$name = DB::table('users')->where('name', 'John')->pluck('name','id');

then the key is actual index in the database.

key||value
[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

you can set any value as key.

Error "package android.support.v7.app does not exist"

Your project is missing the support library from the SDK.

If you have no installed them, just right click on the project > Android Tools > Install support library.

Then, just import into workspace, as an Android project, android-support-v7-appcompat, located into ${android-sdk-path}/extras/android/support/v7

And finally, right click in the Android project > Properties > Android Tab. Push the Add button and add the support project "android-support-v7-appcompat" as dependency.

Clean your project and the must compile and work properly.

Uninstalling Android ADT

I had the issue where after updating the SDK it would only update to version 20 and kept telling me that ANDROID 4.1 (API16) was available and only part of ANDROID 4.2 (API17) was available and there was no update to version 21.

After restarting several times and digging I found (was not obvious to me) going to the SDK Manager and going to FILE -> RELOAD solved the problem. Immediately the other uninstalled parts of API17 were there and I was able to update the SDK. Once updated to 4.2 then I could re-update to version 21 and voila.

Good luck! David

JavaScript, getting value of a td with id name

To get the text content

document.getElementById ( "tdid" ).innerText

or

document.getElementById ( "tdid" ).textContent

var tdElem = document.getElementById ( "tdid" );
var tdText = tdElem.innerText | tdElem.textContent;

If you can use jQuery then you can use

$("#tdid").text();

To get the HTML content

var tdElem = document.getElementById ( "tdid" );
var tdText = tdElem.innerHTML;

in jQuery

$("#tdid").html();

How to replace part of string by position?

string myString = "ABCDEFGHIJ";
string modifiedString = new StringBuilder(myString){[3]='Z', [4]='X'}.ToString();

Let me explain my solution.
Given the problem statement of altering a string in its two specific position (“position 4 to position 5”) with two character ‘Z’ and ‘X’ and the ask is to use the position index to alter the string and not string Replace() method(may be because of the possibility of repetition of some characters in the actual string), I would prefer to use minimalist approach to achieve the goal over using Substring() and string Concat() or string Remove() and Insert() approach. Though all those solutions will serve the purpose in attaining the same goal, but it just depends on personal choice and philosophy of settling with minimalist approach.
Coming back to my solution mention above, if we take a closer look of string and StringBuilder, both of them internally treats a given string as an array of characters. If we look at the implementation of StringBuilder it maintains an internal variable something like “internal char[] m_ChunkChars;” to capture the given string. Now since this is an internal variable, we cannot directly access the same. For external world, to be able to access and alter that character array, StringBuilder exposes them through indexer property which looks something like below

    [IndexerName("Chars")]
    public char this[int index]
    {
      get
      {
        StringBuilder stringBuilder = this;
        do
        {
          // … some code
            return stringBuilder.m_ChunkChars[index1];
          // … some more code
        }
      }
      set
      {
        StringBuilder stringBuilder = this;
        do
        {
            //… some code
            stringBuilder.m_ChunkChars[index1] = value;
            return;
            // …. Some more code
        }
      }
    }

My solution mentioned above leverage this indexer capability to directly alter the internally maintained character array which IMO is efficient and minimalist.

BTW; we can rewrite the above solution more elaborately something like below

 string myString = "ABCDEFGHIJ";
 StringBuilder tempString = new StringBuilder(myString);
 tempString[3] = 'Z';
 tempString[4] = 'X';
 string modifiedString = tempString.ToString();

In this context also would like to mention that in case of string it also have indexer property as a means to expose its internal character array, but in this case it only has Getter property (and no Setter) as string is immutable in nature. And that is why we need to use StringBuilder to alter the character array.

[IndexerName("Chars")]
public extern char this[int index] { [SecuritySafeCritical, __DynamicallyInvokable, MethodImpl(MethodImplOptions.InternalCall)] get; }

And last but not the least this solution is only best fit for this specific problem where the ask is to replace only few characters with a known position index upfront. It may not be the best fit when the requirement is to alter a fairly lengthy string i.e. number of characters to alter are large in numbers.

How can I control the speed that bootstrap carousel slides in items?

In your main.js file or bootstrap.js, change the value of autoplayTimeout

_x000D_
_x000D_
    $('.carousel').each(function () {
        $(this).owlCarousel({
            nav: $(this).data('nav'),
            dots: $(this).data('dots'),
            loop: $(this).data('loop'),
            margin: $(this).data('space'),
            center: $(this).data('center'),
            dotsSpeed: $(this).data('speed'),
            autoplay: $(this).data('autoplay'),
            transitionStyle: $(this).data('transition'),
            animateOut: $(this).data('animate-out'),
            animateIn: $(this).data('animate-in'),
            autoplayTimeout: 3000,
            responsive: {
                0: {
                    items: 1,
                },
                400: {
                    items: $(this).data('slide-sm'),
                },
                700: {
                    items: $(this).data('slide-md'),
                },
                1000: {
                    items: $(this).data('slide'),
                }
            }
        });
    });
_x000D_
_x000D_
_x000D_

How do you detect/avoid Memory leaks in your (Unmanaged) code?

If your C/C++ code is portable to *nix, few things are better than Valgrind.

How to read the output from git diff?

@@ -1,2 +3,4 @@ part of the diff

This part took me a while to understand, so I've created a minimal example.

The format is basically the same the diff -u unified diff.

For instance:

diff -u <(seq 16) <(seq 16 | grep -Ev '^(2|3|14|15)$')

Here we removed lines 2, 3, 14 and 15. Output:

@@ -1,6 +1,4 @@
 1
-2
-3
 4
 5
 6
@@ -11,6 +9,4 @@
 11
 12
 13
-14
-15
 16

@@ -1,6 +1,4 @@ means:

  • -1,6 means that this piece of the first file starts at line 1 and shows a total of 6 lines. Therefore it shows lines 1 to 6.

    1
    2
    3
    4
    5
    6
    

    - means "old", as we usually invoke it as diff -u old new.

  • +1,4 means that this piece of the second file starts at line 1 and shows a total of 4 lines. Therefore it shows lines 1 to 4.

    + means "new".

    We only have 4 lines instead of 6 because 2 lines were removed! The new hunk is just:

    1
    4
    5
    6
    

@@ -11,6 +9,4 @@ for the second hunk is analogous:

  • on the old file, we have 6 lines, starting at line 11 of the old file:

    11
    12
    13
    14
    15
    16
    
  • on the new file, we have 4 lines, starting at line 9 of the new file:

    11
    12
    13
    16
    

    Note that line 11 is the 9th line of the new file because we have already removed 2 lines on the previous hunk: 2 and 3.

Hunk header

Depending on your git version and configuration, you can also get a code line next to the @@ line, e.g. the func1() { in:

@@ -4,7 +4,6 @@ func1() {

This can also be obtained with the -p flag of plain diff.

Example: old file:

func1() {
    1;
    2;
    3;
    4;
    5;
    6;
    7;
    8;
    9;
}

If we remove line 6, the diff shows:

@@ -4,7 +4,6 @@ func1() {
     3;
     4;
     5;
-    6;
     7;
     8;
     9;

Note that this is not the correct line for func1: it skipped lines 1 and 2.

This awesome feature often tells exactly to which function or class each hunk belongs, which is very useful to interpret the diff.

How the algorithm to choose the header works exactly is discussed at: Where does the excerpt in the git diff hunk header come from?

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

When I'm converting from JSX to TSX and we keep some libraries as js/jsx and convert others to ts/tsx I almost always forget to change the js/jsx import statements in the TSX\TS files from

import * as ComponentName from "ComponentName";

to

import ComponentName from "ComponentName";

If calling an old JSX (React.createClass) style component from TSX, then use

var ComponentName = require("ComponentName")

node.js - how to write an array to file

If it's a huuge array and it would take too much memory to serialize it to a string before writing, you can use streams:

var fs = require('fs');

var file = fs.createWriteStream('array.txt');
file.on('error', function(err) { /* error handling */ });
arr.forEach(function(v) { file.write(v.join(', ') + '\n'); });
file.end();

How to extract the nth word and count word occurrences in a MySQL string?

My home-grown regular expression replace function can be used for this.

Demo

See this DB-Fiddle demo, which returns the second word ("I") from a famous sonnet and the number of occurrences of it (1).

SQL

Assuming MySQL 8 or later is being used (to allow use of a Common Table Expression), the following will return the second word and the number of occurrences of it:

WITH cte AS (
     SELECT digits.idx,
            SUBSTRING_INDEX(SUBSTRING_INDEX(words, '~', digits.idx + 1), '~', -1) word
     FROM
     (SELECT reg_replace(UPPER(txt),
                         '[^''’a-zA-Z-]+',
                         '~',
                         TRUE,
                         1,
                         0) AS words
      FROM tbl) delimited
     INNER JOIN
     (SELECT @row := @row + 1 as idx FROM 
      (SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) t1,
      (SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) t2, 
      (SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) t3, 
      (SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) t4, 
      (SELECT @row := -1) t5) digits
     ON LENGTH(REPLACE(words, '~' , '')) <= LENGTH(words) - digits.idx)
SELECT c.word,
       subq.occurrences
FROM cte c
LEFT JOIN (
  SELECT word,
         COUNT(*) AS occurrences
  FROM cte
  GROUP BY word
) subq
ON c.word = subq.word
WHERE idx = 1; /* idx is zero-based so 1 here gets the second word */

Explanation

A few tricks are used in the SQL above and some accreditation is needed. Firstly the regular expression replacer is used to replace all continuous blocks of non-word characters - each being replaced by a single tilda (~) character. Note: A different character could be chosen instead if there is any possibility of a tilda appearing in the text.

The technique from this answer is then used for transforming a string with delimited values into separate row values. It's combined with the clever technique from this answer for generating a table consisting of a sequence of incrementing numbers: 0 - 10,000 in this case.

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

Old skool:

string oldText = "   1 2  3   4    5     ";
string newText = oldText
                    .Replace("  ", " " + (char)22 )
                    .Replace( (char)22 + " ", "" )
                    .Replace( (char)22 + "", "" );

Assert.That( newText, Is.EqualTo( " 1 2 3 4 5 " ) );

How to run a command in the background and get no output?

If they are in the same directory as your script that contains:

./a.sh > /dev/null 2>&1 &
./b.sh > /dev/null 2>&1 &

The & at the end is what makes your script run in the background.

The > /dev/null 2>&1 part is not necessary - it redirects the stdout and stderr streams so you don't have to see them on the terminal, which you may want to do for noisy scripts with lots of output.

How to run a Powershell script from the command line and pass a directory as a parameter

Using the flag -Command you can execute your entire powershell line as if it was a command in the PowerShell prompt:

powershell -Command "& '<PATH_TO_PS1_FILE>' '<ARG_1>' '<ARG_2>' ... '<ARG_N>'"

This solved my issue with running PowerShell commands in Visual Studio Post-Build and Pre-Build events.

How can I remove a button or make it invisible in Android?

View controls (TextView, EditText, Button, Image, etc) all have a visibility property. This can be set to one of three values:

Visible - Displayed

android:visibility="visible"

Invisible - Hidden but space reserved

android:visibility="invisible"

Gone - Hidden completely

android:visibility="gone"

To set the visibility in code use the public constant available in the static View class:

Button button1 = (TextView)findViewById(R.id.button1);
button1.setVisibility(View.VISIBILE);

Can you get the column names from a SqlDataReader?

If you want the column names only, you can do:

List<string> columns = new List<string>();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
{
    DataTable dt = reader.GetSchemaTable();
    foreach (DataRow row in dt.Rows)
    {
        columns.Add(row.Field<String>("ColumnName"));
    }
}

But if you only need one row, I like my AdoHelper addition. This addition is great if you have a single line query and you don't want to deal with data table in you code. It's returning a case insensitive dictionary of column names and values.

public static Dictionary<string, string> ExecuteCaseInsensitiveDictionary(string query, string connectionString, Dictionary<string, string> queryParams = null)
{
    Dictionary<string, string> CaseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    try
    {
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = query;

                // Add the parameters for the SelectCommand.
                if (queryParams != null)
                    foreach (var param in queryParams)
                        cmd.Parameters.AddWithValue(param.Key, param.Value);

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    DataTable dt = new DataTable();
                    dt.Load(reader);
                    foreach (DataRow row in dt.Rows)
                    {
                        foreach (DataColumn column in dt.Columns)
                        {
                            CaseInsensitiveDictionary.Add(column.ColumnName, row[column].ToString());
                        }
                    }
                }
            }
            conn.Close();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return CaseInsensitiveDictionary;
}

How do I get extra data from intent on Android?

You can get any type of extra data from intent, no matter if it's an object or string or any type of data.

Bundle extra = getIntent().getExtras();

if (extra != null){
    String str1 = (String) extra.get("obj"); // get a object

    String str2 =  extra.getString("string"); //get a string
}

and the Shortest solution is:

Boolean isGranted = getIntent().getBooleanExtra("tag", false);

angularjs getting previous route path

@andresh For me locationChangeSuccess worked instead of routeChangeSuccess.

//Go back to the previous stage with this back() call
var history = [];
$rootScope.$on('$locationChangeSuccess', function() {
    history.push($location.$$path);
});

$rootScope.back = function () {
          var prevUrl = history.length > 1 ? history.splice(-2)[0] : "/";
          $location.path(prevUrl);
          history = []; //Delete history array after going back
      };

Testing two JSON objects for equality ignoring child order in Java

One thing I did and it works wonders is to read both objects into HashMap and then compare with a regular assertEquals(). It will call the equals() method of the hashmaps, which will recursively compare all objects inside (they will be either other hashmaps or some single value object like a string or integer). This was done using Codehaus' Jackson JSON parser.

assertEquals(mapper.readValue(expectedJson, new TypeReference<HashMap<String, Object>>(){}), mapper.readValue(actualJson, new TypeReference<HashMap<String, Object>>(){}));

A similar approach can be used if the JSON object is an array instead.

String literals and escape characters in postgresql

Cool.

I also found the documentation regarding the E:

http://www.postgresql.org/docs/8.3/interactive/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS

PostgreSQL also accepts "escape" string constants, which are an extension to the SQL standard. An escape string constant is specified by writing the letter E (upper or lower case) just before the opening single quote, e.g. E'foo'. (When continuing an escape string constant across lines, write E only before the first opening quote.) Within an escape string, a backslash character (\) begins a C-like backslash escape sequence, in which the combination of backslash and following character(s) represents a special byte value. \b is a backspace, \f is a form feed, \n is a newline, \r is a carriage return, \t is a tab. Also supported are \digits, where digits represents an octal byte value, and \xhexdigits, where hexdigits represents a hexadecimal byte value. (It is your responsibility that the byte sequences you create are valid characters in the server character set encoding.) Any other character following a backslash is taken literally. Thus, to include a backslash character, write two backslashes (\\). Also, a single quote can be included in an escape string by writing \', in addition to the normal way of ''.

Composer - the requested PHP extension mbstring is missing from your system

  1. find your php.ini
  2. make sure the directive extension_dir=C:\path\to\server\php\ext is set and adjust the path (set your PHP extension dir)
  3. make sure the directive extension=php_mbstring.dll is set (uncommented)

If this doesn't work and the php_mbstring.dll file is missing, then the PHP installation of this stack is simply broken.

How to generate access token using refresh token through google drive API?

Using ASP.Net Post call, this worked for me.

StringBuilder getNewToken = new StringBuilder();
getNewToken.Append("https://www.googleapis.com/oauth2/v4/token");                        
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(getNewToken.ToString());
                    var values = new Dictionary<string, string>
                    {
                        { "client_id", <Your Client Id> },
                        { "client_secret", <Your Client Secret> },
                        { "refresh_token", <Your Saved Refresh Token> },
                        { "grant_type", "refresh_token"}
                    };

                    var content = new FormUrlEncodedContent(values);
                    var response = await client.PostAsync(getNewToken.ToString(), content);

Best way to script remote SSH commands in Batch (Windows)

The -m switch of PuTTY takes a path to a script file as an argument, not a command.

Reference: https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-m

So you have to save your command (command_run) to a plain text file (e.g. c:\path\command.txt) and pass that to PuTTY:

putty.exe -ssh user@host -pw password -m c:\path\command.txt

Though note that you should use Plink (a command-line connection tool from PuTTY suite). It's a console application, so you can redirect its output to a file (what you cannot do with PuTTY).

A command-line syntax is identical, an output redirection added:

plink.exe -ssh user@host -pw password -m c:\path\command.txt > output.txt

See Using the command-line connection tool Plink.

And with Plink, you can actually provide the command directly on its command-line:

plink.exe -ssh user@host -pw password command > output.txt

Similar questions:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file

How to base64 encode image in linux bash / shell

If you need input from termial, try this

lc=`echo -n "xxx_${yyy}_iOS" |  base64`

-n option will not input "\n" character to base64 command.

Best way to get user GPS location in background in Android

Well Create a class extending Service ,this service will contain your Location listener class(Fused Location Provider) purpose of this service is to get location periodically , something like this

  public class LocationGetter extends Service {


    ......

    public class MyLocationListener implements GooglePlayServicesClient.ConnectionCallbacks,GooglePlayServicesClient.OnConnectionFailedListener,LocationListener, com.google.android.gms.location.LocationListener {

   //your fused Location provider code

    }

    ......

}

Then create a class extending Broadcast Receiver , such that the purpose of this broadcast Receiver is to check whether service is alive if not restart service even during phone ON/OFF ....

register receiver in ur activity , listen for broadcasts , unregeister receiver depending ur need...

How to place div side by side

There are many ways to do what you're asking for:

  1. Using CSS float property:

_x000D_
_x000D_
 <div style="width: 100%; overflow: hidden;">
     <div style="width: 600px; float: left;"> Left </div>
     <div style="margin-left: 620px;"> Right </div>
</div>
_x000D_
_x000D_
_x000D_

  1. Using CSS display property - which can be used to make divs act like a table:

_x000D_
_x000D_
<div style="width: 100%; display: table;">
    <div style="display: table-row">
        <div style="width: 600px; display: table-cell;"> Left </div>
        <div style="display: table-cell;"> Right </div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

There are more methods, but those two are the most popular.

how to delete a specific row in codeigniter?

**multiple delete not working**

function delete_selection() 
{
        $id_array = array();
        $selection = $this->input->post("selection", TRUE);
        $id_array = explode("|", $selection);

        foreach ($id_array as $item):
            if ($item != ''):
                //DELETE ROW
                $this->db->where('entry_id', $item);
                $this->db->delete('helpline_entry');
            endif;
        endforeach;
    }

Uses of Action delegate in C#

For an example of how Action<> is used.

Console.WriteLine has a signature that satisifies Action<string>.

    static void Main(string[] args)
    {
        string[] words = "This is as easy as it looks".Split(' ');

        // Passing WriteLine as the action
        Array.ForEach(words, Console.WriteLine);         
    }

Hope this helps

jQuery-- Populate select from json

That work fine in Ajax call back to update select from JSON object

function UpdateList() {
    var lsUrl = '@Url.Action("Action", "Controller")';

    $.get(lsUrl, function (opdata) {

        $.each(opdata, function (key, value) {
            $('#myselect').append('<option value=' + key + '>' + value + '</option>');
        });
    });
}

$(form).ajaxSubmit is not a function

Try ajaxsubmit library. It does ajax submition as well as validation via ajax.

Also configuration is very flexible to support any kind of UI.

Live demo available with js, css and html examples.

ERROR: Sonar server 'http://localhost:9000' can not be reached

For others who ran into this issue in a project that is not using a sonar-runners.property file, you may find (as I did) that you need to tweak your pom.xml file, adding a sonar.host.url property.

For example, I needed to add the following line under the 'properties' element:

<sonar.host.url>https://sonar.my-internal-company-domain.net</sonar.host.url>

Where the url points to our internal sonar deployment.

How to set column header text for specific column in Datagridview C#

grid.Columns[0].HeaderText

or

grid.Columns["columnname"].HeaderText

Attempt to write a readonly database - Django w/ SELinux error

You can change the owner of your database file and it's folder to django:

chown django:django /home/django/mysite
chown django:django /home/django/mysite/my_db.sqlite3

This work for DigitalOcean's 1-Click Django Droplet

How do I see all foreign keys to a table or column?

I'm reluctant to add yet another answer, but I've had to beg, borrow and steal from the others to get what I want, which is a complete list of all the FK relationships on tables in a given schema, INCLUDING FKs to tables in other schemas. The two crucial recordsets are information_schema.KEY_COLUMN_USAGE and information_schema.referential_constraints. If an attribute you want is missing, just uncomment the KCU., RC. to see what's available

SELECT DISTINCT KCU.TABLE_NAME, KCU.COLUMN_NAME, REFERENCED_TABLE_SCHEMA, KCU.REFERENCED_TABLE_NAME, KCU.REFERENCED_COLUMN_NAME, UPDATE_RULE, DELETE_RULE #, KCU.*, RC.*
FROM information_schema.KEY_COLUMN_USAGE KCU
INNER JOIN information_schema.referential_constraints RC ON KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
WHERE TABLE_SCHEMA = (your schema name)
AND KCU.REFERENCED_TABLE_NAME IS NOT NULL
ORDER BY KCU.TABLE_NAME, KCU.COLUMN_NAME;

File Upload to HTTP server in iphone programming

This is a great wrapper, but when posting to a asp.net web page, two additional post values need to be set:

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    //ADD THESE, BECAUSE ASP.NET is Expecting them for validation
    //Even if they are empty you will be able to post the file
    [request setPostValue:@"" forKey:@"__VIEWSTATE"];
    [request setPostValue:@"" forKey:@"__EVENTVALIDATION"]; 
    ///

    [request setFile:FIleName forKey:@"fileupload_control_Name"];
    [request startSynchronous];

How to map to multiple elements with Java 8 streams?

To do this, I had to come up with an intermediate data structure:

class KeyDataPoint {
    String key;
    DateTime timestamp;
    Number data;
    // obvious constructor and getters
}

With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.

Then, we apply a groupingBy operation on the string key in order to gather the data for each key together. Note that a simple groupingBy would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy which is a mapping operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping operation is simply toList which collects the DataPoint objects of the same group into a list.

Now we have a Map<String, List<DataPoint>> and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.

The code ends up looking like this:

Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.getData().entrySet().stream()
                           .map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
        .collect(groupingBy(KeyDataPoint::getKey,
                    mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

I took some liberties with constructors and getters, but I think they should be obvious.

No value accessor for form control with name: 'recipient'

You should add the ngDefaultControl attribute to your input like this:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)"
    ngDefaultControl>
</md-input>

Taken from comments in this post:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

Note: For later versions of @angular/material:

Nowadays you should instead write:

<md-input-container>
    <input
        mdInput
        [(ngModel)]="recipient"
        name="recipient"
        placeholder="Name"
        (blur)="addRecipient(recipient)">
</md-input-container>

See https://material.angular.io/components/input/overview

How to read a string one letter at a time in python

# Open the file
f = open('morseCode.txt', 'r')

# Read the morse code data into "letters" [(lowercased letter, morse code), ...]
letters = []
for Line in f:
    if not Line.strip(): break
    letter, code = Line.strip().split() # Assuming the format is <letter><whitespace><morse code><newline>
    letters.append((letter.lower(), code))
f.close()

# Get the input from the user
# (Don't use input() - it calls eval(raw_input())!)
i = raw_input("Enter a string to be converted to morse code or press <enter> to quit ") 

# Convert the codes to morse code
out = []
for c in i:
    found = False
    for letter, code in letters:
        if letter == c.lower():
            found = True
            out.append(code)
            break

    if not found: 
        raise Exception('invalid character: %s' % c)

# Print the output
print ' '.join(out)

React.js: How to append a component on click?

As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.

In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field

class HealthConditions extends React.Component {
  constructor(props) {
    super(props);


    this.state = {
      inputLinkClicked: false
    }
  }

  handleAddSecondInput() {
    this.setState({
      inputLinkClicked: true
    })
  }


  render() {
    return(
      <main id="wrapper" className="" data-reset-cookie-tab>
        <div id="content" role="main">
          <div className="inner-block">

            <H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>

            <InputField label="Name of condition"
              InputType="text"
              InputId="id-condition"
              InputName="condition"
            />

            {
              this.state.inputLinkClicked?

              <InputField label=""
                InputType="text"
                InputId="id-condition2"
                InputName="condition2"
              />

              :

              <div></div>
            }

            <button
              type="button"
              className="make-button-link"
              data-add-button=""
              href="#"
              onClick={this.handleAddSecondInput}
            >
              Add a condition
            </button>

            <FormButton buttonLabel="Next"
              handleSubmit={this.handleSubmit}
              linkto={
                this.state.illnessOrDisability === 'true' ?
                "/404"
                :
                "/add-your-details"
              }
            />

            <BackLink backLink="/add-your-details" />

          </div>
         </div>
      </main>
    );
  }
}

T-SQL: Export to new Excel file

This is by far the best post for exporting to excel from SQL:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

To quote from user madhivanan,

Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel

Create an Excel file named testing having the headers same as that of table columns and use these queries

1 Export data to existing EXCEL file from SQL Server table

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;', 
    'SELECT * FROM [SheetName$]') select * from SQLServerTable

2 Export data from Excel to new SQL Server table

select * 
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [Sheet1$]')

3 Export data from Excel to existing SQL Server table (edited)

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [SheetName$]')

4 If you dont want to create an EXCEL file in advance and want to export data to it, use

EXEC sp_makewebtask 
    @outputfile = 'd:\testing.xls', 
    @query = 'Select * from Database_name..SQLServerTable', 
    @colheaders =1, 
    @FixedFont=0,@lastupdated=0,@resultstitle='Testing details'

(Now you can find the file with data in tabular format)

5 To export data to new EXCEL file with heading(column names), create the following procedure

create procedure proc_generate_excel_with_columns
(
    @db_name    varchar(100),
    @table_name varchar(100),   
    @file_name  varchar(100)
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select 
    @columns=coalesce(@columns+',','')+column_name+' as '+column_name 
from 
    information_schema.columns
where 
    table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)

--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)

--Delete dummy file 
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)

After creating the procedure, execute it by supplying database name, table name and file path:

EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'

Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.

Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.

To update single cells

A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?

This is the principle of how you do manage that

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99

You can also add formulas to Excel using this:

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'

Exporting with column names using T-SQL

Member Mladen Prajdic also has a blog entry on how to do this here

References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this

Errors that may occur

If you get the following error:

OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries

Then run this:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

How to do the Recursive SELECT query in MySQL?

If you want to be able to have a SELECT without problems of the parent id having to be lower than child id, a function could be used. It supports also multiple children (as a tree should do) and the tree can have multiple heads. It also ensure to break if a loop exists in the data.

I wanted to use dynamic SQL to be able to pass the table/columns names, but functions in MySQL don't support this.

DELIMITER $$

CREATE FUNCTION `isSubElement`(pParentId INT, pId INT) RETURNS int(11)
DETERMINISTIC    
READS SQL DATA
BEGIN
DECLARE isChild,curId,curParent,lastParent int;
SET isChild = 0;
SET curId = pId;
SET curParent = -1;
SET lastParent = -2;

WHILE lastParent <> curParent AND curParent <> 0 AND curId <> -1 AND curParent <> pId AND isChild = 0 DO
    SET lastParent = curParent;
    SELECT ParentId from `test` where id=curId limit 1 into curParent;

    IF curParent = pParentId THEN
        SET isChild = 1;
    END IF;
    SET curId = curParent;
END WHILE;

RETURN isChild;
END$$

Here, the table test has to be modified to the real table name and the columns (ParentId,Id) may have to be adjusted for your real names.

Usage :

SET @wantedSubTreeId = 3;
SELECT * FROM test WHERE isSubElement(@wantedSubTreeId,id) = 1 OR ID = @wantedSubTreeId;

Result :

3   7   k
5   3   d
9   3   f
1   5   a

SQL for test creation :

CREATE TABLE IF NOT EXISTS `test` (
  `Id` int(11) NOT NULL,
  `ParentId` int(11) DEFAULT NULL,
  `Name` varchar(300) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

insert into test (id, parentid, name) values(3,7,'k');
insert into test (id, parentid, name) values(5,3,'d');
insert into test (id, parentid, name) values(9,3,'f');
insert into test (id, parentid, name) values(1,5,'a');
insert into test (id, parentid, name) values(6,2,'o');
insert into test (id, parentid, name) values(2,8,'c');

EDIT : Here is a fiddle to test it yourself. It forced me to change the delimiter using the predefined one, but it works.

Best way to store passwords in MYSQL database

First off, md5 and sha1 have been proven to be vulnerable to collision attacks and can be rainbow tabled easily (when they see if you hash is the same in their database of common passwords).

There are currently two things that are secure enough for passwords that you can use.

The first is sha512. sha512 is a sub-version of SHA2. SHA2 has not yet been proven to be vulnerable to collision attacks and sha512 will generate a 512-bit hash. Here is an example of how to use sha512:

<?php
hash('sha512',$password);

The other option is called bcrypt. bcrypt is famous for its secure hashes. It's probably the most secure one out there and most customizable one too.

Before you want to start using bcrypt you need to check if your sever has it enabled, Enter this code:

<?php
if (defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH) {
    echo "CRYPT_BLOWFISH is enabled!";
}else {
echo "CRYPT_BLOWFISH is not available";
}

If it returns that it is enabled then the next step is easy, All you need to do to bcrypt a password is (note: for more customizability you need to see this How do you use bcrypt for hashing passwords in PHP?):

crypt($password, $salt);

A salt is usually a random string that you add at the end of all your passwords when you hash them. Using a salt means if someone gets your database, they can not check the hashes for common passwords. Checking the database is called using a rainbow table. You should always use a salt when hashing!

Here are my proofs for the SHA1 and MD5 collision attack vulnerabilities:
http://www.schneier.com/blog/archives/2012/10/when_will_we_se.html, http://eprint.iacr.org/2010/413.pdf,
http://people.csail.mit.edu/yiqun/SHA1AttackProceedingVersion.pdf,
http://conf.isi.qut.edu.au/auscert/proceedings/2006/gauravaram06collision.pdf and
Understanding sha-1 collision weakness

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

You can use Replace instead of INSERT ... ON DUPLICATE KEY UPDATE.

Clear the entire history stack and start a new activity on Android

For me none of the above methods not work.

Just do this to clear all previous activity:

finishAffinity() // if you are in fragment use activity.finishAffinity()
Intent intent = new Intent(this, DestActivity.class); // with all flags you want
startActivity(intent)

How to run a program automatically as admin on Windows 7 at startup?

I think the task scheduler would be overkill (imho). There is a startup folder for win7.

C:\Users\miliu\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

Just create a shortcut for your autostart Applicaton, edit the properties of the shortcut and have it always run as administrator.

Your kids could close it of course, but if they are tech-savvy they always find a way to keep you out. I know i did when i was younger.

Good luck!

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

How can I export data to an Excel file

 private void button1_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp ;
        Excel.Workbook xlWorkBook ;
        Excel.Worksheet xlWorkSheet ;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Add(misValue);

        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";

        xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);

        MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.xls");
    }

    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }

The above code is taken directly off csharp.net please take a look on the site.

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Try using TempData:

public ActionResult Create(FormCollection collection) {
  ...
  TempData["notice"] = "Successfully registered";
  return RedirectToAction("Index");
  ...
}

Then, in your Index view, or master page, etc., you can do this:

<% if (TempData["notice"] != null) { %>
  <p><%= Html.Encode(TempData["notice"]) %></p>
<% } %>

Or, in a Razor view:

@if (TempData["notice"] != null) {
  <p>@TempData["notice"]</p>
}

Quote from MSDN (page no longer exists as of 2014, archived copy here):

An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.

How to indent a few lines in Markdown markup?

To answer MengLu and @lifebalance's questions in response to SColvin's answer (which I much prefer to the accepted answer for the control it provides), it seems as though you could just target a parent element of the lists when setting the display to none, adding a surrounding element if necessary. So if we suppose we're doing this for a table of contents, we can extend SColvin's answer:

HTML

<nav class="table-of-contents">
  this is a normal line of text
  * this is the first level of bullet points, made up of <space><space>*<space>
    * this is more indented, composed of <space><space><space><space>*<space>
</nav>

CSS

.table-of-contents ul {
  list-style-type: none;
}

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

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

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

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

How to print the data in byte array as characters?

Try this one : new String(byte[])

malloc for struct and pointer in C

First malloc allocates memory for struct, including memory for x (pointer to double). Second malloc allocates memory for double value wtich x points to.

Is it possible to run .APK/Android apps on iPad/iPhone devices?

There is another option not mentioned previously:

  • Pieceable Viewer has unfortunately stopped its service at December 31, 2012 but open-sourced its software. You need to compile your iOS application for the emulator and Pieceable's software will embed it in a webpage which hosts the application. This webpage can be used to run the iOS application. See Pieceable's for more details.

Using margin / padding to space <span> from the rest of the <p>

Add this style to your span:

position:relative; 
top: 10px;

Demo: http://jsfiddle.net/BqTUS/3/

Filter object properties by key in ES6

Another short way

_x000D_
_x000D_
function filterByKey(v,keys){
  const newObj ={};
  keys.forEach(key=>{v[key]?newObj[key]=v[key]:''});
  return newObj;
}

//given
let obj ={ foo: "bar", baz: 42,baz2:"blabla" , "spider":"man", monkey:true};

//when
let outObj =filterByKey(obj,["bar","baz2","monkey"]);

//then 
console.log(outObj);
  //{
  //  "baz2": "blabla",
  //  "monkey": true
  //}
_x000D_
_x000D_
_x000D_

Setting values of input fields with Angular 6

You should use the following:

       <td><input id="priceInput-{{orderLine.id}}" type="number" [(ngModel)]="orderLine.price"></td>

You will need to add the FormsModule to your app.module in the inputs section as follows:

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  ..

The use of the brackets around the ngModel are as follows:

  • The [] show that it is taking an input from your TS file. This input should be a public member variable. A one way binding from TS to HTML.

  • The () show that it is taking output from your HTML file to a variable in the TS file. A one way binding from HTML to TS.

  • The [()] are both (e.g. a two way binding)

See here for more information: https://angular.io/guide/template-syntax

I would also suggest replacing id="priceInput-{{orderLine.id}}" with something like this [id]="getElementId(orderLine)" where getElementId(orderLine) returns the element Id in the TS file and can be used anywere you need to reference the element (to avoid simple bugs like calling it priceInput1 in one place and priceInput-1 in another. (if you still need to access the input by it's Id somewhere else)

Iterating Over Dictionary Key Values Corresponding to List in Python

Dictionaries have a built in function called iterkeys().

Try:

for team in league.iterkeys():
    runs_scored = float(league[team][0])
    runs_allowed = float(league[team][1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print win_percentage

How to convert a set to a list in python?

It is already a list

type(my_set)
>>> <type 'list'>

Do you want something like

my_set = set([1,2,3,4])
my_list = list(my_set)
print my_list
>> [1, 2, 3, 4]

EDIT : Output of your last comment

>>> my_list = [1,2,3,4]
>>> my_set = set(my_list)
>>> my_new_list = list(my_set)
>>> print my_new_list
[1, 2, 3, 4]

I'm wondering if you did something like this :

>>> set=set()
>>> set([1,2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable

Center-align a HTML table

Try this -

<table align="center" style="margin: 0px auto;"></table>

Migration: Cannot add foreign key constraint

Chiming in here a few years after the original question, using laravel 5.1, I had the same error as my migrations were computer generated with all the same date code. I went through all the proposed solutions, then refactored to find the error source.

In following laracasts, and in reading these posts, I believe the correct answer is similar to Vickies answer, with the exception that you don't need to add a separate schema call. You don't need to set the table to Innodb, I am assuming laravel is now doing that.

The migrations simply need to be timed correctly, which means you will modify the date code up (later) in the filename for tables that you need foreign keys on. Alternatively or in addition, Lower the datecode for tables that don't need foreign keys.

The advantage in modifying the datecode is your migration code will be easier to read and maintain.

So far my code is working by adjusting the time code up to push back migrations that need foreign keys.

However I do have hundreds of tables, so at the very end I have one last table for just foreign keys. Just to get things flowing. I am assuming I will pull those into the correct file and modify the datecode as i test them.

So an example: file 2016_01_18_999999_create_product_options_table. This one needs the products table to be created. Look at the file names.

 public function up()
{
    Schema::create('product_options', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('product_attribute_id')->unsigned()->index();
        $table->integer('product_id')->unsigned()->index();
        $table->string('value', 40)->default('');
        $table->timestamps();
        //$table->foreign('product_id')->references('id')->on('products');
        $table->foreign('product_attribute_id')->references('id')->on('product_attributes');
        $table->foreign('product_id')->references('id')->on('products');


    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('product_options');
}

the products table: this needs to migrate first. 2015_01_18_000000_create_products_table

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');

        $table->string('style_number', 64)->default('');
        $table->string('title')->default('');
        $table->text('overview')->nullable();
        $table->text('description')->nullable();


        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('products');
}

And finally at the very end the file that I am temporarily using to resolve issues, which I will refactor as I write tests for the models which I named 9999_99_99_999999_create_foreign_keys.php. These keys are commented as I pulled them out, but you get the point.

    public function up()
    {
//        Schema::table('product_skus', function ($table) {
//            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
//    });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
//        Schema::table('product_skus', function ($table)
//        {
//            $table->dropForeign('product_skus_product_id_foreign');
//        });

How to localise a string inside the iOS info.plist file?

You should use InfoPlist.strings file to localize values of Info.plist. To do this, go to File->New->File, choose Strings File under Resource tab of iOS, name it InfoPlist, and create. Open and insert the Info.plist values you want to localize like:

NSLocationWhenInUseUsageDescription = "Description of this";

Now you can localize InfoPlist.strings file with translations.

Select the localization options, or enable localization if needed,

right side editor

You should be able to see the file also on the left side editor.

left side editor

Here is the official documentation for Info.plist keys localization.

Credits to Marco, thanks for including the pics in this answer!

How to loop through a collection that supports IEnumerable?

A regular for each will do:

foreach (var item in collection)
{
    // do your stuff   
}

What is EOF in the C programming language?

int c;

while((c = getchar())!= 10)
{
    if( getchar() == EOF )
        break;

     printf(" %d\n", c);
}

css transition opacity fade background

It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.

If you want to fade to black(ish), you'll need a black container around the image. Something like:

.ctr {
    margin: 0; 
    padding: 0;
    background-color: black;
    display: inline-block;
}

and

<div class="ctr"><img ... /></div>

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

how to pass parameter from @Url.Action to controller function

Try this

public ActionResult CreatePerson(string Enc)

 window.location = '@Url.Action("CreatePerson", "Person", new { Enc = "id", actionType = "Disable" })'.replace("id", id).replace("&amp;", "&");

you will get the id inside the Enc string.

HTTP Basic Authentication credentials passed in URL and encryption

Not necessarily true. It will be encrypted on the wire however it still lands in the logs plain text

How do you change the launcher logo of an app in Android Studio?

To quickly create a new set of icons and change the launcher icon in Android Studio, you can:

  1. Use this tool: https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html to upload your preferred image or icon (your source file). The tool then automatically creates a set of icons in all the different resolutions for the ic_launcher.png.

  2. Download the zip-file created by the tool, extract everything (which will create a folder structure for all the different resolutions) and then replace all the icons inside your project res folder: <AndroidStudioProjectPath>\app\src\main\res

Adding text to ImageView in Android

You can also use a TextView and set the background image to what you wanted in the ImageView. Furthermore if you were using the ImageView as a button you can set it to click-able

Here is some basic code for a TextView that shows an image with text on top of it.

<TextView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/your_image"
    android:text="your text here" />

Shell script to copy files from one location to another location and rename add the current date to every file

There is a proper way to split the filename and the extension: Extract filename and extension in Bash

You can apply it like this:

date=$(date +"%m%d%y")
for FILE in folder1/*.csv
do
    bname=$(basename "$FILE")
    extension="${bname##*.}"
    filenamewoext="${bname%.*}"
    newfilename="${filenamewoext}${date}.${extension}
    cp folder1/${FILE} folder2/${newfilename}
done

Dead simple example of using Multiprocessing Queue, Pool and Locking

Here is an example from my code (for threaded pool, but just change class name and you'll have process pool):

def execute_run(rp): 
   ... do something 

pool = ThreadPoolExecutor(6)
for mat in TESTED_MATERIAL:
    for en in TESTED_ENERGIES:
        for ecut in TESTED_E_CUT:
            rp = RunParams(
                simulations, DEST_DIR,
                PARTICLE, mat, 960, 0.125, ecut, en
            )
            pool.submit(execute_run, rp)
pool.join()

Basically:

  • pool = ThreadPoolExecutor(6) creates a pool for 6 threads
  • Then you have bunch of for's that add tasks to the pool
  • pool.submit(execute_run, rp) adds a task to pool, first arogument is a function called in in a thread/process, rest of the arguments are passed to the called function.
  • pool.join waits until all tasks are done.

How to parse a string into a nullable int

You should never use an exception if you don't have to - the overhead is horrible.

The variations on TryParse solve the problem - if you want to get creative (to make your code look more elegant) you could probably do something with an extension method in 3.5 but the code would be more or less the same.

Twitter Bootstrap and ASP.NET GridView

Add property of show header in gridview

 <asp:GridView ID="dgvUsers" runat="server" **showHeader="True"** CssClass="table table-hover table-striped" GridLines="None" 
AutoGenerateColumns="False">

and in columns add header template

<HeaderTemplate>
                   //header column names
</HeaderTemplate>

How do I view / replay a chrome network debugger har file saved with content?

There is an HAR Viewer developed by Jan Odvarko that you can use. You either use the online version at

Or download the source-code at https://github.com/janodvarko/harviewer.

EDIT: Chrome 62 DevTools include HAR import functionality. https://developers.google.com/web/updates/2017/08/devtools-release-notes#har-imports

embedding image in html email

The following is working code with two ways of achieving this:

using System;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {

            Method1();
            Method2();
        }

        public static void Method1()
        {
            Outlook.Application outlookApp = new Outlook.Application();
            Outlook.MailItem mailItem = outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
            mailItem.Subject = "This is the subject";
            mailItem.To = "[email protected]";
            string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed

            var attachments = mailItem.Attachments;
            var attachment = attachments.Add(imageSrc);
            attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x370E001F", "image/jpeg");
            attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "myident"); // Image identifier found in the HTML code right after cid. Can be anything.
            mailItem.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/id/{00062008-0000-0000-C000-000000000046}/8514000B", true);

            // Set body format to HTML

            mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
            string msgHTMLBody = "<html><head></head><body>Hello,<br><br>This is a working example of embedding an image unsing C#:<br><br><img align=\"baseline\" border=\"1\" hspace=\"0\" src=\"cid:myident\" width=\"\" 600=\"\" hold=\" /> \"></img><br><br>Regards,<br>Tarik Hoshan</body></html>";
            mailItem.HTMLBody = msgHTMLBody;
            mailItem.Send();
        }

        public static void Method2()
        {

            // Create the Outlook application.
            Outlook.Application outlookApp = new Outlook.Application();

            Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);

            //Add an attachment.
            String attachmentDisplayName = "MyAttachment";

            // Attach the file to be embedded
            string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed

            Outlook.Attachment oAttach = mailItem.Attachments.Add(imageSrc, Outlook.OlAttachmentType.olByValue, null, attachmentDisplayName);

            mailItem.Subject = "Sending an embedded image";

            string imageContentid = "someimage.jpg"; // Content ID can be anything. It is referenced in the HTML body

            oAttach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", imageContentid);

            mailItem.HTMLBody = String.Format(
                "<body>Hello,<br><br>This is an example of an embedded image:<br><br><img src=\"cid:{0}\"><br><br>Regards,<br>Tarik</body>",
                imageContentid);

            // Add recipient
            Outlook.Recipient recipient = mailItem.Recipients.Add("[email protected]");
            recipient.Resolve();

            // Send.
            mailItem.Send();
        }
    }
}

Easy way to test a URL for 404 in PHP?

If you are looking for an easiest solution and the one you can try in one go on php5 do

file_get_contents('www.yoursite.com');
//and check by echoing
echo $http_response_header[0];

How to export dataGridView data Instantly to Excel on button click?

I'm adding this answer because none of the other methods use OpenXMLWriter, despite the fact that it is faster than OpenXML DOM and both faster and more reliable than COM/Interop, and because some of the other methods use the clipboard, which I would caution against, as it's output is unreliable.

The details can be found in my answer in the link below, however that example is for a DataTable, but you can adapt it to using a DataGridView by just changing the row/column loops to reference a dgv instead of a dt.

How to export DataTable to Excel

Disable button in jQuery

Simply it's work fine, in HTML:

<button type="button" id="btn_CommitAll"class="btn_CommitAll">save</button>

In JQuery side put this function for disable button:

function disableButton() {
    $('.btn_CommitAll').prop("disabled", true);
}

For enable button:

function enableButton() {
    $('.btn_CommitAll').prop("disabled", false);
}

That's all.

What is the difference between jQuery: text() and html() ?

I think that the difference is to insert html tag in text() you html tag do not functions

$('#output').html('You are registered'+'<br>'  +'  '
                     + 'Mister'+'  ' + name+'   ' + sourname ); }

output :

You are registered <br> Mister name sourname

replacing text() with html()

output

You are registered
Mister name sourname 

then the tag <br> works in html()

How is the java memory pool divided?

The Heap is divided into young and old generations as follows :

Young Generation: It is a place where an object lived for a short period and it is divided into two spaces:

  • Eden Space: When object created using new keyword memory allocated on this space.
  • Survivor Space (S0 and S1): This is the pool which contains objects which have survived after minor java garbage collection from Eden space.

Old Generation: This pool basically contains tenured and virtual (reserved) space and will be holding those objects which survived after garbage collection from the Young Generation.

  • Tenured Space: This memory pool contains objects which survived after multiple garbage collection means an object which survived after garbage collection from Survivor space.

enter image description here

Explanation

Let's imagine our application has just started.

So at this point all three of these spaces are empty (Eden, S0, S1).

Whenever a new object is created it is placed in the Eden space.

When the Eden space gets full then the garbage collection process (minor GC) will take place on the Eden space and any surviving objects are moved into S0.

Our application then continues running add new objects are created in the Eden space the next time that the garbage collection process runs it looks at everything in the Eden space and in S0 and any objects that survive get moved into S1.

PS: Based on the configuration that how much time object should survive in Survivor space, the object may also move back and forth to S0 and S1 and then reaching the threshold objects will be moved to old generation heap space.

Is there an easy way to strike through text in an app widget?

To do it programatically in a textview, untested in other views >>

TextView tv = (TextView) findViewById(R.id.mytext);
tv.setText("This is strike-thru");
tv.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);

In Java, how to find if first character in a string is upper case without regex

we can find upper case letter by using regular expression as well

private static void findUppercaseFirstLetterInString(String content) {
    Matcher m = Pattern
            .compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(
                    content);
    System.out.println("Given input string : " + content);
    while (m.find()) {
        if (m.group(1).equals(m.group(1).toUpperCase())) {
            System.out.println("First Letter Upper case match found :"
                    + m.group());
        }
    }
}

for detailed example . please visit http://www.onlinecodegeek.com/2015/09/how-to-determines-if-string-starts-with.html

fix java.net.SocketTimeoutException: Read timed out

Here are few pointers/suggestions for investigation

  1. I see that every time you vote, you call vote method which creates a fresh HTTP connection.
  2. This might be a problem. I would suggest to use a single HttpClient instance to post to the server. This way it wont create too many connections from the client side.
  3. At the end of everything, HttpClient needs to be shut and hence call httpclient.getConnectionManager().shutdown(); to release the resources used by the connections.

Should I use int or Int32

You should not care in most programming languages, unless you need to write very specific mathematical functions, or code optimized for one specific architecture... Just make sure the size of the type is enough for you (use something bigger than an Int if you know you'll need more than 32-bits for example)

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

Detect iPhone/iPad purely by css

This is how I handle iPhone (and similar) devices [not iPad]:

In my CSS file:

@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {
   /* CSS overrides for mobile here */
}

In the head of my HTML document:

<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">

How to use onSavedInstanceState example please

If Data Is not Loaded From savedInstanceState use following code.
The problem is url call is not to complete fully so, check if data is loaded then to show the instanceState value.

//suppose data is not Loaded to savedInstanceState at 1st swipe
if (savedInstanceState == null && !mAlreadyLoaded){
    mAlreadyLoaded = true;
    GetStoryData();//Url Call
} else {
    if (listArray != null) {  //Data Array From JsonArray(ListArray)
        System.out.println("LocalData  " + listArray);
        view.findViewById(R.id.progressBar).setVisibility(View.GONE);
    }else{
        GetStoryData();//Url Call
    }
}

How to close a web page on a button click, a hyperlink or a link button click?

Assuming you're using WinForms, as it was the first thing I did when I was starting C# you need to create an event to close this form.

Lets say you've got a button called myNewButton. If you double click it on WinForms designer you will create an event. After that you just have to use this.Close

    private void myNewButton_Click(object sender, EventArgs e) {
        this.Close();
    }

And that should be it.

The only reason for this not working is that your Event is detached from button. But it should create new event if old one is no longer attached when you double click on the button in WinForms designer.

MySQL wait_timeout Variable - GLOBAL vs SESSION

SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 28800
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 28800

At first, wait_timeout = 28800 which is the default value. To change the session value, you need to set the global variable because the session variable is read-only.

SET @@GLOBAL.wait_timeout=300

After you set the global variable, the session variable automatically grabs the value.

SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 300
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 300

Next time when the server restarts, the session variables will be set to the default value i.e. 28800.

P.S. I m using MySQL 5.6.16

Dynamically change bootstrap progress bar value when checkboxes checked

Try this maybe :

Bootply : http://www.bootply.com/106527

Js :

$('input').on('click', function(){
  var valeur = 0;
  $('input:checked').each(function(){
       if ( $(this).attr('value') > valeur )
       {
           valeur =  $(this).attr('value');
       }
  });
  $('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);    
});

HTML :

 <div class="progress progress-striped active">
        <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
        </div>
    </div>
<div class="row tasks">
        <div class="col-md-6">
          <p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>
        </div>
        <div class="col-md-2">
          <label>2014-01-29</label>
        </div>
        <div class="col-md-2">
          <input name="progress" class="progress" type="checkbox" value="10">
        </div>
        <div class="col-md-2">
          <input name="done" class="done" type="checkbox" value="20">
        </div>
      </div><!-- tasks -->

<div class="row tasks">
        <div class="col-md-6">
          <p><span>Set your goals + benchmarks</span>Having SMART goals can help you be
sure that you’ll have tangible results to share with the world (or your
boss) at the end of your campaign.</p>
        </div>
        <div class="col-md-2">
          <label>2014-01-25</label>
        </div>
        <div class="col-md-2">
          <input name="progress" class="progress" type="checkbox" value="30">
        </div>
        <div class="col-md-2">
          <input name="done" class="done" type="checkbox" value="40">
        </div>
      </div><!-- tasks -->

Css

.tasks{
    background-color: #F6F8F8;
    padding: 10px;
    border-radius: 5px;
    margin-top: 10px;
}
.tasks span{
    font-weight: bold;
}
.tasks input{
    display: block;
    margin: 0 auto;
    margin-top: 10px;
}
.tasks a{
    color: #000;
    text-decoration: none;
    border:none;
}
.tasks a:hover{
    border-bottom: dashed 1px #0088cc;
}
.tasks label{
    display: block;
    text-align: center;
}

_x000D_
_x000D_
$(function(){_x000D_
$('input').on('click', function(){_x000D_
  var valeur = 0;_x000D_
  $('input:checked').each(function(){_x000D_
       if ( $(this).attr('value') > valeur )_x000D_
       {_x000D_
           valeur =  $(this).attr('value');_x000D_
       }_x000D_
  });_x000D_
  $('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);    _x000D_
});_x000D_
_x000D_
});
_x000D_
.tasks{_x000D_
 background-color: #F6F8F8;_x000D_
 padding: 10px;_x000D_
 border-radius: 5px;_x000D_
 margin-top: 10px;_x000D_
}_x000D_
.tasks span{_x000D_
 font-weight: bold;_x000D_
}_x000D_
.tasks input{_x000D_
 display: block;_x000D_
 margin: 0 auto;_x000D_
 margin-top: 10px;_x000D_
}_x000D_
.tasks a{_x000D_
 color: #000;_x000D_
 text-decoration: none;_x000D_
 border:none;_x000D_
}_x000D_
.tasks a:hover{_x000D_
 border-bottom: dashed 1px #0088cc;_x000D_
}_x000D_
.tasks label{_x000D_
 display: block;_x000D_
 text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
 <div class="progress progress-striped active">_x000D_
        <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">_x000D_
        </div>_x000D_
    </div>_x000D_
<div class="row tasks">_x000D_
        <div class="col-md-6">_x000D_
          <p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <label>2014-01-29</label>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="progress" class="progress" type="checkbox" value="10">_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="done" class="done" type="checkbox" value="20">_x000D_
        </div>_x000D_
      </div><!-- tasks -->_x000D_
_x000D_
<div class="row tasks">_x000D_
        <div class="col-md-6">_x000D_
          <p><span>Set your goals + benchmarks</span>Having SMART goals can help you be_x000D_
sure that you’ll have tangible results to share with the world (or your_x000D_
boss) at the end of your campaign.</p>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <label>2014-01-25</label>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="progress" class="progress" type="checkbox" value="30">_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="done" class="done" type="checkbox" value="40">_x000D_
        </div>_x000D_
      </div><!-- tasks -->
_x000D_
_x000D_
_x000D_

How to print a string multiple times?

def repeat_char_rows_cols(char, rows, cols):
    return (char*cols + '\n')*rows

>>> print(repeat_char_rows_cols('@', 4, 2))
@@
@@
@@
@@

/bin/sh: pushd: not found

This is because pushd is a builtin function in bash. So it is not related to the PATH variable and also it is not supported by /bin/sh (which is used by default by make. You can change that by setting SHELL (although it will not work directly (test1)).

You can instead run all the commands through bash -c "...". That will make the commands, including pushd/popd, run in a bash environment (test2).

SHELL = /bin/bash

test1:
        @echo before
        @pwd
        @pushd /tmp
        @echo in /tmp
        @pwd
        @popd
        @echo after
        @pwd

test2:
        @/bin/bash -c "echo before;\
        pwd; \
        pushd /tmp; \
        echo in /tmp; \
        pwd; \
        popd; \
        echo after; \
        pwd;"

When running make test1 and make test2 it gives the following:

prompt>make test1
before
/download/2011/03_mar
make: pushd: Command not found
make: *** [test1] Error 127
prompt>make test2
before
/download/2011/03_mar
/tmp /download/2011/03_mar
in /tmp
/tmp
/download/2011/03_mar
after
/download/2011/03_mar
prompt>

For test1, even though bash is used as a shell, each command/line in the rule is run by itself, so the pushd command is run in a different shell than the popd.

Simple search MySQL database using php

You need to use $_POST not $_post.

Disable scrolling in an iPhone web application?

Change to the touchstart event instead of touchmove. Under One Finger Events it says that no events are sent during a pan, so touchmove may be too late.

I added the listener to document, not body.

Example:

document.ontouchstart = function(e){ 
    e.preventDefault(); 
}

Quoting backslashes in Python string literals

Use a raw string:

>>> foo = r'baz "\"'
>>> foo
'baz "\\"'

Note that although it looks wrong, it's actually right. There is only one backslash in the string foo.

This happens because when you just type foo at the prompt, python displays the result of __repr__() on the string. This leads to the following (notice only one backslash and no quotes around the printed string):

>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

And let's keep going because there's more backslash tricks. If you want to have a backslash at the end of the string and use the method above you'll come across a problem:

>>> foo = r'baz \'
  File "<stdin>", line 1
    foo = r'baz \'
                 ^  
SyntaxError: EOL while scanning single-quoted string

Raw strings don't work properly when you do that. You have to use a regular string and escape your backslashes:

>>> foo = 'baz \\'
>>> print(foo)
baz \

However, if you're working with Windows file names, you're in for some pain. What you want to do is use forward slashes and the os.path.normpath() function:

myfile = os.path.normpath('c:/folder/subfolder/file.txt')
open(myfile)

This will save a lot of escaping and hair-tearing. This page was handy when going through this a while ago.

MySQL Multiple Where Clause

May be using this query you don't get any result or empty result. You need to use OR instead of AND in your query like below.

$query = mysql_query("SELECT image_id FROM list WHERE (style_id = 24 AND style_value = 'red') OR (style_id = 25 AND style_value = 'big') OR (style_id = 27 AND style_value = 'round');

Try out this query.

How to get a specific output iterating a hash in Ruby?

You can also refine Hash::each so it will support recursive enumeration. Here is my version of Hash::each(Hash::each_pair) with block and enumerator support:

module HashRecursive
    refine Hash do
        def each(recursive=false, &block)
            if recursive
                Enumerator.new do |yielder|
                    self.map do |key, value|
                        value.each(recursive=true).map{ |key_next, value_next| yielder << [[key, key_next].flatten, value_next] } if value.is_a?(Hash)
                        yielder << [[key], value]
                    end
                end.entries.each(&block)
            else
                super(&block)
            end
        end
        alias_method(:each_pair, :each)
    end
end

using HashRecursive

Here are usage examples of Hash::each with and without recursive flag:

hash = {
    :a => {
        :b => {
            :c => 1,
            :d => [2, 3, 4]
        },
        :e => 5
    },
    :f => 6
}

p hash.each, hash.each {}, hash.each.size
# #<Enumerator: {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}:each>
# {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}
# 2

p hash.each(true), hash.each(true) {}, hash.each(true).size
# #<Enumerator: [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]:each>
# [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]
# 6

hash.each do |key, value|
    puts "#{key} => #{value}"
end
# a => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# f => 6

hash.each(true) do |key, value|
    puts "#{key} => #{value}"
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :b] => {:c=>1, :d=>[2, 3, 4]}
# [:a, :e] => 5
# [:a] => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# [:f] => 6

hash.each_pair(recursive=true) do |key, value|
    puts "#{key} => #{value}" unless value.is_a?(Hash)
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :e] => 5
# [:f] => 6

Here is example from the question itself:

hash = {
    1   =>  ["a", "b"], 
    2   =>  ["c"], 
    3   =>  ["a", "d", "f", "g"], 
    4   =>  ["q"]
}

hash.each(recursive=false) do |key, value|
    puts "#{key} => #{value}"
end
# 1 => ["a", "b"]
# 2 => ["c"]
# 3 => ["a", "d", "f", "g"]
# 4 => ["q"]

Also take a look at my recursive version of Hash::merge(Hash::merge!) here.

iOS - UIImageView - how to handle UIImage image orientation

extension UIImage {
    func fixImageOrientation() -> UIImage {
        UIGraphicsBeginImageContext(self.size)
        self.draw(at: .zero)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage ?? self
    }
}
  1. Create extension like top example.
  2. Call it: imageView.image?.fixImageOrientation() or UIImage(named: "someImage").fixImageOrientation()

  3. Good luck all!

Check If only numeric values were entered in input. (jQuery)

I used this:

jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, ""); 
return this.optional(element) || phone_number.length > 9 &&
    phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");

Java converting int to hex and back again

Using Integer.toHexString(...) is a good answer. But personally prefer to use String.format(...).

Try this sample as a test.

byte[] values = new byte[64];
Arrays.fill(values, (byte)8);  //Fills array with 8 just for test
String valuesStr = "";
for(int i = 0; i < values.length; i++)
    valuesStr += String.format("0x%02x", values[i] & 0xff) + " ";
valuesStr.trim();

Is HTML considered a programming language?

No - there's a big prejudice in IT against web design; but in this case the "real" programmers are on pretty firm ground.

If you've done a lot of web design work you've probably done some JavaScript, so you can put that down under 'programming languages'; if you want to list HTML as well, then I agree with the answer that suggests "Technologies".

But unless you're targeting agents who're trying to tick boxes rather than find you a good job, a bare list of things you've used doesn't really look all that good. You're better off listing the projects you've worked on and detailing the technologies you used on each; that demonstrates that you've got real experience of using them rather than just that you know some buzzwords.

Remove characters from C# string

Taking the performance figures from @drzaus, here is an extension method that uses the fastest algorithm.

public static class StringEx
{
    public static string RemoveCharacters(this string s, params char[] unwantedCharacters) 
        => s == null ? null : string.Join(string.Empty, s.Split(unwantedCharacters));
}

Usage

var name = "edward woodward!";
var removeDs = name.RemoveCharacters('d', '!');
Assert.Equal("ewar woowar", removeDs); // old joke

What is let-* in Angular 2 templates?

update Angular 5

ngOutletContext was renamed to ngTemplateOutletContext

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

original

Templates (<template>, or <ng-template> since 4.x) are added as embedded views and get passed a context.

With let-col the context property $implicit is made available as col within the template for bindings. With let-foo="bar" the context property bar is made available as foo.

For example if you add a template

<ng-template #myTemplate let-col let-foo="bar">
  <div>{{col}}</div>
  <div>{{foo}}</div>
</ng-template>

<!-- render above template with a custom context -->
<ng-template [ngTemplateOutlet]="myTemplate"
             [ngTemplateOutletContext]="{
                                           $implicit: 'some col value',
                                           bar: 'some bar value'
                                        }"
></ng-template>

See also this answer and ViewContainerRef#createEmbeddedView.

*ngFor also works this way. The canonical syntax makes this more obvious

<ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">
  <div>{{item}}</div>
</ng-template>

where NgFor adds the template as embedded view to the DOM for each item of items and adds a few values (item, index, odd) to the context.

See also Using $implict to pass multiple parameters

Setting timezone to UTC (0) in PHP

In PHP DateTime (PHP >= 5.3)

$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->getTimestamp();

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

VBA copy cells value and format

Following on from jpw it might be good to encapsulate his solution in a small subroutine to save on having lots of lines of code:

Private Sub CommandButton1_Click()
Dim i As Integer
Dim a As Integer
a = 15
For i = 11 To 32
  If Worksheets(1).Cells(i, 3) <> "" Then
    call copValuesAndFormat(i,3,a,15)        
    call copValuesAndFormat(i,5,a,17) 
    call copValuesAndFormat(i,6,a,18) 
    call copValuesAndFormat(i,7,a,19) 
    call copValuesAndFormat(i,8,a,20) 
    call copValuesAndFormat(i,9,a,21) 
    a = a + 1
  End If
Next i
end sub

sub copValuesAndFormat(x1 as integer, y1 as integer, x2 as integer, y2 as integer)
  Worksheets(1).Cells(x1, y1).Copy
  Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteFormats
  Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteValues
end sub

(I do not have Excel in current location so please excuse bugs as not tested)

How do I show running processes in Oracle DB?

I suspect you would just want to grab a few columns from V$SESSION and the SQL statement from V$SQL. Assuming you want to exclude the background processes that Oracle itself is running

SELECT sess.process, sess.status, sess.username, sess.schemaname, sql.sql_text
  FROM v$session sess,
       v$sql     sql
 WHERE sql.sql_id(+) = sess.sql_id
   AND sess.type     = 'USER'

The outer join is to handle those sessions that aren't currently active, assuming you want those. You could also get the sql_fulltext column from V$SQL which will have the full SQL statement rather than the first 1000 characters, but that is a CLOB and so likely a bit more complicated to deal with.

Realistically, you probably want to look at everything that is available in V$SESSION because it's likely that you can get a lot more information than SP_WHO provides.

Does Android support near real time push notification?

There is a new open-source effort to develop a Java library for push notifications on Android, using the Meteor comet server as a backend. You can check it out at the Deacon Project Blog. We need developers, so please spread the word!

How to loop through elements of forms with JavaScript?

You can iterate named fields somehow like this:

let jsonObject = {};
for(let field of form.elements) {
  if (field.name) {
      jsonObject[field.name] = field.value;
  }
}

Or, if you need only submiting fields:

function formDataToJSON(form) {
  let jsonObject = {};
  let formData = new FormData(form);
  for(let field of formData) {
      jsonObject[field[0]] = field[1];
  }
  return JSON.stringify(jsonObject);
}

How to copy a folder via cmd?

xcopy  e:\source_folder f:\destination_folder /e /i /h

The /h is just in case there are hidden files. The /i creates a destination folder if there are muliple source files.

JavaScript check if variable exists (is defined/initialized)

You can also use !! before a variable to check if it's defined. E.g.

let dog = "woof";
let chineseCat; // Undefined.
console.log("1.");
console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");

chineseCat= "mao"; // dog and chineseCat are now defined.
console.log("2.");
console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");

Output:

1.
Both are NOT defined
2. 
Both are defined

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

In Python 3.5 you can overload @ as an operator. It is named as __matmul__, because it is designed to do matrix multiplication, but it can be anything you want. See PEP465 for details.

This is a simple implementation of matrix multiplication.

class Mat(list):
    def __matmul__(self, B):
        A = self
        return Mat([[sum(A[i][k]*B[k][j] for k in range(len(B)))
                    for j in range(len(B[0])) ] for i in range(len(A))])

A = Mat([[1,3],[7,5]])
B = Mat([[6,8],[4,2]])

print(A @ B)

This code yields:

[[18, 14], [62, 66]]

Converting JSON to XLS/CSV in Java

you can use commons csv to convert into CSV format. or use POI to convert into xls. if you need helper to convert into xls, you can use jxls, it can convert java bean (or list) into excel with expression language.

Basically, the json doc maybe is a json array, right? so it will be same. the result will be list, and you just write the property that you want to display in excel format that will be read by jxls. See http://jxls.sourceforge.net/reference/collections.html

If the problem is the json can't be read in the jxls excel property, just serialize it into collection of java bean first.

Create a jTDS connection string

As detailed in the jTDS Frequenlty Asked Questions, the URL format for jTDS is:

jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]

So, to connect to a database called "Blog" hosted by a MS SQL Server running on MYPC, you may end up with something like this:

jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS;user=sa;password=s3cr3t

Or, if you prefer to use getConnection(url, "sa", "s3cr3t"):

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

EDIT: Regarding your Connection refused error, double check that you're running SQL Server on port 1433, that the service is running and that you don't have a firewall blocking incoming connections.

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

Alternative solution that uses .query() method:

In [5]: df.query("countries in @countries")
Out[5]:
  countries
1        UK
3     China

In [6]: df.query("countries not in @countries")
Out[6]:
  countries
0        US
2   Germany

How to put a div in center of browser using CSS?

<html>
<head>
<style>
*
{
    margin:0;
    padding:0;
}

html, body
{
    height:100%;
}

#distance
{
    width:1px;
    height:50%;
    margin-bottom:-300px;
    float:left;
}


#something
{
    position:relative;
    margin:0 auto;
    text-align:left;
    clear:left;
    width:800px;
    min-height:600px;
    height:auto;
    border: solid 1px #993333;
    z-index: 0;
}

/* for Internet Explorer */
* html #something{
height: 600px;
}
</style>

</head>
<body>

<div id="distance"></div>

<div id="something">
</div>
</body>

</html>

Tested in FF2-3, IE6-7, Opera and works well!

CodeIgniter - How to return Json response from controller

return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode(array(
                    'text' => 'Error 500',
                    'type' => 'danger'
            )));

How do I access an access array item by index in handlebars?

The following, with an additional dot before the index, works just as expected. Here, the square brackets are optional when the index is followed by another property:

{{people.[1].name}}
{{people.1.name}}

However, the square brackets are required in:

{{#with people.[1]}}
  {{name}}
{{/with}}

In the latter, using the index number without the square brackets would get one:

Error: Parse error on line ...:
...     {{#with people.1}}                
-----------------------^
Expecting 'ID', got 'INTEGER'

As an aside: the brackets are (also) used for segment-literal syntax, to refer to actual identifiers (not index numbers) that would otherwise be invalid. More details in What is a valid identifier?

(Tested with Handlebars in YUI.)

2.xx Update

You can now use the get helper for this:

(get people index)

although if you get an error about index needing to be a string, do:

(get people (concat index ""))

How can I check the system version of Android?

if (Build.VERSION.SDK_INT >= ApiHelper.VERSION_CODES.HONEYCOMB_MR2) {
//do anything you  like.
}

How to get a variable value if variable name is stored as string?

In bash 4.3, the '-v' test for set variables was introduced. At the same time, 'nameref' declaration was added. These two features together with the indirection operator (!) enable a simplified version of the previous example:

get_value()
{
  declare -n var_name=$1
  if [[ -v var_name ]]
  then
    echo "${var_name}"
  else
    echo "variable with name <${!var_name}> is not set"
  fi
}

test=123
get_value test
123

test="\$(echo \"something nasty\")"
get_value test
$(echo "something nasty")

unset test
get_value test
variable with name <test> is not set

As this approach eliminates the need for 'eval', it is safer. This code checked under bash 5.0.3(1).

How to read files and stdout from a running Docker container

To view the stdout, you can start the docker container with -i. This of course does not enable you to leave the started process and explore the container.

docker start -i containerid

Alternatively you can view the filesystem of the container at

/var/lib/docker/containers/containerid/root/

However neither of these are ideal. If you want to view logs or any persistent storage, the correct way to do so would be attaching a volume with the -v switch when you use docker run. This would mean you can inspect log files either on the host or attach them to another container and inspect them there.

How to update two tables in one statement in SQL Server 2005?

Sorry, afaik, you cannot do that. To update attributes in two different tables, you will need to execute two separate statements. But they can be in a batch ( a set of SQL sent to the server in one round trip)

Adjusting the Xcode iPhone simulator scale and size

Specific to XCode 9.1:
You can refere to @Krunal's answer above or follow below steps

its bit tricky to adjust Simulator size.

If you want to zoom your simulator screen follow below steps :

  • Goto Window->Uncheck Show Device Bezels

refer screenshot 1

  • Goto Window->select zoom

refere screenshot 2

after doing this you can resize your simulator by dragging edges of simulator.

Pixel Accurate : Its to display your simulator in same size as Physical device pixels, if your screen size doesn't have enough resolution to cover dimension it would not enable Pixel Accurate option.

Alternate is change simulator to landscape mode by clicking ? + ? ,then you could click ? + 2 to select Pixel Accurate option (make sure you have disable Show Device Bezels to reduce size.

How to check for a Null value in VB.NET

You can also use the IsDBNull function:

If Not IsDBNull(editTransactionRow.pay_id) Then
...

Difference between <context:annotation-config> and <context:component-scan>

I found this nice summary of which annotations are picked up by which declarations. By studying it you will find that <context:component-scan/> recognizes a superset of annotations recognized by <context:annotation-config/>, namely:

  • @Component, @Service, @Repository, @Controller, @Endpoint
  • @Configuration, @Bean, @Lazy, @Scope, @Order, @Primary, @Profile, @DependsOn, @Import, @ImportResource

As you can see <context:component-scan/> logically extends <context:annotation-config/> with CLASSPATH component scanning and Java @Configuration features.

Underscore prefix for property and method names in JavaScript

Welcome to 2019!

It appears a proposal to extend class syntax to allow for # prefixed variable to be private was accepted. Chrome 74 ships with this support.

_ prefixed variable names are considered private by convention but are still public.

This syntax tries to be both terse and intuitive, although it's rather different from other programming languages.

Why was the sigil # chosen, among all the Unicode code points?

  • @ was the initial favorite, but it was taken by decorators. TC39 considered swapping decorators and private state sigils, but the committee decided to defer to the existing usage of transpiler users.
  • _ would cause compatibility issues with existing JavaScript code, which has allowed _ at the start of an identifier or (public) property name for a long time.

This proposal reached Stage 3 in July 2017. Since that time, there has been extensive thought and lengthy discussion about various alternatives. In the end, this thought process and continued community engagement led to renewed consensus on the proposal in this repository. Based on that consensus, implementations are moving forward on this proposal.

See https://caniuse.com/#feat=mdn-javascript_classes_private_class_fields

What is the difference between angular-route and angular-ui-router?

ui router make your life easier! You can add it to you AngularJS application via injecting it into your applications...

ng-route comes as part of the core AngularJS, so it's simpler and gives you fewer options...

Look at here to understand ng-route better: https://docs.angularjs.org/api/ngRoute

Also when using it, don't forget to use: ngView ..

ng-ui-router is different but:

https://github.com/angular-ui/ui-router but gives you more options....

How to get the 'height' of the screen using jquery

use with responsive website (view in mobile or ipad)

jQuery(window).height();   // return height of browser viewport
jQuery(window).width();    // return width of browser viewport

rarely use

jQuery(document).height(); // return height of HTML document
jQuery(document).width();  // return width of HTML document

ASP.NET Custom Validator Client side & Server Side validation not firing

Server-side validation won't fire if client-side validation is invalid, the postback is not send.

Don't you have some other validation that doesn't pass?

The client-side validation is not executed because you specified ClientValidationFunction="TextBoxDTownCityClient" and this will look for a function named TextBoxDTownCityClient as validation function, but the function name should be TextBoxDAddress1Client

(as you wrote)

Python: How to increase/reduce the fontsize of x and y tick labels?

You can set the fontsize directly in the call to set_xticklabels and set_yticklabels (as noted in previous answers). This will only affect one Axes at a time.

ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)

You can also set the ticklabel font size globally (i.e. for all figures/subplots in a script) using rcParams:

import matplotlib.pyplot as plt

plt.rc('xtick',labelsize=8)
plt.rc('ytick',labelsize=8)

Or, equivalently:

plt.rcParams['xtick.labelsize']=8
plt.rcParams['ytick.labelsize']=8

Finally, if this is a setting that you would like to be set for all your matplotlib plots, you could also set these two rcParams in your matplotlibrc file:

xtick.labelsize      : 8 # fontsize of the x tick labels
ytick.labelsize      : 8 # fontsize of the y tick labels

Display PNG image as response to jQuery AJAX request

You'll need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php

Then in your ajax call change the success function to this:

$('.div_imagetranscrits').html('<img src="data:image/png;base64,' + data + '" />');

SQL query to find third highest salary in company

I found a very good explanation in

http://www.programmerinterview.com/index.php/database-sql/find-nth-highest-salary-sql/

This query should give nth highest salary

SELECT *
FROM Employee Emp1
WHERE (N-1) = (
    SELECT COUNT(DISTINCT(Emp2.Salary))
    FROM Employee Emp2
    WHERE Emp2.Salary > Emp1.Salary)

How do you echo a 4-digit Unicode character in Bash?

In bash to print a Unicode character to output use \x,\u or \U (first for 2 digit hex, second for 4 digit hex, third for any length)

echo -e '\U1f602'

I you want to assign it to a variable use $'...' syntax

x=$'\U1f602'
echo $x

When to use RDLC over RDL reports?

If we have fewer number of reports which are less complex and consumed by asp.net web pages. It's better to go with rdlc,reason is we can avoid maintaing reports on RS instance. but we have to fetch the data from DB manually and bind it to rdlc.

Cons:designing rdlc in visual studio is little difficult compared to SSrs designer.

Pro:Maintenance is easy. while exporting the report from we page,observed that performance gain compared to server side reports.

Visual Studio 2017: Display method references

In Visual Studio Professional or Enterprise you can enable CodeLens by doing this:

Tools ? Options ? Text Editor ? All Languages ? CodeLens

This is not available in the Community Edition

Java random numbers using a seed

The easy way is to use:

Random rand = new Random(System.currentTimeMillis());

This is the best way to generate Random numbers.

Zoom in on a point (using scale and translate)

Finally solved it:

_x000D_
_x000D_
var zoomIntensity = 0.2;_x000D_
_x000D_
var canvas = document.getElementById("canvas");_x000D_
var context = canvas.getContext("2d");_x000D_
var width = 600;_x000D_
var height = 200;_x000D_
_x000D_
var scale = 1;_x000D_
var originx = 0;_x000D_
var originy = 0;_x000D_
var visibleWidth = width;_x000D_
var visibleHeight = height;_x000D_
_x000D_
_x000D_
function draw(){_x000D_
    // Clear screen to white._x000D_
    context.fillStyle = "white";_x000D_
    context.fillRect(originx,originy,800/scale,600/scale);_x000D_
    // Draw the black square._x000D_
    context.fillStyle = "black";_x000D_
    context.fillRect(50,50,100,100);_x000D_
}_x000D_
// Draw loop at 60FPS._x000D_
setInterval(draw, 1000/60);_x000D_
_x000D_
canvas.onwheel = function (event){_x000D_
    event.preventDefault();_x000D_
    // Get mouse offset._x000D_
    var mousex = event.clientX - canvas.offsetLeft;_x000D_
    var mousey = event.clientY - canvas.offsetTop;_x000D_
    // Normalize wheel to +1 or -1._x000D_
    var wheel = event.deltaY < 0 ? 1 : -1;_x000D_
_x000D_
    // Compute zoom factor._x000D_
    var zoom = Math.exp(wheel*zoomIntensity);_x000D_
    _x000D_
    // Translate so the visible origin is at the context's origin._x000D_
    context.translate(originx, originy);_x000D_
  _x000D_
    // Compute the new visible origin. Originally the mouse is at a_x000D_
    // distance mouse/scale from the corner, we want the point under_x000D_
    // the mouse to remain in the same place after the zoom, but this_x000D_
    // is at mouse/new_scale away from the corner. Therefore we need to_x000D_
    // shift the origin (coordinates of the corner) to account for this._x000D_
    originx -= mousex/(scale*zoom) - mousex/scale;_x000D_
    originy -= mousey/(scale*zoom) - mousey/scale;_x000D_
    _x000D_
    // Scale it (centered around the origin due to the trasnslate above)._x000D_
    context.scale(zoom, zoom);_x000D_
    // Offset the visible origin to it's proper position._x000D_
    context.translate(-originx, -originy);_x000D_
_x000D_
    // Update scale and others._x000D_
    scale *= zoom;_x000D_
    visibleWidth = width / scale;_x000D_
    visibleHeight = height / scale;_x000D_
}
_x000D_
<canvas id="canvas" width="600" height="200"></canvas>
_x000D_
_x000D_
_x000D_

The key, as @Tatarize pointed out, is to compute the axis position such that the zoom point (mouse pointer) remains in the same place after the zoom.

Originally the mouse is at a distance mouse/scale from the corner, we want the point under the mouse to remain in the same place after the zoom, but this is at mouse/new_scale away from the corner. Therefore we need to shift the origin (coordinates of the corner) to account for this.

originx -= mousex/(scale*zoom) - mousex/scale;
originy -= mousey/(scale*zoom) - mousey/scale;
scale *= zoom

The remaining code then needs to apply the scaling and translate to the draw context so it's origin coincides with the canvas corner.

What is the recommended project structure for spring boot rest projects?

Though this question has an accepted answer, still I would like to share my project structure for RESTful services.

src/main/java
    +- com
        +- example
            +- Application.java
            +- ApplicationConstants.java
                +- configuration
                |   +- ApplicationConfiguration.java
                +- controller
                |   +- ApplicationController.java
                +- dao
                |   +- impl
                |   |   +- ApplicationDaoImpl.java
                |   +- ApplicationDao.java
                +- dto
                |   +- ApplicationDto.java
                +- service
                |   +- impl
                |   |   +- ApplicationServiceImpl.java
                |   +- ApplicationService.java
                +- util
                |   +- ApplicationUtils.java
                +- validation
                |   +- impl
                |   |   +- ApplicationValidationImpl.java
                |   +- ApplicationValidation.java

DAO = Data Access Object.
DTO = Data Transfer Object.

Programmatically register a broadcast receiver

It sounds like you want to control whether components published in your manifest are active, not dynamically register a receiver (via Context.registerReceiver()) while running.

If so, you can use PackageManager.setComponentEnabledSetting() to control whether these components are active:

http://developer.android.com/reference/android/content/pm/PackageManager.html#setComponentEnabledSetting(android.content.ComponentName, int, int)

Note if you are only interested in receiving a broadcast while you are running, it is better to use registerReceiver(). A receiver component is primarily useful for when you need to make sure your app is launched every time the broadcast is sent.

Create hive table using "as select" or "like" and also specify delimiter

Both the answers provided above work fine.

  1. CREATE TABLE person AS select * from employee;
  2. CREATE TABLE person LIKE employee;

How to get enum value by string or int

No, you don't want a generic method. This is much easier:

MyEnum myEnum = (MyEnum)myInt;

MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), myString);

I think it will also be faster.

'do...while' vs. 'while'

I can't imagine how you've gone this long without using a do...while loop.

There's one on another monitor right now and there are multiple such loops in that program. They're all of the form:

do
{
    GetProspectiveResult();
}
while (!ProspectIsGood());

A hex viewer / editor plugin for Notepad++?

There is an old plugin called HEX Editor here.

According to this question on Super User it does not work on newer versions of Notepad++ and might have some stability issues, but it still could be useful depending on your needs.

How to Add Stacktrace or debug Option when Building Android Studio Project

Go into your project.

install Gradle.

https://docs.gradle.org/current/userguide/installation.html

On a mac: brew install gradle

Then gradle build --stacktrace

How to append new data onto a new line

You need to change parameter "a" => "a+". Follow this code bellows:

def storescores():
hs = open("hst.txt","a+")

Add a pipe separator after items in an unordered list unless that item is the last on a line

Just

li + li::before {
    content: " | ";
}

Of course, this does not actually solve the OP's problem. He wants to elide the vertical bars at the beginning and end of lines depending on where they are broken. I will go out on a limb and assert that this problem is not solvable using CSS, and not even with JS unless one wants to essentially rewrite the browser engine's text-measurement/layout/line breaking logic.

The only pieces of CSS, as far as I can see, that "know" about line breaking are, first, the ::first-line pseudo element, which does not help us here--in any case, it is limited to a few presentational attributes, and does not work together with things like ::before and ::after. The only other aspect of CSS I can think of that to some extent exposes line-breaking is hyphenation. However, hyphenating is all about adding a character (usually a dash) to the end of lines in certain situations, whereas here we are concerned about removing a character (the vertical line), so I just can't see how to apply any kind of hyphenation-related logic, even with the help of properties such as hyphenate-character.

We have the word-spacing property, which is applied intra-line but not at line beginnings and endings, which seems promising, but it defines the width of the space between words, not the character(s) to be used.

One wonders if there's some way to use the text-overflow property, which has the little-known ability to take two values for display of overflow text at both left and right, as in

text-overflow: '' '';

but there still doesn't seem to be any obvious way to get from A to B here.

Angular, content type is not being sent with $http

In case it's useful to anyone. For AngularJS 1.5x I wanted to set CSRF for all requests and I found that when I did this:

$httpProvider.defaults.headers.get = { 'CSRF-Token': afToken }; 
$httpProvider.defaults.headers.put = { 'CSRF-Token': afToken };
$httpProvider.defaults.headers.post = { 'CSRF-Token': afToken }; 

Angular removed the content type so I had to add this:

$httpProvider.defaults.headers.common = { "Content-Type": "application/json"};

Otherwise I get a 415 media type error.

So I am doing this to configure my application for all requests:

angular.module("myapp.maintenance", [])
    .controller('maintenanceCtrl', MaintenanceCtrl)
    .directive('convertToNumber', ConvertToNumber)
    .config(configure);

MaintenanceCtrl.$inject = ["$scope", "$http", "$sce", "$window", "$document", "$timeout", "$filter", 'alertService'];
configure.$inject = ["$httpProvider"];

// configure the header tokens for  CSRF for http operations in this module
function configure($httpProvider) {

    const afToken = angular.element('input[id="__AntiForgeryToken"]').attr('value');

    $httpProvider.defaults.headers.get = { 'CSRF-Token': afToken }; // only added for GET
    $httpProvider.defaults.headers.put = { 'CSRF-Token': afToken }; // added for PUT
    $httpProvider.defaults.headers.post = { 'CSRF-Token': afToken }; // added for POST

    // for some reason if we do the above we have to set the default content type for all 
    // looks like angular clears it when we add our own headers
    $httpProvider.defaults.headers.common = { "Content-Type": "application/json" };

}

How to define dimens.xml for every different screen size in android?

There are nice libraries which will handle everything and reduce your pain. For using it, just add two dependencies in gradle:

 implementation 'com.intuit.ssp:ssp-android:1.0.5'
 implementation 'com.intuit.sdp:sdp-android:1.0.5'

After that, use dimens like this:

        android:layout_marginTop="@dimen/_80sdp"

Excel VBA - Sum up a column

I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.

Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))

how to bold words within a paragraph in HTML/CSS?

<p><strong>This is in bold.</strong> This is not.</p>

You might find Mozilla Developer Network to be a very handy and reliable reference.

Nested lists python

You can do this. Adapt it to your situation:

  for l in Nlist:
      for item in l:
        print item

Assign command output to variable in batch file

This is work for me

@FOR /f "delims=" %i in ('reg query hklm\SOFTWARE\Macromedia\FlashPlayer\CurrentVersion') DO set var=%i
echo %var%

Plot size and resolution with R markdown, knitr, pandoc, beamer

Figure sizes are specified in inches and can be included as a global option of the document output format. For example:

---
title: "My Document"
output:
  html_document:
    fig_width: 6
    fig_height: 4
---

And the plot's size in the graphic device can be increased at the chunk level:

```{r, fig.width=14, fig.height=12}          #Expand the plot width to 14 inches

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

You can also use the out.width and out.height arguments to directly define the size of the plot in the output file:

```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

Change bootstrap navbar collapse breakpoint without using LESS

For Bootstrap 3.3 this is the only code you need:

@media (min-width: 768px) and (max-width: 1000px) {
   .navbar-collapse.collapse {
       display: none !important;
   }
   .navbar-toggle{
        display: block !important;
   }
   .navbar-header{
        float: none;
   }
}

How to create a <style> tag with Javascript?

You wrote:

var divNode = document.createElement("div");
divNode.innerHTML = "<br><style>h1 { background: red; }</style>";
document.body.appendChild(divNode);

Why not this?

var styleNode = document.createElement("style");
document.head.appendChild(styleNode);

Henceforward you can append CSS rules easily to the HTML code:

styleNode.innerHTML = "h1 { background: red; }\n";
styleNode.innerHTML += "h2 { background: green; }\n";

...or directly to the DOM:

styleNode.sheet.insertRule("h1 { background: red; }");
styleNode.sheet.insertRule("h2 { background: green; }");

I expect this to work everywhere except archaic browsers.

Definitely works in Chrome in year 2019.

How do I get out of 'screen' without typing 'exit'?

  • Ctrl + A, Ctrl + \ - Exit screen and terminate all programs in this screen. It is helpful, for example, if you need to close a tty connection.

  • Ctrl + D, D or - Ctrl + A, Ctrl + D - "minimize" screen and screen -r to restore it.

Difference between JSON.stringify and JSON.parse

JSON.parse() takes a JSON string and transforms it into a JavaScript object.

JSON.stringify() takes a JavaScript object and transforms it into a JSON string.

const myObj = {
      name: 'bipon',
      age: 25,
      favoriteFood: 'fish curry'
};

 const myObjStr = JSON.stringify(myObj);

console.log(myObjStr);
// "{"name":"bipon","age":26,"favoriteFood":"fish curry"}"

console.log(JSON.parse(myObjStr));
 // Object {name:"bipon",age:26,favoriteFood:"fish curry"}
And although the methods are usually used on objects, they can also be used on arrays:
const myArr = ['simon', 'gomez', 'john'];

const myArrStr = JSON.stringify(myArr);

console.log(myArrStr);
// "["simon","gomez","john"]"

console.log(JSON.parse(myArrStr));
// ["simon","gomez","john"]

Find and extract a number from a string

  string verificationCode ="dmdsnjds5344gfgk65585";
            string code = "";
            Regex r1 = new Regex("\\d+");
          Match m1 = r1.Match(verificationCode);
           while (m1.Success)
            {
                code += m1.Value;
                m1 = m1.NextMatch();
            }

Java Pass Method as Parameter

I did not found any solution here that show how to pass method with parameters bound to it as a parameter of a method. Bellow is example of how you can pass a method with parameter values already bound to it.

  1. Step 1: Create two interfaces one with return type, another without. Java has similar interfaces but they are of little practical use because they do not support Exception throwing.


    public interface Do {
    void run() throws Exception;
    }


    public interface Return {
        R run() throws Exception;
    }

  1. Example of how we use both interfaces to wrap method call in transaction. Note that we pass method with actual parameters.


    //example - when passed method does not return any value
    public void tx(final Do func) throws Exception {
        connectionScope.beginTransaction();
        try {
            func.run();
            connectionScope.commit();
        } catch (Exception e) {
            connectionScope.rollback();
            throw e;
        } finally {
            connectionScope.close();
        }
    }

    //Invoke code above by 
    tx(() -> api.delete(6));

Another example shows how to pass a method that actually returns something



        public  R tx(final Return func) throws Exception {
    R r=null;
    connectionScope.beginTransaction();
    try {
                r=func.run();
                connectionScope.commit();
            } catch (Exception e) {
                connectionScope.rollback();
                throw e;
            } finally {
                connectionScope.close();
            }
        return r;
        }
        //Invoke code above by 
        Object x= tx(() -> api.get(id));

Access item in a list of lists

You can access the elements in a list-of-lists by first specifying which list you're interested in and then specifying which element of that list you want. For example, 17 is element 2 in list 0, which is list1[0][2]:

>>> list1 = [[10,13,17],[3,5,1],[13,11,12]]
>>> list1[0][2]
17

So, your example would be

50 - list1[0][0] + list1[0][1] - list1[0][2]

How do I check whether input string contains any spaces?

You can use regex “\\s”

Example program to count number of spaces (Java 9 and above)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] args) {

    Pattern pattern = Pattern.compile("\\s", Pattern.CASE_INSENSITIVE);        
    Matcher matcher = pattern.matcher("stackoverflow is a good place to get all my answers");        

    long matchCount = matcher.results().count();   
 
    if(matchCount > 0) 
      System.out.println("Match found " + matchCount + " times.");           
    else 
      System.out.println("Match not found");        
  }
}

For Java 8 and below you can use matcher.find() in a while loop and increment the count. For example,

int count = 0;
while (matcher.find()) {
  count ++;
}

Interfaces — What's the point?

Interfaces can also be daisy chained to create yet another interface. This ability to implement multiple Interfaces give the developer the advantage of adding functionality to their classes without having to change current class functionality (SOLID Principles)

O = "Classes should be open for extension but closed for modification"