Programs & Examples On #Request cancelling

Stopping or safely ignoring a request, usually an HTTP transaction between a client and a server.

How to Query Database Name in Oracle SQL Developer?

Edit: Whoops, didn't check your question tags before answering.

Check that you can actually connect to DB (have the driver placed? tested the conn when creating it?).

If so, try runnung those queries with F5

Xcode: Could not locate device support files

If you have XCode 8.1 and iOS 10.2, update XCode manually to 8.2.1. For some reason App Store didn't offer this update.

Limit text length to n lines using CSS

The solution from this thread is to use the jquery plugin dotdotdot. Not a CSS solution, but it gives you a lot of options for "read more" links, dynamic resizing etc.

How do I merge a specific commit from one branch into another in Git?

The git cherry-pick <commit> command allows you to take a single commit (from whatever branch) and, essentially, rebase it in your working branch.

Chapter 5 of the Pro Git book explains it better than I can, complete with diagrams and such. (The chapter on Rebasing is also good reading.)

Lastly, there are some good comments on the cherry-picking vs merging vs rebasing in another SO question.

How to add element in List while iterating in java?

I do this by adding the elements to an new, empty tmp List, then adding the tmp list to the original list using addAll(). This prevents unnecessarily copying a large source list.

Imagine what happens when the OP's original list has a few million items in it; for a while you'll suck down twice the memory.

In addition to conserving resources, this technique also prevents us from having to resort to 80s-style for loops and using what are effectively array indexes which could be unattractive in some cases.

How to add a string to a string[] array? There's no .Add function

Why don't you use a for loop instead of using foreach. In this scenario, there is no way you can get the index of the current iteration of the foreach loop.

The name of the file can be added to the string[] in this way,

private string[] ColeccionDeCortes(string Path)
{
  DirectoryInfo X = new DirectoryInfo(Path);
  FileInfo[] listaDeArchivos = X.GetFiles();
  string[] Coleccion=new string[listaDeArchivos.Length];

  for (int i = 0; i < listaDeArchivos.Length; i++)
  {
     Coleccion[i] = listaDeArchivos[i].Name;
  }

  return Coleccion;
}

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

How do I multiply each element in a list by a number?

You can do it in-place like so:

 l = [1, 2, 3, 4, 5]
 l[:] = [x * 5 for x in l]

This requires no additional imports and is very pythonic.

How create Date Object with values in java

SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
//format as u want

try {
    String dateStart = "June 14 2018 16:02:37";
    cal.setTime(sdf.parse(dateStart));
    //all done
} catch (ParseException e) {
    e.printStackTrace();
}

Differences between SP initiated SSO and IDP initiated SSO

In IDP Init SSO (Unsolicited Web SSO) the Federation process is initiated by the IDP sending an unsolicited SAML Response to the SP. In SP-Init, the SP generates an AuthnRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with a SAML Response. IMHO ADFSv2 support for SAML2.0 Web SSO SP-Init is stronger than its IDP-Init support re: integration with 3rd Party Fed products (mostly revolving around support for RelayState) so if you have a choice you'll want to use SP-Init as it'll probably make life easier with ADFSv2.

Here are some simple SSO descriptions from the PingFederate 8.0 Getting Started Guide that you can poke through that may help as well -- https://documentation.pingidentity.com/pingfederate/pf80/index.shtml#gettingStartedGuide/task/idpInitiatedSsoPOST.html

How to remove a newline from a string in Bash

Adding answer to show example of stripping multiple characters including \r using tr and using sed. And illustrating using hexdump.

In my case I had found that a command ending with awk print of the last item |awk '{print $2}' in the line included a carriage-return \r as well as quotes.

I used sed 's/["\n\r]//g' to strip both the carriage-return and quotes.

I could also have used tr -d '"\r\n'.

Interesting to note sed -z is needed if one wishes to remove \n line-feed chars.

$ COMMAND=$'\n"REBOOT"\r   \n'

$ echo "$COMMAND" |hexdump -C
00000000  0a 22 52 45 42 4f 4f 54  22 0d 20 20 20 0a 0a     |."REBOOT".   ..|

$ echo "$COMMAND" |tr -d '"\r\n' |hexdump -C
00000000  52 45 42 4f 4f 54 20 20  20                       |REBOOT   |

$ echo "$COMMAND" |sed 's/["\n\r]//g' |hexdump -C
00000000  0a 52 45 42 4f 4f 54 20  20 20 0a 0a              |.REBOOT   ..|

$ echo "$COMMAND" |sed -z 's/["\n\r]//g' |hexdump -C
00000000  52 45 42 4f 4f 54 20 20  20                       |REBOOT   |

And this is relevant: What are carriage return, linefeed, and form feed?

  • CR == \r == 0x0d
  • LF == \n == 0x0a

Insert content into iFrame

You can enter (for example) text from div into iFrame:

var $iframe = $('#iframe');
$iframe.ready(function() {
    $iframe.contents().find("body").append($('#mytext'));
});

and divs:

<iframe id="iframe"></iframe>
<div id="mytext">Hello!</div>

and JSFiddle demo: link

Define an <img>'s src attribute in CSS

CSS is not used to define values to DOM element attributes, javascript would be more suitable for this.

JavaScript backslash (\) in variables is causing an error

The backslash \ is reserved for use as an escape character in Javascript.

To use a backslash literally you need to use two backslashes

\\

Can you break from a Groovy "each" closure?

You could break by RETURN. For example

  def a = [1, 2, 3, 4, 5, 6, 7]
  def ret = 0
  a.each {def n ->
    if (n > 5) {
      ret = n
      return ret
    }
  }

It works for me!

Enter key in textarea

You could do something like this:

<body>

<textarea id="txtArea" onkeypress="onTestChange();"></textarea>

<script>
function onTestChange() {
    var key = window.event.keyCode;

    // If the user has pressed enter
    if (key === 13) {
        document.getElementById("txtArea").value = document.getElementById("txtArea").value + "\n*";
        return false;
    }
    else {
        return true;
    }
}
</script>

</body>

Although the new line character feed from pressing enter will still be there, but its a start to getting what you want.

Toggle Class in React

For anybody reading this in 2019, after React 16.8 was released, take a look at the React Hooks. It really simplifies handling states in components. The docs are very well written with an example of exactly what you need.

Overlay normal curve to histogram in R

Here's a nice easy way I found:

h <- hist(g, breaks = 10, density = 10,
          col = "lightgray", xlab = "Accuracy", main = "Overall") 
xfit <- seq(min(g), max(g), length = 40) 
yfit <- dnorm(xfit, mean = mean(g), sd = sd(g)) 
yfit <- yfit * diff(h$mids[1:2]) * length(g) 

lines(xfit, yfit, col = "black", lwd = 2)

Split Spark Dataframe string column into multiple columns

Here's a solution to the general case that doesn't involve needing to know the length of the array ahead of time, using collect, or using udfs. Unfortunately this only works for spark version 2.1 and above, because it requires the posexplode function.

Suppose you had the following DataFrame:

df = spark.createDataFrame(
    [
        [1, 'A, B, C, D'], 
        [2, 'E, F, G'], 
        [3, 'H, I'], 
        [4, 'J']
    ]
    , ["num", "letters"]
)
df.show()
#+---+----------+
#|num|   letters|
#+---+----------+
#|  1|A, B, C, D|
#|  2|   E, F, G|
#|  3|      H, I|
#|  4|         J|
#+---+----------+

Split the letters column and then use posexplode to explode the resultant array along with the position in the array. Next use pyspark.sql.functions.expr to grab the element at index pos in this array.

import pyspark.sql.functions as f

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .show()
#+---+------------+---+---+
#|num|     letters|pos|val|
#+---+------------+---+---+
#|  1|[A, B, C, D]|  0|  A|
#|  1|[A, B, C, D]|  1|  B|
#|  1|[A, B, C, D]|  2|  C|
#|  1|[A, B, C, D]|  3|  D|
#|  2|   [E, F, G]|  0|  E|
#|  2|   [E, F, G]|  1|  F|
#|  2|   [E, F, G]|  2|  G|
#|  3|      [H, I]|  0|  H|
#|  3|      [H, I]|  1|  I|
#|  4|         [J]|  0|  J|
#+---+------------+---+---+

Now we create two new columns from this result. First one is the name of our new column, which will be a concatenation of letter and the index in the array. The second column will be the value at the corresponding index in the array. We get the latter by exploiting the functionality of pyspark.sql.functions.expr which allows us use column values as parameters.

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .drop("val")\
    .select(
        "num",
        f.concat(f.lit("letter"),f.col("pos").cast("string")).alias("name"),
        f.expr("letters[pos]").alias("val")
    )\
    .show()
#+---+-------+---+
#|num|   name|val|
#+---+-------+---+
#|  1|letter0|  A|
#|  1|letter1|  B|
#|  1|letter2|  C|
#|  1|letter3|  D|
#|  2|letter0|  E|
#|  2|letter1|  F|
#|  2|letter2|  G|
#|  3|letter0|  H|
#|  3|letter1|  I|
#|  4|letter0|  J|
#+---+-------+---+

Now we can just groupBy the num and pivot the DataFrame. Putting that all together, we get:

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .drop("val")\
    .select(
        "num",
        f.concat(f.lit("letter"),f.col("pos").cast("string")).alias("name"),
        f.expr("letters[pos]").alias("val")
    )\
    .groupBy("num").pivot("name").agg(f.first("val"))\
    .show()
#+---+-------+-------+-------+-------+
#|num|letter0|letter1|letter2|letter3|
#+---+-------+-------+-------+-------+
#|  1|      A|      B|      C|      D|
#|  3|      H|      I|   null|   null|
#|  2|      E|      F|      G|   null|
#|  4|      J|   null|   null|   null|
#+---+-------+-------+-------+-------+

How to resolve "Server Error in '/' Application" error?

The error message is quite clear: you have a configuration element in a web.config file in a subfolder of your web app that is not allowed at that level - OR you forgot to configure your web application as IIS application.

Example: you try to override application level settings like forms authentication parameters in a web.config in a subfolder of your application

How to convert an OrderedDict into a regular dict in python3

>>> from collections import OrderedDict
>>> OrderedDict([('method', 'constant'), ('data', '1.225')])
OrderedDict([('method', 'constant'), ('data', '1.225')])
>>> dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))
{'data': '1.225', 'method': 'constant'}
>>>

However, to store it in a database it'd be much better to convert it to a format such as JSON or Pickle. With Pickle you even preserve the order!

ASP.NET Core Web API exception handling

By adding your own "Exception Handling Middleware", makes it hard to reuse some good built-in logic of Exception Handler like send an "RFC 7807-compliant payload to the client" when an error happens.

What I made was to extend built-in Exception handler outside of the Startup.cs class to handle custom exceptions or override the behavior of existing ones. For example, an ArgumentException and convert into BadRequest without changing the default behavior of other exceptions:

on the Startup.cs add:

app.UseExceptionHandler("/error");

and extend ErrorController.cs with something like this:

using System;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;

namespace Api.Controllers
{
    [ApiController]
    [ApiExplorerSettings(IgnoreApi = true)]
    [AllowAnonymous]
    public class ErrorController : ControllerBase
    {
        [Route("/error")]
        public IActionResult Error(
            [FromServices] IWebHostEnvironment webHostEnvironment)
        {
            var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
            var exceptionType = context.Error.GetType();
            
            if (exceptionType == typeof(ArgumentException)
                || exceptionType == typeof(ArgumentNullException)
                || exceptionType == typeof(ArgumentOutOfRangeException))
            {
                if (webHostEnvironment.IsDevelopment())
                {
                    return ValidationProblem(
                        context.Error.StackTrace,
                        title: context.Error.Message);
                }

                return ValidationProblem(context.Error.Message);
            }

            if (exceptionType == typeof(NotFoundException))
            {
                return NotFound(context.Error.Message);
            }

            if (webHostEnvironment.IsDevelopment())
            {
                return Problem(
                    context.Error.StackTrace,
                    title: context.Error.Message
                    );
            }
            
            return Problem();
        }
    }
}

Note that:

  1. NotFoundException is a custom exception and all you need to do is throw new NotFoundException(null); or throw new ArgumentException("Invalid argument.");
  2. You should not serve sensitive error information to clients. Serving errors is a security risk.

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You can just controll it with a boolean, so you only call unbind if bind has been made

public void doBindService()
{
    if (!mIsBound)
    {
        bindService(new Intent(this, DMusic.class), Scon, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }
}

public void doUnbindService()
{
    if (mIsBound)
    {
        unbindService(Scon);
        mIsBound = false;
    }
}

If you only want to unbind it if it has been connected

public ServiceConnection Scon = new ServiceConnection() {

    public void onServiceConnected(ComponentName name, IBinder binder)
    {
        mServ = ((DMusic.ServiceBinder) binder).getService();
        mIsBound = true;
    }

    public void onServiceDisconnected(ComponentName name)
    {
        mServ = null;
    }
};

How to set a radio button in Android

btnDisplay.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

            // get selected radio button from radioGroup
        int selectedId = radioSexGroup.getCheckedRadioButtonId();

        // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);

        Toast.makeText(MyAndroidAppActivity.this,
            radioSexButton.getText(), Toast.LENGTH_SHORT).show();

    }

});

Find the index of a char in string?

"abcdefgh..".IndexOf("d")

returns 3

In general returns first occurrence index, if not present returns -1

HTML tag inside JavaScript

This is what I used for my countdown clock:

</SCRIPT>
<center class="auto-style19" style="height: 31px">
<Font face="blacksmith" size="large"><strong>
<SCRIPT LANGUAGE="JavaScript">
var header = "You have <I><font color=red>" 
+ getDaysUntilICD10() + "</font></I>&nbsp; "
header += "days until ICD-10 starts!"
document.write(header)
</SCRIPT>

The HTML inside of my script worked, though I could not explain why.

Why is semicolon allowed in this python snippet?

A quote from "When Pythons Attack"

Don't terminate all of your statements with a semicolon. It's technically legal to do this in Python, but is totally useless unless you're placing more than one statement on a single line (e.g., x=1; y=2; z=3).

Excel date to Unix timestamp

None of the current answers worked for me because my data was in this format from the unix side:

2016-02-02 19:21:42 UTC

I needed to convert this to Epoch to allow referencing other data which had epoch timestamps.

  1. Create a new column for the date part and parse with this formula

    =DATEVALUE(MID(A2,6,2) & "/" & MID(A2,9,2) & "/" & MID(A2,1,4)) 
    
  2. As other Grendler has stated here already, create another column

    =(B2-DATE(1970,1,1))*86400 
    
  3. Create another column with just the time added together to get total seconds:

    =(VALUE(MID(A2,12,2))*60*60+VALUE(MID(A2,15,2))*60+VALUE(MID(A2,18,2)))
    
  4. Create a last column that just adds the last two columns together:

    =C2+D2
    

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

Some of the Answers are correct, but in case of working with new xampp or with some one not working other answers try this:

just go to the xampp folder:

xampp/apache/conf/extra/httpd-xampp.c­onf

and if you are trying to access from local ip in your network so change,

 Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
    <Directory "C:/xampp/phpMyAdmin">
        AllowOverride AuthConfig
        Require local
        ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
    </Directory>

Change to :

 Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
    <Directory "C:/xampp/phpMyAdmin">
        AllowOverride AuthConfig
        Require all granted
        ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
    </Directory>

Note: this is just for text, for the security of the xampp has some search....

How can I compile and run c# program without using visual studio?

I use a batch script to compile and run C#:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc /out:%1 %2

@echo off

if errorlevel 1 (
    pause
    exit
)

start %1 %1

I call it like this:

C:\bin\csc.bat "C:\code\MyProgram.exe" "C:\code\MyProgram.cs"

I also have a shortcut in Notepad++, which you can define by going to Run > Run...:

C:\bin\csc.bat "$(CURRENT_DIRECTORY)\$(NAME_PART).exe" "$(FULL_CURRENT_PATH)"

I assigned this shortcut to my F5 key for maximum laziness.

How to execute multiple SQL statements from java

you can achieve that using Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.

Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. reference

When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.

  • JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.
  • The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.
  • The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement.
  • Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove.

EXAMPLE:

import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) throws Exception{
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection
      ("jdbc:derby://localhost:1527/testDb","name","pass");

      Statement stmt = con.createStatement
      (ResultSet.TYPE_SCROLL_SENSITIVE,
      ResultSet.CONCUR_UPDATABLE);
      String insertEmp1 = "insert into emp values
      (10,'jay','trainee')";
      String insertEmp2 = "insert into emp values
      (11,'jayes','trainee')";
      String insertEmp3 = "insert into emp values
      (12,'shail','trainee')";
      con.setAutoCommit(false);
      stmt.addBatch(insertEmp1);//inserting Query in stmt
      stmt.addBatch(insertEmp2);
      stmt.addBatch(insertEmp3);
      ResultSet rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows before batch execution= "
      + rs.getRow());
      stmt.executeBatch();
      con.commit();
      System.out.println("Batch executed");
      rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows after batch execution= "
      + rs.getRow());
   }
} 

refer http://www.tutorialspoint.com/javaexamples/jdbc_executebatch.htm

Google Play app description formatting

Another alternative to cut, copy and paste emojis is:

https://emojicut.com/

post ajax data to PHP and return data

 $.ajax({
            type: "POST",
            data: {data:the_id},
            url: "http://localhost/test/index.php/data/count_votes",
            success: function(data){
               //data will contain the vote count echoed by the controller i.e.  
                 "yourVoteCount"
              //then append the result where ever you want like
              $("span#votes_number").html(data); //data will be containing the vote count which you have echoed from the controller

                }
            });

in the controller

$data = $_POST['data'];  //$data will contain the_id
//do some processing
echo "yourVoteCount";

Clarification

i think you are confusing

{data:the_id}

with

success:function(data){

both the data are different for your own clarity sake you can modify it as

success:function(vote_count){
$(span#someId).html(vote_count);

How to use UIScrollView in Storyboard

After hours of trial and error, I've found a very easy way to put contents into scrollviews that are 'offscreen'. Tested with XCode 5 & iOS 7. You can do this almost entirely in Storyboard, using 2 small tricks/workarounds :

  1. Drag a viewcontroller onto your storyboard.
  2. Drag a scrollView on this viewController, for the demo you can leave its size default, covering the entire screen.
  3. Now comes trick 1 : before adding any element to the scrollView, drag in a regular 'view' (This view will be made larger than the screen, and will contain all the sub elements like buttons, labels, ...let's call it the 'enclosing view').
  4. Let this enclosing view's Y size in the size inspector to for example 800.
  5. Drop in a label onto the enclosing view, somewhere at Y position 200, name it 'label 1'.
  6. Trick 2 : make sure the enclosing view is selected (not the scrollView !), and set its Y position to for example -250, so you can add an item that is 'outside' the screen
  7. Drop in a label, somewhere at the bottom of the screen, name it 'label 2'. This label is actually 'off screen'.
  8. Reset the Y position of the enclosing view to 0, you'll no longer see label 2, as it was positioned off screen.

So far for the storyboard work, now you need to add a single line of code to the viewController's 'viewDidLoad' method to set the scrollViews contents so it contains the entire 'enclosing view'. I didn't find a way to do this in Storyboard:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.scrollView.contentSize = CGSizeMake(320, 800);
}

You can try doing this by adding a contentSize keyPath as a size to the scrollView in the Identity Inspector and setting it to (320, 1000).

I think Apple should make this easier in storyboard, in a TableViewController you can just scroll offscreen in Storyboard (just add 20 cells, and you'll see you can simply scroll), this should be possible with a ScrollViewController too.

Summernote image upload

I tested this code and Works

Javascript

<script>
$(document).ready(function() {
  $('#summernote').summernote({
    height: 200,
    onImageUpload: function(files, editor, welEditable) {
      sendFile(files[0], editor, welEditable);
    }
  });

  function sendFile(file, editor, welEditable) {
    data = new FormData();
    data.append("file", file);
    $.ajax({
      data: data,
      type: "POST",
      url: "Your URL POST (php)",
      cache: false,
      contentType: false,
      processData: false,
      success: function(url) {
        editor.insertImage(welEditable, url);
      }
    });
  }
});
</script>

PHP

if ($_FILES['file']['name']) {
  if (!$_FILES['file']['error']) {
    $name = md5(rand(100, 200));
    $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    $filename = $name.
    '.'.$ext;
    $destination = '/assets/images/'.$filename; //change this directory
    $location = $_FILES["file"]["tmp_name"];
    move_uploaded_file($location, $destination);
    echo 'http://test.yourdomain.al/images/'.$filename; //change this URL
  } else {
    echo $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
  }
}

Update:

After 0.7.0 onImageUpload should be inside callbacks option as mentioned by @tugberk

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

Generate a dummy-variable

another way you can do it is use

ifelse(year < 1965 , 1, 0)

PHP: Get the key from an array in a foreach loop

Use foreach with key and value.

Example:

foreach($samplearr as $key => $val) {
     print "<tr><td>" 
         . $key 
         . "</td><td>" 
         . $val['value1'] 
         . "</td><td>" 
         . $val['value2'] 
         . "</td></tr>";
}

How to write a CSS hack for IE 11?

So I found my own solution to this problem in the end.

After searching through Microsoft documentation I managed to find a new IE11 only style msTextCombineHorizontal

In my test, I check for IE10 styles and if they are a positive match, then I check for the IE11 only style. If I find it, then it's IE11+, if I don't, then it's IE10.

Code Example: Detect IE10 and IE11 by CSS Capability Testing (JSFiddle)

I will update the code example with more styles when I discover them.

NOTE: This will almost certainly identify IE12 and IE13 as "IE11", as those styles will probably carry forward. I will add further tests as new versions roll out, and hopefully be able to rely again on Modernizr.

I'm using this test for fallback behavior. The fallback behavior is just less glamorous styling, it doesn't have reduced functionality.

Get the current displaying UIViewController on the screen in AppDelegate.m

Way less code than all other solutions:

Objective-C version:

- (UIViewController *)getTopViewController {
    UIViewController *topViewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
    while (topViewController.presentedViewController) topViewController = topViewController.presentedViewController;

    return topViewController;
}

Swift 2.0 version: (credit goes to Steve.B)

func getTopViewController() -> UIViewController {
    var topViewController = UIApplication.sharedApplication().delegate!.window!!.rootViewController!
    while (topViewController.presentedViewController != nil) {
        topViewController = topViewController.presentedViewController!
    }
    return topViewController
}

Works anywhere in your app, even with modals.

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

Assuming your objective is to develop and test your xpath queries for screen maps. Then either use Chrome's developer tools. This allows you to run the xpath query to show the matches. Or in Firefox >9 you can do the same thing with the Web Developer Tools console. In earlier version use x-path-finder or Firebug.

How to check queue length in Python

Use queue.rear+1 to get the length of the queue

What is the minimum length of a valid international phone number?

EDIT 2015-06-27: Minimum is actually 8, including country code. My bad.

Original post

The minimum phone number that I use is 10 digits. International users should always be putting their country code, and as far as I know there are no countries with fewer than ten digits if you count country code.

More info here: https://en.wikipedia.org/wiki/Telephone_numbering_plan

How to concatenate multiple lines of output to one line?

The fastest and easiest ways I know to solve this problem:

When we want to replace the new line character \n with the space:

xargs < file

xargs has own limits on the number of characters per line and the number of all characters combined, but we can increase them. Details can be found by running this command: xargs --show-limits and of course in the manual: man xargs

When we want to replace one character with another exactly one character:

tr '\n' ' ' < file

When we want to replace one character with many characters:

tr '\n' '~' < file | sed s/~/many_characters/g

First, we replace the newline characters \n for tildes ~ (or choose another unique character not present in the text), and then we replace the tilde characters with any other characters (many_characters) and we do it for each tilde (flag g).

Check if table exists without using "select from"

There are several issues to note with the answers here:

1) INFORMATION_SCHEMA.TABLES does not include TEMPORARY tables.

2) Using any type of SHOW query, i.e. SHOW TABLES LIKE 'test_table', will force the return of a resultset to the client, which is undesired behavior for checking if a table exists server-side, from within a stored procedure that also returns a resultset.

3) As some users mentioned, you have to be careful with how you use SELECT 1 FROM test_table LIMIT 1.

If you do something like:

SET @table_exists = 0;
SET @table_exists = (SELECT 1 FROM test_table LIMIT 1);

You will not get the expected result if the table has zero rows.

Below is a stored procedure that will work for all tables (even TEMPORARY).

It can be used like:

SET @test_table = 'test_table';
SET @test_db = NULL;
SET @does_table_exist = NULL;

CALL DoesTableExist(@test_table, @test_db, @does_table_exist);

SELECT @does_table_exist;

The code:

/*
    p_table_name is required
    p_database_name is optional
        if NULL is given for p_database_name, then it defaults to the currently selected database
    p_does_table_exist
        The @variable to save the result to

    This procedure attempts to
        SELECT NULL FROM `p_database_name`.`p_table_name` LIMIT 0;

    If [SQLSTATE '42S02'] is raised, then
        SET p_does_table_exist = 0
    Else
        SET p_does_table_exist = 1

    Info on SQLSTATE '42S02' at:
        https://dev.mysql.com/doc/refman/5.7/en/server-error-reference.html#error_er_no_such_table
*/

DELIMITER $$

DROP PROCEDURE IF EXISTS DoesTableExist
$$

CREATE PROCEDURE         DoesTableExist (
    IN p_table_name VARCHAR(64),
    IN p_database_name VARCHAR(64),
    OUT p_does_table_exist TINYINT(1) UNSIGNED
)
BEGIN
    /* 793441 is used in this procedure for ensuring that user variables have unique names */

    DECLARE EXIT HANDLER FOR SQLSTATE '42S02'
    BEGIN
        SET p_does_table_exist = 0
        ;
    END
    ;


    IF p_table_name IS NULL THEN
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'DoesTableExist received NULL for p_table_name.';
    END IF;


    /* redirect resultset to a dummy variable */

    SET @test_select_sql_793441 = CONCAT(
        "SET @dummy_var_793441 = ("
            " SELECT"
                " NULL"
            " FROM ",
                IF(
                    p_database_name IS NULL,
                    "",
                    CONCAT(
                        "`",
                        REPLACE(p_database_name, "`", "``"),
                        "`."
                    )
                ),
                "`",
                REPLACE(p_table_name, "`", "``"),
                "`"
            " LIMIT 0"
        ")"
    )
    ;

    PREPARE _sql_statement FROM @test_select_sql_793441
    ;
    SET @test_select_sql_793441 = NULL
    ;
    EXECUTE _sql_statement
    ;
    DEALLOCATE PREPARE _sql_statement
    ;

    SET p_does_table_exist = 1
    ;
END
$$

DELIMITER ;

What's the purpose of META-INF?

If you're using JPA1, you might have to drop a persistence.xml file in there which specifies the name of a persistence-unit you might want to use. A persistence-unit provides a convenient way of specifying a set of metadata files, and classes, and jars that contain all classes to be persisted in a grouping.

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

// ...

EntityManagerFactory emf =
      Persistence.createEntityManagerFactory(persistenceUnitName);

See more here: http://www.datanucleus.org/products/datanucleus/jpa/emf.html

Java, looping through result set

List<String> sids = new ArrayList<String>();
List<String> lids = new ArrayList<String>();

String query = "SELECT rlink_id, COUNT(*)"
             + "FROM dbo.Locate  "
             + "GROUP BY rlink_id ";

Statement stmt = yourconnection.createStatement();
try {
    ResultSet rs4 = stmt.executeQuery(query);

    while (rs4.next()) {
        sids.add(rs4.getString(1));
        lids.add(rs4.getString(2));
    }
} finally {
    stmt.close();
}

String show[] = sids.toArray(sids.size());
String actuate[] = lids.toArray(lids.size());

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

There is a really simple tuturial here : http://my-wd-local.wikidot.com/otherapp:configure-virtualbox-shared-folders-in-a-windows-ho

telling to do:

sudo mkdir /mnt/vbox_share
sudo mount.vboxsf nameAddesAsShared /mnt/vbox_share

Get Substring - everything before certain char

One way to do this is to use String.Substring together with String.IndexOf:

int index = str.IndexOf('-');
string sub;
if (index >= 0)
{
    sub = str.Substring(0, index);
}
else
{
    sub = ... // handle strings without the dash
}

Starting at position 0, return all text up to, but not including, the dash.

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

I have the same issue, I solved the problem, just disabled

"BranchCache Service" in services.

Somehow windows updates, this service is triggered in startup, and uses 80 ports. When you check via netstat you could see the system is used this but couldnt understand which service is used.

Hidden Features of Java

String Parameterised Class Factory.

Class.forName( className ).newInstance();

Load a resource (property file, xml, xslt, image etc) from deployment jar file.

this.getClass().getClassLoader().getResourceAsStream( ... ) ;

Working with dictionaries/lists in R

To extend a little bit answer of Calimo I present few more things you may find useful while creating this quasi dictionaries in R:

a) how to return all the VALUES of the dictionary:

>as.numeric(foo)
[1] 12 22 33

b) check whether dictionary CONTAINS KEY:

>'tic' %in% names(foo)
[1] TRUE

c) how to ADD NEW key, value pair to dictionary:

c(foo,tic2=44)

results:

tic       tac       toe     tic2
12        22        33        44 

d) how to fulfill the requirement of REAL DICTIONARY - that keys CANNOT repeat(UNIQUE KEYS)? You need to combine b) and c) and build function which validates whether there is such key, and do what you want: e.g don't allow insertion, update value if the new differs from the old one, or rebuild somehow key(e.g adds some number to it so it is unique)

e) how to DELETE pair BY KEY from dictionary:

foo<-foo[which(foo!=foo[["tac"]])]

Datatable date sorting dd/mm/yyyy issue

Zaheer Ahmed' solution works fine if you have to deal with already uk formated date.

I had an issue with this solution because I had to manage US formated date.

I figured it out with this tiny change :

function parseDate(a) {
    var ukDatea = a.split('/');
    return (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
}

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
    "date-uk-pre": function ( a ) {
        return parseDate(a);
    },

    "date-uk-asc": function ( a, b ) {
        a = parseDate(a);
        b = parseDate(b);
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },

    "date-uk-desc": function ( a, b ) {
        a = parseDate(a);
        b = parseDate(b);
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
});

Followed by your "aoColumns" definition.

Generate a random date between two other dates

It's modified method of @(Tom Alsberg). I modified it to get date with milliseconds.

import random
import time
import datetime

def random_date(start_time_string, end_time_string, format_string, random_number):
    """
    Get a time at a proportion of a range of two formatted times.
    start and end should be strings specifying times formated in the
    given format (strftime-style), giving an interval [start, end].
    prop specifies how a proportion of the interval to be taken after
    start.  The returned time will be in the specified format.
    """
    dt_start = datetime.datetime.strptime(start_time_string, format_string)
    dt_end = datetime.datetime.strptime(end_time_string, format_string)

    start_time = time.mktime(dt_start.timetuple()) + dt_start.microsecond / 1000000.0
    end_time = time.mktime(dt_end.timetuple()) + dt_end.microsecond / 1000000.0

    random_time = start_time + random_number * (end_time - start_time)

    return datetime.datetime.fromtimestamp(random_time).strftime(format_string)

Example:

print TestData.TestData.random_date("2000/01/01 00:00:00.000000", "2049/12/31 23:59:59.999999", '%Y/%m/%d %H:%M:%S.%f', random.random())

Output: 2028/07/08 12:34:49.977963

changing source on html5 video tag

Using the <source /> tags proved difficult for me in Chrome 14.0.835.202 specifically, although it worked fine for me in FireFox. (This could be my lack of knowledge, but I thought an alternate solution might be useful anyway.) So, I ended up just using a <video /> tag and setting the src attribute right on the video tag itself. The canPlayVideo('<mime type>') function was used to determine whether or not the specific browser could play the input video. The following works in FireFox and Chrome.

Incidently, both FireFox and Chrome are playing the "ogg" format, although Chrome recommends "webm". I put the check for browser support of "ogg" first only because other posts have mentioned that FireFox prefers the ogg source first (i.e. <source src="..." type="video/ogg"/> ). But, I haven't tested (and highly doubt) whether or not it the order in the code makes any difference at all when setting the "src" on the video tag.

HTML

<body onload="setupVideo();">
    <video id="media" controls="true" preload="auto" src="">
    </video>
</body>

JavaScript

function setupVideo() {
       // You will probably get your video name differently
       var videoName = "http://video-js.zencoder.com/oceans-clip.mp4";

       // Get all of the uri's we support
       var indexOfExtension = videoName.lastIndexOf(".");
       //window.alert("found index of extension " + indexOfExtension);
       var extension = videoName.substr(indexOfExtension, videoName.length - indexOfExtension);
       //window.alert("extension is " + extension);
       var ogguri = encodeURI(videoName.replace(extension, ".ogv"));
       var webmuri = encodeURI(videoName.replace(extension, ".webm"));
       var mp4uri = encodeURI(videoName.replace(extension, ".mp4"));
       //window.alert(" URI is " + webmuri);


       // Get the video element
       var v = document.getElementById("media");
       window.alert(" media is " + v);

       // Test for support
       if (v.canPlayType("video/ogg")) {
            v.setAttribute("src", ogguri);
           //window.alert("can play ogg");
       }
       else if (v.canPlayType("video/webm")) {
           v.setAttribute("src", webmuri);
           //window.alert("can play webm");
       }
       else if (v.canPlayType("video/mp4")) {
           v.setAttribute("src", mp4uri);
           //window.alert("can play mp4");
       }
       else {
           window.alert("Can't play anything");
       }

      v.load();
      v.play();
  }

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

In my case I was running into issues with my $PATH on Linux. This can also happen on MacOS.

Check to see if /usr/bin/pip3 install package_name_goes_here works for you. If so then run which pip3 this will tell you which is the first directory that pip3 is installed in.

If it is something like /usr/local/bin/pip3 which is different from /usr/bin/pip3 then you may need to adjust your $PATH.

Run echo $PATH and copy the result.

The PATH is simply a colon separated list of directories that contain directories. Bash will always return the first instance of the program that you are attempting to execute. Move all the system directories upfront. Here is a list of some of the system directories:

/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin

If that fails then verify you have openssl installed by running openssl version -a if not then install openssl.

Removing whitespace between HTML elements when using line breaks

Another solution would be to use unconventional line breaks in places of spaces. This is similar to the first couple answers, and is an alternative way of lining up elements. It also is a super-edge-optimization technique because it replaces spaces in your markup with carriage returns.

<img
src="image1.jpg"><img
src="image2.jpg"><img
src="image3.jpg"><img
src="image4.jpg">

Note that there are no spaces in any of that code. Places where spaces are normally used in HTML are replaced with carriage returns. It's less verbose than both using comments and using whitespace like Paul de Vrieze recommended.

Credit to tech.co for this approach.

iOS - Dismiss keyboard when touching outside of UITextField

just use this code in your .m file it will resign the textfield when user tap outside of the textfield.

 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
  [textfield resignFirstResponder];
 }

How to use document.getElementByName and getElementByTag?

If you have given same text name for both of your Id and Name properties you can give like document.getElementByName('frmMain')[index] other wise object required error will come.And if you have only one table in your page you can use document.getElementBytag('table')[index].

EDIT:

You can replace the index according to your form, if its first form place 0 for index.

How to pass a PHP variable using the URL

I found this solution in "Super useful bits of PHP, Form and JavaScript code" at Skytopia.

Inside "page1.php" or "page1.html":

// Send the variables myNumber=1 and myFruit="orange" to the new PHP page...
<a href="page2c.php?myNumber=1&myFruit=orange">Send variables via URL!</a> 

    //or as I needed it.
    <a href='page2c.php?myNumber={$row[0]}&myFruit={$row[1]}'>Send variables</a>

Inside "page2c.php":

<?php
    // Retrieve the URL variables (using PHP).
    $num = $_GET['myNumber'];
    $fruit = $_GET['myFruit'];
    echo "Number: ".$num."  Fruit: ".$fruit;
?>

How do you set a default value for a MySQL Datetime column?

Here is how to do it on MySQL 5.1:

ALTER TABLE `table_name` CHANGE `column_name` `column_name` 
TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;

I have no clue why you have to enter the column name twice.

How to remove all listeners in an element?

I think that the fastest way to do this is to just clone the node, which will remove all event listeners:

var old_element = document.getElementById("btn");
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);

Just be careful, as this will also clear event listeners on all child elements of the node in question, so if you want to preserve that you'll have to resort to explicitly removing listeners one at a time.

How can I mimic the bottom sheet from the Maps app?

Maybe you can try my answer https://github.com/AnYuan/AYPannel, inspired by Pulley. Smooth transition from moving the drawer to scrolling the list. I added a pan gesture on the container scroll view, and set shouldRecognizeSimultaneouslyWithGestureRecognizer to return YES. More detail in my github link above. Wish to help.

Is it better to use NOT or <> when comparing values?

The latter (<>), because the meaning of the former isn't clear unless you have a perfect understanding of the order of operations as it applies to the Not and = operators: a subtlety which is easy to miss.

How to create an HTTPS server in Node.js?

You can use also archive this with the Fastify framework:

const { readFileSync } = require('fs')
const Fastify = require('fastify')

const fastify = Fastify({
  https: {
    key: readFileSync('./test/asset/server.key'),
    cert: readFileSync('./test/asset/server.cert')
  },
  logger: { level: 'debug' }
})

fastify.listen(8080)

(and run openssl req -nodes -new -x509 -keyout server.key -out server.cert to create the files if you need to write tests)

MVC: How to Return a String as JSON

Use the following code in your controller:

return Json(new { success = string }, JsonRequestBehavior.AllowGet);

and in JavaScript:

success: function (data) {
    var response = data.success;
    ....
}

Cell spacing in UICollectionView

I have a horizontal UICollectionView and subclassed UICollectionViewFlowLayout. The collection view has large cells, and only shows one row of them at a time, and the collection view fits the width of the screen.

I tried iago849's answer and it worked, but then I found out I didn't even need his answer. For some reason, setting the minimumInterItemSpacing does nothing. The spacing between my items/cells can be entirely controlled by minimumLineSpacing.

Not sure why it works this way, but it works.

C++ class forward declaration

In order for new T to compile, T must be a complete type. In your case, when you say new tile_tree_apple inside the definition of tile_tree::tick, tile_tree_apple is incomplete (it has been forward declared, but its definition is later in your file). Try moving the inline definitions of your functions to a separate source file, or at least move them after the class definitions.

Something like:

class A
{
    void f1();
    void f2();
};
class B
{
   void f3();
   void f4();
};

inline void A::f1() {...}
inline void A::f2() {...}
inline void B::f3() {...}
inline void B::f4() {...}

When you write your code this way, all references to A and B in these methods are guaranteed to refer to complete types, since there are no more forward references!

How do you calculate log base 2 in Java for integers?

Some cases just worked when I used Math.log10:

public static double log2(int n)
{
    return (Math.log10(n) / Math.log10(2));
}

How can I search sub-folders using glob.glob module?

The command rglob will do an infinite recursion down the deepest sub-level of your directory structure. If you only want one level deep, then do not use it, however.

I realize the OP was talking about using glob.glob. I believe this answers the intent, however, which is to search all subfolders recursively.

The rglob function recently produced a 100x increase in speed for a data processing algorithm which was using the folder structure as a fixed assumption for the order of data reading. However, with rglob we were able to do a single scan once through all files at or below a specified parent directory, save their names to a list (over a million files), then use that list to determine which files we needed to open at any point in the future based on the file naming conventions only vs. which folder they were in.

Javascript add method to object

You can make bar a function making it a method.

Foo.bar = function(passvariable){  };

As a property it would just be assigned a string, data type or boolean

Foo.bar = "a place";

JPanel vs JFrame in Java

JFrame is the window; it can have one or more JPanel instances inside it. JPanel is not the window.

You need a Swing tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/

Adding a favicon to a static HTML page

as an additional note that may help someone some day.

You can not echo anything to the page before:

Hello
<link rel="shortcut icon" type="image/ico" href="/webico.ico"/>
<link rel="shortcut icon" type="image/ico" href="/webico.ico"/>

will not load ico

<link rel="shortcut icon" type="image/ico" href="/webico.ico"/>
<link rel="shortcut icon" type="image/ico" href="/webico.ico"/>
Hello

works fine

How to calculate the sum of the datatable column in asp.net?

 this.LabelControl.Text = datatable.AsEnumerable()
    .Sum(x => x.Field<int>("Amount"))
    .ToString();

If you want to filter the results:

 this.LabelControl.Text = datatable.AsEnumerable()
    .Where(y => y.Field<string>("SomeCol") != "foo")
    .Sum(x => x.Field<int>("MyColumn") )
    .ToString();

How to import classes defined in __init__.py

Yes, it is possible. You might also want to define __all__ in __init__.py files. It's a list of modules that will be imported when you do

from lib import *

Change text color with Javascript?

use ONLY

function init() { 
    about = document.getElementById("about");
    about.style.color = 'blue';
}

.innerHTML() sets or gets the HTML syntax describing the element's descendants., All you need is an object here.

Demo

C# Regex for Guid

I use an easier regex pattern

^[0-9A-Fa-f\-]{36}$

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

Convert iterator to pointer?

Vector is a template class and it is not safe to convert the contents of a class to a pointer : You cannot inherit the vector class to add this new functionality. and changing the function parameter is actually a better idea. Jst create another vector of int vector temp_foo (foo.begin[X],foo.end()); and pass this vector to you functions

how to update the multiple rows at a time using linq to sql?

To update one column here are some syntax options:

Option 1

var ls=new int[]{2,3,4};
using (var db=new SomeDatabaseContext())
{
    var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
    some.ForEach(a=>a.status=true);
    db.SubmitChanges();
}

Option 2

using (var db=new SomeDatabaseContext())
{
     db.SomeTable
       .Where(x=>ls.Contains(x.friendid))
       .ToList()
       .ForEach(a=>a.status=true);

     db.SubmitChanges();
}

Option 3

using (var db=new SomeDatabaseContext())
{
    foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
    {
        some.status=true;
    }
    db.SubmitChanges();
}

Update

As requested in the comment it might make sense to show how to update multiple columns. So let's say for the purpose of this exercise that we want not just to update the status at ones. We want to update name and status where the friendid is matching. Here are some syntax options for that:

Option 1

var ls=new int[]{2,3,4};
var name="Foo";
using (var db=new SomeDatabaseContext())
{
    var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
    some.ForEach(a=>
                    {
                        a.status=true;
                        a.name=name;
                    }
                );
    db.SubmitChanges();
}

Option 2

using (var db=new SomeDatabaseContext())
{
    db.SomeTable
        .Where(x=>ls.Contains(x.friendid))
        .ToList()
        .ForEach(a=>
                    {
                        a.status=true;
                        a.name=name;
                    }
                );
    db.SubmitChanges();
}

Option 3

using (var db=new SomeDatabaseContext())
{
    foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
    {
        some.status=true;
        some.name=name;
    }
    db.SubmitChanges();
}

Update 2

In the answer I was using LINQ to SQL and in that case to commit to the database the usage is:

db.SubmitChanges();

But for Entity Framework to commit the changes it is:

db.SaveChanges()

How to set session attribute in java?

I am try to catch your point.I hope it is helpful.....

if (session.isNew()){
     title = "Welcome to my website";
     session.setAttribute(userIDKey, userID);

How can I Remove .DS_Store files from a Git repository?

Remove existing files from the repository:

find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch

Add the line

.DS_Store

to the file .gitignore, which can be found at the top level of your repository (or created if it isn't there already). You can do this easily with this command in the top directory

echo .DS_Store >> .gitignore

Then

git add .gitignore
git commit -m '.DS_Store banished!'

How to make php display \t \n as tab and new line instead of characters

"\t" not '\t', php doesnt escape in single quotes

Changing Background Image with CSS3 Animations

Works for me. Notice the use of background-image for transition.

#poster-img {
  background-repeat: no-repeat;
  background-position: center;
  position: absolute;
  overflow: hidden;
  -webkit-transition: background-image 1s ease-in-out;
  transition: background-image 1s ease-in-out;
}

How to send UTF-8 email?

You can add header "Content-Type: text/html; charset=UTF-8" to your message body.

$headers = "Content-Type: text/html; charset=UTF-8";

If you use native mail() function $headers array will be the 4th parameter mail($to, $subject, $message, $headers)

If you user PEAR Mail::factory() code will be:

$smtp = Mail::factory('smtp', $params);

$mail = $smtp->send($to, $headers, $body);

Variables within app.config/web.config

Usally, I end up writing a static class with properties to access each of the settings of my web.config.

public static class ConfigManager 
{
    public static string MyBaseDir
    {
        return ConfigurationManager.AppSettings["MyBaseDir"].toString();
    }

    public static string Dir1
    {
        return MyBaseDir + ConfigurationManager.AppSettings["Dir1"].toString();
    }

}

Usually, I also do type conversions when required in this class. It allows to have a typed access to your config, and if settings change, you can edit them in only one place.

Usually, replacing settings with this class is relatively easy and provides a much greater maintainability.

android - how to convert int to string and place it in a EditText?

try Integer.toString(integer value); method as

ed = (EditText)findViewById(R.id.box);
int x = 10;
ed.setText(Integer.toString(x));

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

Got this exception when maintaining very old application on Server 2003 using Asp classic on IIS6 with Oracle 9.2.0.1. The fix is by updating oracle to 9.2.0.6.

Download files from server php

To read directory contents you can use readdir() and use a script, in my example download.php, to download files

if ($handle = opendir('/path/to/your/dir/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
        }
    }
    closedir($handle);
}

In download.php you can force browser to send download data, and use basename() to make sure client does not pass other file name like ../config.php

$file = basename($_GET['file']);
$file = '/path/to/your/dir/'.$file;

if(!file_exists($file)){ // file does not exist
    die('file not found');
} else {
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");

    // read the file from disk
    readfile($file);
}

Why am I getting a " Traceback (most recent call last):" error?

I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:

TypeError: 'int' object is not callable

My code for Python 3 is as follows:

# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error

raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: {M_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: {F_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: {G_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: {inches_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    # Printing error in the line below
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

I hope this helps.

Best dynamic JavaScript/JQuery Grid

Have a look at agiletoolkit.org as this has a simple to use CRUD which supports 2,4,6,7,9,10 and 12 out of the box (uses Ajax to defender the grid when adding,deleting data and it integrates with jquery.

I would post some examples but on an iPad at the moment.

What is the default scope of a method in Java?

Without an access modifier, a class member is accessible throughout the package in which it's declared. You can learn more from the Java Language Specification, §6.6.

Members of an interface are always publicly accessible, whether explicitly declared or not.

How to change the sender's name or e-mail address in mutt?

before you send the email you can press <ESC> f (Escape followed by f) to change the From: Address.

Constraint: This only works if you use mutt in curses mode and do not wan't to script it or if you want to change the address permanent. Then the other solutions are way better!

Is there a function to copy an array in C/C++?

I like the answer of Ed S., but this only works for fixed size arrays and not when the arrays are defined as pointers.

So, the C++ solution where the arrays are defined as pointers:

#include<algorithm>
...
const int bufferSize = 10;
char* origArray, newArray;
std::copy(origArray, origArray + bufferSize, newArray);

Note: No need to deduct buffersize with 1:

  1. Copies all elements in the range [first, last) starting from first and proceeding to last - 1

See: https://en.cppreference.com/w/cpp/algorithm/copy

When and why do I need to use cin.ignore() in C++?

As pointed right by many other users. It's because there may be whitespace or a newline character.

Consider the following code, it removes all the duplicate characters from a given string.

#include <bits/stdc++.h>
using namespace std;

int main() {
    int t;
    cin>>t;
    cin.ignore(); //Notice that this cin.ignore() is really crucial for any extra whitespace or newline character
    while(t--){
        vector<int> v(256,0);
        string s;
        getline(cin,s);
        string s2;
        for(int i=0;i<s.size();i++){
            if (v[s[i]]) continue;
            else{
                s2.push_back(s[i]);
                v[s[i]]++;
            }
        }
        cout<<s2<<endl;
    }
    return 0;
}

So, You get the point that it will ignore those unwanted inputs and will get the job done.

Windows batch: echo without new line

Using: echo | set /p= or <NUL set /p= will both work to suppress the newline.

However, this can be very dangerous when writing more advanced scripts when checking the ERRORLEVEL becomes important as setting set /p= without specifying a variable name will set the ERRORLEVEL to 1.

A better approach would be to just use a dummy variable name like so:
echo | set /p dummyName=Hello World

This will produce exactly what you want without any sneaky stuff going on in the background as I had to find out the hard way, but this only works with the piped version; <NUL set /p dummyName=Hello will still raise the ERRORLEVEL to 1.

How to read the Stock CPU Usage data

This should be the Unix load average. Wikipedia has a nice article about this.

The numbers show the average load of the CPU in different time intervals. From left to right: last minute/last five minutes/last fifteen minutes

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

So I was running 300 PHP processes simulatenously and was getting a rate of between 60 - 90 per second (my process involves 3x queries). I upped it to 400 and this fell to about 40-50 per second. I dropped it to 200 and am back to between 60 and 90!

So my advice to anyone with this problem is experiment with running less than more and see if it improves. There will be less memory and CPU being used so the processes that do run will have greater ability and the speed may improve.

Removing leading and trailing spaces from a string

Why complicate?

std::string removeSpaces(std::string x){
    if(x[0] == ' ') { x.erase(0, 1); return removeSpaces(x); }
    if(x[x.length() - 1] == ' ') { x.erase(x.length() - 1, x.length()); return removeSpaces(x); }
    else return x;
}

This works even if boost was to fail, no regex, no weird stuff nor libraries.

EDIT: Fix for M.M.'s comment.

Adding values to an array in java

put x=0 outside the for loop that is the problem

How can I produce an effect similar to the iOS 7 blur view?

This is a solution that you can see in the vidios of the WWDC. You have to do a Gaussian Blur, so the first thing you have to do is to add a new .m and .h file with the code i'm writing here, then you have to make and screen shoot, use the desired effect and add it to your view, then your UITable UIView or what ever has to be transparent, you can play with applyBlurWithRadius, to archive the desired effect, this call works with any UIImage.

At the end the blured image will be the background and the rest of the controls above has to be transparent.

For this to work you have to add the next libraries:

Acelerate.framework,UIKit.framework,CoreGraphics.framework

I hope you like it.

Happy coding.

    //Screen capture.
    UIGraphicsBeginImageContext(self.view.bounds.size);

    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(c, 0, 0);
    [self.view.layer renderInContext:c];

    UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();
    viewImage = [viewImage applyLightEffect];

    UIGraphicsEndImageContext();

    //.h FILE
    #import <UIKit/UIKit.h>

    @interface UIImage (ImageEffects)

   - (UIImage *)applyLightEffect;
   - (UIImage *)applyExtraLightEffect;
   - (UIImage *)applyDarkEffect;
   - (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor;

   - (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage;

   @end

    //.m FILE
    #import "cGaussianEffect.h"
    #import <Accelerate/Accelerate.h>
    #import <float.h>


     @implementation UIImage (ImageEffects)


    - (UIImage *)applyLightEffect
    {
        UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0.3];
        return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
    }


    - (UIImage *)applyExtraLightEffect
    {
        UIColor *tintColor = [UIColor colorWithWhite:0.97 alpha:0.82];
        return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
    }


    - (UIImage *)applyDarkEffect
    {
        UIColor *tintColor = [UIColor colorWithWhite:0.11 alpha:0.73];
        return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
    }


    - (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor
    {
        const CGFloat EffectColorAlpha = 0.6;
        UIColor *effectColor = tintColor;
        int componentCount = CGColorGetNumberOfComponents(tintColor.CGColor);
        if (componentCount == 2) {
            CGFloat b;
            if ([tintColor getWhite:&b alpha:NULL]) {
                effectColor = [UIColor colorWithWhite:b alpha:EffectColorAlpha];
            }
        }
        else {
            CGFloat r, g, b;
            if ([tintColor getRed:&r green:&g blue:&b alpha:NULL]) {
                effectColor = [UIColor colorWithRed:r green:g blue:b alpha:EffectColorAlpha];
            }
        }
        return [self applyBlurWithRadius:10 tintColor:effectColor saturationDeltaFactor:-1.0 maskImage:nil];
    }


    - (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage
    {
        if (self.size.width < 1 || self.size.height < 1) {
            NSLog (@"*** error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self);
            return nil;
        }
        if (!self.CGImage) {
            NSLog (@"*** error: image must be backed by a CGImage: %@", self);
            return nil;
        }
        if (maskImage && !maskImage.CGImage) {
            NSLog (@"*** error: maskImage must be backed by a CGImage: %@", maskImage);
            return nil;
        }

        CGRect imageRect = { CGPointZero, self.size };
        UIImage *effectImage = self;

        BOOL hasBlur = blurRadius > __FLT_EPSILON__;
        BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__;
        if (hasBlur || hasSaturationChange) {
            UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
            CGContextRef effectInContext = UIGraphicsGetCurrentContext();
            CGContextScaleCTM(effectInContext, 1.0, -1.0);
            CGContextTranslateCTM(effectInContext, 0, -self.size.height);
            CGContextDrawImage(effectInContext, imageRect, self.CGImage);

            vImage_Buffer effectInBuffer;
            effectInBuffer.data     = CGBitmapContextGetData(effectInContext);
            effectInBuffer.width    = CGBitmapContextGetWidth(effectInContext);
            effectInBuffer.height   = CGBitmapContextGetHeight(effectInContext);
            effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext);

            UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
            CGContextRef effectOutContext = UIGraphicsGetCurrentContext();
            vImage_Buffer effectOutBuffer;
            effectOutBuffer.data     = CGBitmapContextGetData(effectOutContext);
            effectOutBuffer.width    = CGBitmapContextGetWidth(effectOutContext);
            effectOutBuffer.height   = CGBitmapContextGetHeight(effectOutContext);
            effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext);

            if (hasBlur) {
                CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale];
                NSUInteger radius = floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5);
                if (radius % 2 != 1) {
                    radius += 1;
                }
                vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
                vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
                vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
            }
            BOOL effectImageBuffersAreSwapped = NO;
            if (hasSaturationChange) {
                CGFloat s = saturationDeltaFactor;
                CGFloat floatingPointSaturationMatrix[] = {
                    0.0722 + 0.9278 * s,  0.0722 - 0.0722 * s,  0.0722 - 0.0722 * s,  0,
                    0.7152 - 0.7152 * s,  0.7152 + 0.2848 * s,  0.7152 - 0.7152 * s,  0,
                    0.2126 - 0.2126 * s,  0.2126 - 0.2126 * s,  0.2126 + 0.7873 * s,  0,
                                  0,                    0,                    0,  1,
                };
                const int32_t divisor = 256;
                NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix)/sizeof(floatingPointSaturationMatrix[0]);
                int16_t saturationMatrix[matrixSize];
                for (NSUInteger i = 0; i < matrixSize; ++i) {
                    saturationMatrix[i] = (int16_t)roundf(floatingPointSaturationMatrix[i] * divisor);
                }
                if (hasBlur) {
                    vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
                    effectImageBuffersAreSwapped = YES;
                }
                else {
                    vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
                }
            }
            if (!effectImageBuffersAreSwapped)
                effectImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();

            if (effectImageBuffersAreSwapped)
                effectImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }

        UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
        CGContextRef outputContext = UIGraphicsGetCurrentContext();
        CGContextScaleCTM(outputContext, 1.0, -1.0);
        CGContextTranslateCTM(outputContext, 0, -self.size.height);

        CGContextDrawImage(outputContext, imageRect, self.CGImage);

        if (hasBlur) {
            CGContextSaveGState(outputContext);
            if (maskImage) {
                CGContextClipToMask(outputContext, imageRect, maskImage.CGImage);
            }
            CGContextDrawImage(outputContext, imageRect, effectImage.CGImage);
            CGContextRestoreGState(outputContext);
        }

        if (tintColor) {
            CGContextSaveGState(outputContext);
            CGContextSetFillColorWithColor(outputContext, tintColor.CGColor);
            CGContextFillRect(outputContext, imageRect);
            CGContextRestoreGState(outputContext);
        }

        UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return outputImage;
    }

How can I specify a local gem in my Gemfile?

In order to use local gem repository in a Rails project, follow the steps below:

  1. Check if your gem folder is a git repository (the command is executed in the gem folder)

    git rev-parse --is-inside-work-tree
    
  2. Getting repository path (the command is executed in the gem folder)

    git rev-parse --show-toplevel
    
  3. Setting up a local override for the rails application

    bundle config local.GEM_NAME /path/to/local/git/repository
    

    where GEM_NAME is the name of your gem and /path/to/local/git/repository is the output of the command in point 2

  4. In your application Gemfile add the following line:

    gem 'GEM_NAME', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
    
  5. Running bundle install should give something like this:

    Using GEM_NAME (0.0.1) from git://github.com/GEM_NAME/GEM_NAME.git (at /path/to/local/git/repository) 
    

    where GEM_NAME is the name of your gem and /path/to/local/git/repository from point 2

  6. Finally, run bundle list, not gem list and you should see something like this:

    GEM_NAME (0.0.1 5a68b88)
    

    where GEM_NAME is the name of your gem


A few important cases I am observing using:

Rails 4.0.2  
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux] 
Ubuntu 13.10  
RubyMine 6.0.3
  • It seems RubyMine is not showing local gems as an external library. More information about the bug can be found here and here
  • When I am changing something in the local gem, in order to be loaded in the rails application I should stop/start the rails server
  • If I am changing the version of the gem, stopping/starting the Rails server gives me an error. In order to fix it, I am specifying the gem version in the rails application Gemfile like this:

    gem 'GEM_NAME', '0.0.2', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
    

git - Server host key not cached

I too had the same issue when I was trying to clone a repository on my Windows 7 machine. I tried most of the answers mentioned here. None of them worked for me.

What worked for me was, running the Pageant (Putty authentication agent) program. Once the Pageant was running in the background I was able to clone, push & pull from/to the repository. This worked for me, may be because I've setup my public key such that whenever it is used for the first time a password is required & the Pageant starts up.

Getting list of lists into pandas DataFrame

With approach explained by EdChum above, the values in the list are shown as rows. To show the values of lists as columns in DataFrame instead, simply use transpose() as following:

table = [[1 , 2], [3, 4]]
df = pd.DataFrame(table)
df = df.transpose()
df.columns = ['Heading1', 'Heading2']

The output then is:

      Heading1  Heading2
0         1        3
1         2        4

Maven: Failed to read artifact descriptor

You can always try mvn -U clean install

-U forces a check for updated releases and snapshots on remote repositories.

Python os.path.join() on a list

Assuming join wasn't designed that way (which it is, as ATOzTOA pointed out), and it only took two parameters, you could still use the built-in reduce:

>>> reduce(os.path.join,["c:/","home","foo","bar","some.txt"])
'c:/home\\foo\\bar\\some.txt'

Same output like:

>>> os.path.join(*["c:/","home","foo","bar","some.txt"])
'c:/home\\foo\\bar\\some.txt' 

Just for completeness and educational reasons (and for other situations where * doesn't work).

Hint for Python 3

reduce was moved to the functools module.

java- reset list iterator to first element of the list

You can call listIterator method again to get an instance of iterator pointing at beginning of list:

iter = list.listIterator();

Remove array element based on object property

You can use lodash's findIndex to get the index of the specific element and then splice using it.

myArray.splice(_.findIndex(myArray, function(item) {
    return item.value === 'money';
}), 1);

Update

You can also use ES6's findIndex()

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

const itemToRemoveIndex = myArray.findIndex(function(item) {
  return item.field === 'money';
});

// proceed to remove an item only if it exists.
if(itemToRemoveIndex !== -1){
  myArray.splice(itemToRemoveIndex, 1);
}

text flowing out of div

You need to apply the following CSS property to the container block (div):

overflow-wrap: break-word;

According to the specifications (source CSS | MDN):

The overflow-wrap CSS property specifies whether or not the browser should insert line breaks within words to prevent text from overflowing its content box.

With the value set to break-word

To prevent overflow, normally unbreakable words may be broken at arbitrary points if there are no otherwise acceptable break points in the line.

Worth mentioning...

The property was originally a nonstandard and unprefixed Microsoft extension called word-wrap, and was implemented by most browsers with the same name. It has since been renamed to overflow-wrap, with word-wrap being an alias.


If you care about legacy browsers support it's worth specifying both:

word-wrap    : break-word;
overflow-wrap: break-word;

Ex. IE9 does not recognize overflow-wrap but works fine with word-wrap

Redirecting from HTTP to HTTPS with PHP

This is a good way to do it:

<?php
if (!(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || 
   $_SERVER['HTTPS'] == 1) ||  
   isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&   
   $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
{
   $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
   header('HTTP/1.1 301 Moved Permanently');
   header('Location: ' . $redirect);
   exit();
}
?>

What is the easiest way to ignore a JPA field during persistence?

To ignore a field, annotate it with @Transient so it will not be mapped by hibernate.
Source: Hibernate Annotations.

Play/pause HTML 5 video using JQuery

I also made it work like this:

$(window).scroll(function() {
    if($(window).scrollTop() > 0)
        document.querySelector('#video').pause();
    else
        document.querySelector('#video').play();
});

Having Django serve downloadable files

def qrcodesave(request): 
    import urllib2;   
    url ="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chl=s&chld=H|0"; 
    opener = urllib2.urlopen(url);  
    content_type = "application/octet-stream"
    response = HttpResponse(opener.read(), content_type=content_type)
    response["Content-Disposition"]= "attachment; filename=aktel.png"
    return response 

How to hide element using Twitter Bootstrap and show it using jQuery?

Razz's answer is good if you're willing to rewrite what you have done.

Was in the same trouble and worked it out with the following:

_x000D_
_x000D_
/**_x000D_
 * The problem: https://github.com/twbs/bootstrap/issues/9881_x000D_
 * _x000D_
 * This script enhances jQuery's methods: show and hide dynamically._x000D_
 * If the element was hidden by bootstrap's css class 'hide', remove it first._x000D_
 * Do similar in overriding the method 'hide'._x000D_
 */_x000D_
!function($) {_x000D_
    "use strict";_x000D_
_x000D_
    var oldShowHide = {'show': $.fn.show, 'hide': $.fn.hide};_x000D_
    $.fn.extend({_x000D_
        show: function() {_x000D_
            this.each(function(index) {_x000D_
                var $element = $(this);_x000D_
                if ($element.hasClass('hide')) {_x000D_
                    $element.removeClass('hide');_x000D_
                }_x000D_
            });_x000D_
            return oldShowHide.show.call(this);_x000D_
        },_x000D_
        hide: function() {_x000D_
            this.each(function(index) {_x000D_
                var $element = $(this);_x000D_
                if ($element.hasClass('show')) {_x000D_
                    $element.removeClass('show');_x000D_
                }_x000D_
            });_x000D_
            return oldShowHide.hide.call(this);_x000D_
        }_x000D_
    });_x000D_
}(window.jQuery);
_x000D_
_x000D_
_x000D_

Throw it away when Bootstrap comes with a fix for this problem.

Get event listeners attached to node using addEventListener

Chrome DevTools, Safari Inspector and Firebug support getEventListeners(node).

getEventListeners(document)

Why do we need to install gulp globally and locally?

TLDR; Here's why:

The reason this works is because gulp tries to run your gulpfile.js using your locally installed version of gulp, see here. Hence the reason for a global and local install of gulp.

Essentially, when you install gulp locally the script isn't in your PATH and so you can't just type gulp and expect the shell to find the command. By installing it globally the gulp script gets into your PATH because the global node/bin/ directory is most likely on your path.

To respect your local dependencies though, gulp will use your locally installed version of itself to run the gulpfile.js.

removing table border

To remove from all tables, (add this to the head or external style sheet)

<style type="text/css">
table td{
border:none;
}
</style>

The image shows where the style is coming from (Firebug)

HTML5 video - show/hide controls programmatically

Here's how to do it:

var myVideo = document.getElementById("my-video")    
myVideo.controls = false;

Working example: https://jsfiddle.net/otnfccgu/2/

See all available properties, methods and events here: https://www.w3schools.com/TAGs/ref_av_dom.asp

SQL Server stored procedure parameters

I'm going on a bit of an assumption here, but I'm assuming the logic inside the procedure gets split up via task. And you cant have nullable parameters as @Yuck suggested because of the dynamics of the parameters?

So going by my assumption

If TaskName = "Path1" Then Something

If TaskName = "Path2" Then Something Else

My initial thought is, if you have separate functions with business-logic you need to create, and you can determine that you have say 5-10 different scenarios, rather write individual stored procedures as needed, instead of trying one huge one solution fits all approach. Might get a bit messy to maintain.

But if you must...

Why not try dynamic SQL, as suggested by @E.J Brennan (Forgive me, i haven't touched SQL in a while so my syntax might be rusty) That being said i don't know if its the best approach, but could this could possibly meet your needs?

CREATE PROCEDURE GetTaskEvents
    @TaskName varchar(50)
    @Values varchar(200)
AS
BEGIN
  DECLARE @SQL VARCHAR(MAX)

  IF @TaskName = 'Something'
  BEGIN
    @SQL = 'INSERT INTO.....' + CHAR(13)
    @SQL += @Values + CHAR(13) 
  END

  IF @TaskName = 'Something Else'
  BEGIN
    @SQL = 'DELETE SOMETHING WHERE' + CHAR(13)
    @SQL += @Values + CHAR(13) 
  END

  PRINT(@SQL)
  EXEC(@SQL)    
END

(The CHAR(13) adds a new line.. an old habbit i picked up somewhere, used to help debugging/reading dynamic procedures when running SQL profiler.)

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

This is an elaborate version, to help you understand

function setVolatileBehavior(elem, onColor, offColor, promptText){ //changed spelling of function name to be the same as name used at invocation below
elem.addEventListener("change", function(){
    if (document.activeElement == elem && elem.value==promptText){
        elem.value='';
        elem.style.color = onColor;
    }
    else if (elem.value==''){
        elem.value=promptText;
        elem.style.color = offColor;
    }
});
elem.addEventListener("blur", function(){
    if (document.activeElement == elem && elem.value==promptText){
        elem.value='';
        elem.style.color = onColor;
    }
    else if (elem.value==''){
        elem.value=promptText;
        elem.style.color = offColor;
    }
});
elem.addEventListener("focus", function(){
    if (document.activeElement == elem && elem.value==promptText){
        elem.value='';
        elem.style.color = onColor;
    }
    else if (elem.value==''){
        elem.value=promptText;
        elem.style.color = offColor;
    }
});
elem.value=promptText;
elem.style.color=offColor;
}

Use like this:

setVolatileBehavior(document.getElementById('yourElementID'),'black','gray','Name');

Sort JavaScript object by key

There's a great project by @sindresorhus called sort-keys that works awesome.

You can check its source code here:

https://github.com/sindresorhus/sort-keys

Or you can use it with npm:

$ npm install --save sort-keys

Here are also code examples from his readme

const sortKeys = require('sort-keys');

sortKeys({c: 0, a: 0, b: 0});
//=> {a: 0, b: 0, c: 0}

sortKeys({b: {b: 0, a: 0}, a: 0}, {deep: true});
//=> {a: 0, b: {a: 0, b: 0}}

sortKeys({c: 0, a: 0, b: 0}, {
    compare: (a, b) => -a.localeCompare(b)
});
//=> {c: 0, b: 0, a: 0}

Is there a way to word-wrap long words in a div?

Reading the original comment, rutherford is looking for a cross-browser way to wrap unbroken text (inferred by his use of word-wrap for IE, designed to break unbroken strings).

/* Source: http://snipplr.com/view/10979/css-cross-browser-word-wrap */
.wordwrap { 
   white-space: pre-wrap;      /* CSS3 */   
   white-space: -moz-pre-wrap; /* Firefox */    
   white-space: -pre-wrap;     /* Opera <7 */   
   white-space: -o-pre-wrap;   /* Opera 7 */    
   word-wrap: break-word;      /* IE */
}

I've used this class for a bit now, and works like a charm. (note: I've only tested in FireFox and IE)

How do you write a migration to rename an ActiveRecord model and its table in Rails?

The other answers and comments covered table renaming, file renaming, and grepping through your code.

I'd like to add a few more caveats:

Let's use a real-world example I faced today: renaming a model from 'Merchant' to 'Business.'

  • Don't forget to change the names of dependent tables and models in the same migration. I changed my Merchant and MerchantStat models to Business and BusinessStat at the same time. Otherwise I'd have had to do way too much picking and choosing when performing search-and-replace.
  • For any other models that depend on your model via foreign keys, the other tables' foreign-key column names will be derived from your original model name. So you'll also want to do some rename_column calls on these dependent models. For instance, I had to rename the 'merchant_id' column to 'business_id' in various join tables (for has_and_belongs_to_many relationship) and other dependent tables (for normal has_one and has_many relationships). Otherwise I would have ended up with columns like 'business_stat.merchant_id' pointing to 'business.id'. Here's a good answer about doing column renames.
  • When grepping, remember to search for singular, plural, capitalized, lowercase, and even UPPERCASE (which may occur in comments) versions of your strings.
  • It's best to search for plural versions first, then singular. That way if you have an irregular plural - such as in my merchants :: businesses example - you can get all the irregular plurals correct. Otherwise you may end up with, for example, 'businesss' (3 s's) as an intermediate state, resulting in yet more search-and-replace.
  • Don't blindly replace every occurrence. If your model names collide with common programming terms, with values in other models, or with textual content in your views, you may end up being too over-eager. In my example, I wanted to change my model name to 'Business' but still refer to them as 'merchants' in the content in my UI. I also had a 'merchant' role for my users in CanCan - it was the confusion between the merchant role and the Merchant model that caused me to rename the model in the first place.

how to call a method in another Activity from Activity

The startActivityForResult pattern is much better suited for what you're trying to achieve : http://developer.android.com/reference/android/app/Activity.html#StartingActivities

Try below code

public class MainActivity extends Activity {  

    Button button1;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        textView1=(TextView)findViewById(R.id.textView1);  
        button1=(Button)findViewById(R.id.button1);  
        button1.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View arg0) {  
                Intent intent=new Intent(MainActivity.this,SecondActivity.class);  
                startActivityForResult(intent, 2);// Activity is started with requestCode 2  
            }  
        });  
    }  
 // Call Back method  to get the Message form other Activity  
    @Override  
       protected void onActivityResult(int requestCode, int resultCode, Intent data)  
       {  
                 super.onActivityResult(requestCode, resultCode, data);  
                  // check if the request code is same as what is passed  here it is 2  
                   if(requestCode==2)  
                         {  
                          //do the things u wanted 
                         }  
     }  

} 

SecondActivity.class

public class SecondActivity extends Activity {  

    Button button1;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_second);  

            button1=(Button)findViewById(R.id.button1);  
            button1.setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View arg0) {  
                    String message="hello ";  
                    Intent intent=new Intent();  
                    intent.putExtra("MESSAGE",message);  
                    setResult(2,intent);  
                    finish();//finishing activity  
                }  
            });  
    }  

}  

Let me know if it helped...

vuejs update parent data from child component

his example will tell you how to pass input value to parent on submit button.

First define eventBus as new Vue.

//main.js
import Vue from 'vue';
export const eventBus = new Vue();

Pass your input value via Emit.
//Sender Page
import { eventBus } from "../main";
methods: {
//passing data via eventbus
    resetSegmentbtn: function(InputValue) {
        eventBus.$emit("resetAllSegment", InputValue);
    }
}

//Receiver Page
import { eventBus } from "../main";

created() {
     eventBus.$on("resetAllSegment", data => {
         console.log(data);//fetching data
    });
}

Count specific character occurrences in a string

This is the simple way:

text = "the little red hen"
count = text.Split("e").Length -1 ' Equals 4
count = text.Split("t").Length -1 ' Equals 3

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

Use Query.setParameterList(), Javadoc here.

There are four variants to pick from.

How to solve WAMP and Skype conflict on Windows 7?

I think it is better to change default port of Skype.

Open skype. Go to Tools, Options, Connections, change the port.

What is the difference between AF_INET and PF_INET in socket programming?

Beej's famous network programming guide gives a nice explanation:

In some documentation, you'll see mention of a mystical "PF_INET". This is a weird etherial beast that is rarely seen in nature, but I might as well clarify it a bit here. Once a long time ago, it was thought that maybe a address family (what the "AF" in "AF_INET" stands for) might support several protocols that were referenced by their protocol family (what the "PF" in "PF_INET" stands for).
That didn't happen. Oh well. So the correct thing to do is to use AF_INET in your struct sockaddr_in and PF_INET in your call to socket(). But practically speaking, you can use AF_INET everywhere. And, since that's what W. Richard Stevens does in his book, that's what I'll do here.

How can I String.Format a TimeSpan object with a custom format in .NET?

I would go with

myTimeSpan.ToString("hh\\:mm\\:ss");

PHP multidimensional array search by value

Expanding on the function @mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:

 function searchArrayKeyVal($sKey, $id, $array) {
    foreach ($array as $key => $val) {
        if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) !== false) {
            return $key;
        }
    }
         return false;
 }

For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"

Are list-comprehensions and functional functions faster than "for loops"?

I have managed to modify some of @alpiii's code and discovered that List comprehension is a little faster than for loop. It might be caused by int(), it is not fair between list comprehension and for loop.

from functools import reduce
import datetime

def time_it(func, numbers, *args):
    start_t = datetime.datetime.now()
    for i in range(numbers):
        func(args[0])
    print (datetime.datetime.now()-start_t)

def square_sum1(numbers):
    return reduce(lambda sum, next: sum+next*next, numbers, 0)

def square_sum2(numbers):
    a = []
    for i in numbers:
        a.append(i*2)
    a = sum(a)
    return a

def square_sum3(numbers):
    sqrt = lambda x: x*x
    return sum(map(sqrt, numbers))

def square_sum4(numbers):
    return(sum([i*i for i in numbers]))

time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
0:00:00.101122 #Reduce

0:00:00.089216 #For loop

0:00:00.101532 #Map

0:00:00.068916 #List comprehension

HttpClient not supporting PostAsJsonAsync method C#

As already debatted, this method isn't available anymore since .NET 4.5.2. To expand on Jeroen K's answer you can make an extension method:

public static async Task<HttpResponseMessage> PostAsJsonAsync<TModel>(this HttpClient client, string requestUrl, TModel model)
{
    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(model);
    var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
    return await client.PostAsync(requestUrl, stringContent);
}

Now you are able to call client.PostAsJsonAsync("api/AgentCollection", user).

How to POST using HTTPclient content type = application/x-www-form-urlencoded

Another variant to POST this content type and which does not use a dictionary would be:

StringContent postData = new StringContent(JSON_CONTENT, Encoding.UTF8, "application/x-www-form-urlencoded");
using (HttpResponseMessage result = httpClient.PostAsync(url, postData).Result)
{
    string resultJson = result.Content.ReadAsStringAsync().Result;
}

Are there benefits of passing by pointer over passing by reference in C++?

Clarifications to the preceding posts:


References are NOT a guarantee of getting a non-null pointer. (Though we often treat them as such.)

While horrifically bad code, as in take you out behind the woodshed bad code, the following will compile & run: (At least under my compiler.)

bool test( int & a)
{
  return (&a) == (int *) NULL;
}

int
main()
{
  int * i = (int *)NULL;
  cout << ( test(*i) ) << endl;
};

The real issue I have with references lies with other programmers, henceforth termed IDIOTS, who allocate in the constructor, deallocate in the destructor, and fail to supply a copy constructor or operator=().

Suddenly there's a world of difference between foo(BAR bar) and foo(BAR & bar). (Automatic bitwise copy operation gets invoked. Deallocation in destructor gets invoked twice.)

Thankfully modern compilers will pick up this double-deallocation of the same pointer. 15 years ago, they didn't. (Under gcc/g++, use setenv MALLOC_CHECK_ 0 to revisit the old ways.) Resulting, under DEC UNIX, in the same memory being allocated to two different objects. Lots of debugging fun there...


More practically:

  • References hide that you are changing data stored someplace else.
  • It's easy to confuse a Reference with a Copied object.
  • Pointers make it obvious!

HTML Input Box - Disable

The syntax to disable an HTML input is as follows:

<input type="text" id="input_id" DISABLED />

How do I create/edit a Manifest file?

Go to obj folder in you app folder, then Debug. In there delete the manifest file and build again. It worked for me.

Finding the max value of an attribute in an array of objects

Well, first you should parse the JSON string, so that you can easily access it's members:

var arr = $.parseJSON(str);

Use the map method to extract the values:

arr = $.map(arr, function(o){ return o.y; });

Then you can use the array in the max method:

var highest = Math.max.apply(this,arr);

Or as a one-liner:

var highest = Math.max.apply(this,$.map($.parseJSON(str), function(o){ return o.y; }));

java.sql.SQLException: Fail to convert to internal representation

Check with your bean class. Column data type and bean datatype must be same.

Angular2 - Http POST request parameters

These answers are all outdated for those utilizing the HttpClient rather than Http. I was starting to go crazy thinking, "I have done the import of URLSearchParams but it still doesn't work without .toString() and the explicit header!"

With HttpClient, use HttpParams instead of URLSearchParams and note the body = body.append() syntax to achieve multiple params in the body since we are working with an immutable object:

login(userName: string, password: string): Promise<boolean> {
    if (!userName || !password) {
      return Promise.resolve(false);
    }

    let body: HttpParams = new HttpParams();
    body = body.append('grant_type', 'password');
    body = body.append('username', userName);
    body = body.append('password', password);

    return this.http.post(this.url, body)
      .map(res => {
        if (res) {          
          return true;
        }
        return false;
      })
      .toPromise();
  }

Working copy XXX locked and cleanup failed in SVN

Spotlight is its usual rubbish self at finding the lock files recursively.

EasyFind on Mac App Store works

http://itunes.apple.com/gb/app/easyfind/id411673888?mt=12

search for 'lock'

Select all / Delete

Read a javascript cookie by name

function getCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");

    for (i=0;i<ARRcookies.length;i++)
    {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name)
        {
            return unescape(y);
        }
     }
}

Source: W3Schools

Edit: as @zcrar70 noted, the above code is incorrect, please see the following answer Javascript getCookie functions

How do you compare two version Strings in Java?

I liked the idea from @Peter Lawrey, And i extended it to further limits :

    /**
    * Normalize string array, 
    * Appends zeros if string from the array
    * has length smaller than the maxLen.
    **/
    private String normalize(String[] split, int maxLen){
        StringBuilder sb = new StringBuilder("");
        for(String s : split) {
            for(int i = 0; i<maxLen-s.length(); i++) sb.append('0');
            sb.append(s);
        }
        return sb.toString();
    }

    /**
    * Removes trailing zeros of the form '.00.0...00'
    * (and does not remove zeros from, say, '4.1.100')
    **/
    public String removeTrailingZeros(String s){
        int i = s.length()-1;
        int k = s.length()-1;
        while(i >= 0 && (s.charAt(i) == '.' || s.charAt(i) == '0')){
          if(s.charAt(i) == '.') k = i-1;
          i--;  
        } 
        return s.substring(0,k+1);
    }

    /**
    * Compares two versions(works for alphabets too),
    * Returns 1 if v1 > v2, returns 0 if v1 == v2,
    * and returns -1 if v1 < v2.
    **/
    public int compareVersion(String v1, String v2) {

        // Uncomment below two lines if for you, say, 4.1.0 is equal to 4.1
        // v1 = removeTrailingZeros(v1);
        // v2 = removeTrailingZeros(v2);

        String[] splitv1 = v1.split("\\.");
        String[] splitv2 = v2.split("\\.");
        int maxLen = 0;
        for(String str : splitv1) maxLen = Math.max(maxLen, str.length());
        for(String str : splitv2) maxLen = Math.max(maxLen, str.length());
        int cmp = normalize(splitv1, maxLen).compareTo(normalize(splitv2, maxLen));
        return cmp > 0 ? 1 : (cmp < 0 ? -1 : 0);
    }

Hope it helps someone. It passed all test cases in interviewbit and leetcode (need to uncomment two lines in compareVersion function).

Easily tested !

How to convert Milliseconds to "X mins, x seconds" in Java?

For those who looking for Kotlin code:

fun converter(millis: Long): String =
        String.format(
            "%02d : %02d : %02d",
            TimeUnit.MILLISECONDS.toHours(millis),
            TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(
                TimeUnit.MILLISECONDS.toHours(millis)
            ),
            TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(
                TimeUnit.MILLISECONDS.toMinutes(millis)
            )
        )

Sample output: 09 : 10 : 26

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

If the extra entries in the log bother you but an extra second of start-up time doesn't, just add this to your logging.properties and forget about it:

org.apache.jasper.servlet.TldScanner.level = WARNING

Getting the first and last day of a month, using a given DateTime object

You can try this for get current month first day;

DateTime.Now.AddDays(-(DateTime.Now.Day-1))

and assign it a value.

Like this:

dateEndEdit.EditValue = DateTime.Now;
dateStartEdit.EditValue = DateTime.Now.AddDays(-(DateTime.Now.Day-1));

Adding whitespace in Java

If you have an Instance of the EditText available at the point in your code where you want add whitespace, then this code below will work. There may be some things to consider, for example the code below may trigger any TextWatcher you have set to this EditText, idk for sure, just saying, but this will work when trying to append blank space like this: " ", hasn't worked.

messageInputBox.dispatchKeyEvent(new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_SPACE, 0, 0, 0, 0,
                        KeyEvent.KEYCODE_ENDCALL));

How to install the Raspberry Pi cross compiler on my Linux host machine?

The initial question has been posted quite some time ago and in the meantime Debian has made huge headway in the area of multiarch support.

Multiarch is a great achievement for cross compilation!

In a nutshell the following steps are required to leverage multiarch for Raspbian Jessie cross compilation:

  • On your Ubuntu host install Debian Jessie amd64 within a chroot or a LXC container.
  • Enable the foreign architecture armhf.
  • Install the cross compiler from the emdebian tools repository.
  • Tweak the cross compiler (it would generate code for ARMv7-A by default) by writing a custom gcc specs file.
  • Install armhf libraries (libstdc++ etc.) from the Raspbian repository.
  • Build your source code.

Since this is a lot of work I have automated the above setup. You can read about it here:

Cross Compiling for Raspbian

"A lambda expression with a statement body cannot be converted to an expression tree"

For your specific case, the body is for creating a variable, and switching to IEnumerable will force all the operations to be processed on client-side, I propose the following solution.

Obj[] myArray = objects
.Select(o => new
{
    SomeLocalVar = o.someVar, // You can even use any LINQ statement here
    Info = o,
}).Select(o => new Obj()
{
    Var1 = o.SomeLocalVar,
    Var2 = o.Info.var2,
    Var3 = o.SomeLocalVar.SubValue1,
    Var4 = o.SomeLocalVar.SubValue2,
}).ToArray();

Edit: Rename for C# Coding Convention

How do I put a clear button inside my HTML text input box like the iPhone does?

Firefox doesn't seem to support the clear search field functionality... I found this pure CSS solution that works nicely: Textbox with a clear button completely in CSS | Codepen | 2013. The magic happens at

.search-box:not(:valid) ~ .close-icon {
    display: none;
}

_x000D_
_x000D_
body {
    background-color: #f1f1f1;
    font-family: Helvetica,Arial,Verdana;

}
h2 {
    color: green;
    text-align: center;
}
.redfamily {
    color: red; 
}
.search-box,.close-icon,.search-wrapper {
    position: relative;
    padding: 10px;
}
.search-wrapper {
    width: 500px;
    margin: auto;
}
.search-box {
    width: 80%;
    border: 1px solid #ccc;
  outline: 0;
  border-radius: 15px;
}
.search-box:focus {
    box-shadow: 0 0 15px 5px #b0e0ee;
    border: 2px solid #bebede;
}
.close-icon {
    border:1px solid transparent;
    background-color: transparent;
    display: inline-block;
    vertical-align: middle;
  outline: 0;
  cursor: pointer;
}
.close-icon:after {
    content: "X";
    display: block;
    width: 15px;
    height: 15px;
    position: absolute;
    background-color: #FA9595;
    z-index:1;
    right: 35px;
    top: 0;
    bottom: 0;
    margin: auto;
    padding: 2px;
    border-radius: 50%;
    text-align: center;
    color: white;
    font-weight: normal;
    font-size: 12px;
    box-shadow: 0 0 2px #E50F0F;
    cursor: pointer;
}
.search-box:not(:valid) ~ .close-icon {
    display: none;
}
_x000D_
<h2>
    Textbox with a clear button completely in CSS <br> <span class="redfamily">< 0 lines of JavaScript ></span>
</h2>
<div class="search-wrapper">
    <form>
    <input type="text" name="focus" required class="search-box" placeholder="Enter search term" />
        <button class="close-icon" type="reset"></button>
    </form>
</div>
_x000D_
_x000D_
_x000D_

I needed more functionality and added this jQuery in my code:

$('.close-icon').click(function(){ /* my code */ });

Getting the IP address of the current machine using Java

private static InetAddress getLocalAddress(){
        try {
            Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
            while( b.hasMoreElements()){
                for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses())
                    if ( f.getAddress().isSiteLocalAddress())
                        return f.getAddress();
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

Android: keeping a background service alive (preventing process death)

When you bind your Service to Activity with BIND_AUTO_CREATE your service is being killed just after your Activity is Destroyed and unbound. It does not depend on how you've implemented your Services unBind method it will be still killed.

The other way is to start your Service with startService method from your Activity. This way even if your Activity is destroyed your service won't be destroyed or even paused but you have to pause/destroy it by yourself with stopSelf/stopService when appropriate.

Removing input background colour for Chrome autocomplete?

This works for me.

.input:-webkit-autofill {transition: background-color 5000s ease-in-out 0s;}

How to get user's high resolution profile picture on Twitter?

use this URL : "https://twitter.com/(userName)/profile_image?size=original"

If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient, using TWTRAuthSession.

This is the code snipe for iOS:

if let twitterId = session.userID{
   let twitterClient = TWTRAPIClient(userID: twitterId)
   twitterClient.loadUser(withID: twitterId) {(user, error) in
       if let userName = user?.screenName{
          let url = "https://twitter.com/\(userName)/profile_image?size=original")
       }
   }
}

Spring,Request method 'POST' not supported

Try this

@RequestMapping(value = "proffessional", method = RequestMethod.POST)
    public @ResponseBody
    String forgotPassword(@ModelAttribute("PROFESSIONAL") UserProfessionalForm professionalForm,
            BindingResult result, Model model) {

        UserProfileVO userProfileVO = new UserProfileVO();
        userProfileVO.setUser(sessionData.getUser());
        userService.saveUserProfile(userProfileVO);
        model.addAttribute("professional", professionalForm);
        return "Your Professional Details Updated";
    }

How to create an exit message

The abort function does this. For example:

abort("Message goes here")

Note: the abort message will be written to STDERR as opposed to puts which will write to STDOUT.

#1214 - The used table type doesn't support FULLTEXT indexes

The problem occurred because of wrong table type.MyISAM is the only type of table that Mysql supports for Full-text indexes.

To correct this error run following sql.

 CREATE TABLE gamemech_chat (
  id bigint(20) unsigned NOT NULL auto_increment,
  from_userid varchar(50) NOT NULL default '0',
  to_userid varchar(50) NOT NULL default '0',
  text text NOT NULL,
  systemtext text NOT NULL,
  timestamp datetime NOT NULL default '0000-00-00 00:00:00',
  chatroom bigint(20) NOT NULL default '0',
  PRIMARY KEY  (id),
  KEY from_userid (from_userid),
  FULLTEXT KEY from_userid_2 (from_userid),
  KEY chatroom (chatroom),
  KEY timestamp (timestamp)
) ENGINE=MyISAM;

Using grep to search for hex strings in a file

If you want search for printable strings, you can use:

strings -ao filename | grep string

strings will output all printable strings from a binary with offsets, and grep will search within.

If you want search for any binary string, here is your friend:

AND/OR in Python?

if input == 'a':
    for char in 'abc':
        if char in some_list:
            some_list.remove(char)

Button that refreshes the page on click

button that refresh the page on click

Use onClick button with window.location.reload():

<button onClick="window.location.reload();">

Get current URL path in PHP

it should be :

$_SERVER['REQUEST_URI'];

Take a look at : Get the full URL in PHP

Get just the filename from a path in a Bash script

basename and dirname solutions are more convenient. Those are alternative commands:

FILE_PATH="/opt/datastores/sda2/test.old.img"
echo "$FILE_PATH" | sed "s/.*\///"

This returns test.old.img like basename.

This is salt filename without extension:

echo "$FILE_PATH" | sed -r "s/.+\/(.+)\..+/\1/"

It returns test.old.

And following statement gives the full path like dirname command.

echo "$FILE_PATH" | sed -r "s/(.+)\/.+/\1/"

It returns /opt/datastores/sda2

UL has margin on the left

by default <UL/> contains default padding

therefore try adding style to padding:0px in css class or inline css

How to store custom objects in NSUserDefaults

I create a library RMMapper (https://github.com/roomorama/RMMapper) to help save custom object into NSUserDefaults easier and more convenient, because implementing encodeWithCoder and initWithCoder is super boring!

To mark a class as archivable, just use: #import "NSObject+RMArchivable.h"

To save a custom object into NSUserDefaults:

#import "NSUserDefaults+RMSaveCustomObject.h"
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults rm_setCustomObject:user forKey:@"SAVED_DATA"];

To get custom obj from NSUserDefaults:

user = [defaults rm_customObjectForKey:@"SAVED_DATA"]; 

How can I list ALL DNS records?

Many DNS servers refuse ‘ANY’ queries. So the only way is to query for every type individually. Luckily there are sites that make this simpler. For example, https://www.nslookup.io shows the most popular record types by default, and has support for all existing record types.

ASP.NET page life cycle explanation

Partial Class _Default
    Inherits System.Web.UI.Page
    Dim str As String

    Protected Sub Page_Disposed(sender As Object, e As System.EventArgs) Handles Me.Disposed

        str += "PAGE DISPOSED" & "<br />"
    End Sub

    Protected Sub Page_Error(sender As Object, e As System.EventArgs) Handles Me.Error
        str += "PAGE ERROR " & "<br />"
    End Sub

    Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
        str += "PAGE INIT " & "<br />"
    End Sub

    Protected Sub Page_InitComplete(sender As Object, e As System.EventArgs) Handles Me.InitComplete
        str += "INIT Complte " & "<br />"
    End Sub

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        str += "PAGE LOAD " & "<br />"

    End Sub

    Protected Sub Page_LoadComplete(sender As Object, e As System.EventArgs) Handles Me.LoadComplete
        str += "PAGE LOAD Complete " & "<br />"
    End Sub

    Protected Sub Page_PreInit(sender As Object, e As System.EventArgs) Handles Me.PreInit
        str = ""
        str += "PAGE PRE INIT" & "<br />"
    End Sub

    Protected Sub Page_PreLoad(sender As Object, e As System.EventArgs) Handles Me.PreLoad
        str += "PAGE PRE LOAD " & "<br />"
    End Sub

    Protected Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
        str += "PAGE PRE RENDER " & "<br />"
    End Sub

    Protected Sub Page_PreRenderComplete(sender As Object, e As System.EventArgs) Handles Me.PreRenderComplete
        str += "PAGE PRE RENDER COMPLETE " & "<br />"
    End Sub

    Protected Sub Page_SaveStateComplete(sender As Object, e As System.EventArgs) Handles Me.SaveStateComplete
        str += "PAGE SAVE STATE COMPLTE  " & "<br />"
        lbl.Text = str
    End Sub

    Protected Sub Page_Unload(sender As Object, e As System.EventArgs) Handles Me.Unload
        'Response.Write("PAGE UN LOAD\n")
    End Sub
End Class

How to change the height of a <br>?

Might found a solution very easy which you only need to create different type of
. Seem to have worked for me.

example : (html code)

<br/ class="150%space">

(css code)

br[class='150%space']
{
   line-height: 150%;
}

SQL Case Sensitive String Compare

You Can easily Convert columns to VARBINARY(Max Length), The length must be the maximum you expect to avoid defective comparison, It's enough to set length as the column length. Trim column help you to compare the real value except space has a meaning and valued in your table columns, This is a simple sample and as you can see I Trim the columns value and then convert and compare.:

CONVERT(VARBINARY(250),LTRIM(RTRIM(Column1))) = CONVERT(VARBINARY(250),LTRIM(RTRIM(Column2)))

Hope this help.

mysql -> insert into tbl (select from another table) and some default values

With MySQL if you are inserting into a table that has a auto increment primary key and you want to use a built-in MySQL function such as NOW() then you can do something like this:

INSERT INTO course_payment 
SELECT NULL, order_id, payment_gateway, total_amt, charge_amt, refund_amt, NOW()
FROM orders ORDER BY order_id DESC LIMIT 10;

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

Here is what I did.

set ulimit -n 32000 in the file /etc/init.d/docker

and restart the docker service

docker run -ti node:latest /bin/bash

run this command to verify

user@4d04d06d5022:/# ulimit -a

should see this in the result

open files (-n) 32000

[user@ip ec2-user]# docker run -ti node /bin/bash
user@4d04d06d5022:/# ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 58729
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 32000
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 58729
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

remove space between paragraph and unordered list

I got pretty good results with my HTML mailing list by using the following:

p { margin-bottom: 0; }
ul { margin-top: 0; }

This does not reset all margin values but only those that create such a gap before ordered list, and still doesn't assume anything about default margin values.

How do I change the text of a span element using JavaScript?

For some reason, it seems that using "text" attribute is the way to go with most browsers. It worked for me

$("#span_id").text("text value to assign");

How to retrieve value from elements in array using jQuery?

You can just loop though the items:

$("input[name^='card']").each(function() {
    console.log($(this).val());
});

How do I align spans or divs horizontally?

you can do:

<div style="float: left;"></div>

or

<div style="display: inline;"></div>

Either one will cause the divs to tile horizontally.

Creating a jQuery object from a big HTML-string

There is also a great library called cheerio designed specifically for this.

Fast, flexible, and lean implementation of core jQuery designed specifically for the server.

var cheerio = require('cheerio'),
    $ = cheerio.load('<h2 class="title">Hello world</h2>');

$('h2.title').text('Hello there!');
$('h2').addClass('welcome');

$.html();
//=> <h2 class="title welcome">Hello there!</h2>

How to get value by class name in JavaScript or jquery?

Try this:

$(document).ready(function(){
    var yourArray = [];
    $("span.HOEnZb").find("div").each(function(){
        if(($.trim($(this).text()).length>0)){
         yourArray.push($(this).text());
        }
    });
});

DEMO

Remove last specific character in a string c#

Dim psValue As String = "1,5,12,34,123,12"
psValue = psValue.Substring(0, psValue.LastIndexOf(","))

output:

1,5,12,34,123

How to create an empty array in PHP with predefined size?

There is also array_pad. You can use it like this:

$data = array_pad($data,$number_of_items,0);

For initializing with zeros the $number_of_items positions of the array $data.

XSS prevention in JSP/Servlet web application

If you want to automatically escape all JSP variables without having to explicitly wrap each variable, you can use an EL resolver as detailed here with full source and an example (JSP 2.0 or newer), and discussed in more detail here:

For example, by using the above mentioned EL resolver, your JSP code will remain like so, but each variable will be automatically escaped by the resolver

...
<c:forEach items="${orders}" var="item">
  <p>${item.name}</p>
  <p>${item.price}</p>
  <p>${item.description}</p>
</c:forEach>
...

If you want to force escaping by default in Spring, you could consider this as well, but it doesn't escape EL expressions, just tag output, I think:

http://forum.springsource.org/showthread.php?61418-Spring-cross-site-scripting&p=205646#post205646

Note: Another approach to EL escaping that uses XSL transformations to preprocess JSP files can be found here:

http://therning.org/niklas/2007/09/preprocessing-jsp-files-to-automatically-escape-el-expressions/

How to list all Git tags?

Also git show-ref is rather useful, so that you can directly associate tags with correspondent commits:

$ git tag
osgeolive-6.5
v8.0
...

$ git show-ref --tags
e7e66977c1f34be5627a268adb4b9b3d59700e40 refs/tags/osgeolive-6.5
8f27e65bddd7d4b8515ce620fb485fdd78fcdf89 refs/tags/v8.0
...

Grunt watch error - Waiting...Fatal error: watch ENOSPC

To find out who's making inotify instances, try this command (source):

for foo in /proc/*/fd/*; do readlink -f $foo; done | grep inotify | sort | uniq -c | sort -nr

Mine looked like this:

 25 /proc/2857/fd/anon_inode:inotify
  9 /proc/2880/fd/anon_inode:inotify
  4 /proc/1375/fd/anon_inode:inotify
  3 /proc/1851/fd/anon_inode:inotify
  2 /proc/2611/fd/anon_inode:inotify
  2 /proc/2414/fd/anon_inode:inotify
  1 /proc/2992/fd/anon_inode:inotify

Using ps -p 2857, I was able to identify process 2857 as sublime_text. Only after closing all sublime windows was I able to run my node script.

Why do people write #!/usr/bin/env python on the first line of a Python script?

If you're running your script in a virtual environment, say venv, then executing which python while working on venv will display the path to the Python interpreter:

~/Envs/venv/bin/python

Note that the name of the virtual environment is embedded in the path to the Python interpreter. Therefore, hardcoding this path in your script will cause two problems:

  • If you upload the script to a repository, you're forcing other users to have the same virtual environment name. This is if they identify the problem first.
  • You won't be able to run the script across multiple virtual environments even if you had all required packages in other virtual environments.

Therefore, to add to Jonathan's answer, the ideal shebang is #!/usr/bin/env python, not just for portability across OSes but for portability across virtual environments as well!

Programmatically open new pages on Tabs

You can't directly control this, because it's an option controlled by Internet Explorer users.

Opening pages using Window.open with a different window name will open in a new browser window like a popup, OR open in a new tab, if the user configured the browser to do so.

How to change color and font on ListView

Even better, you do not need to create separate android xml layout for list cell view. You can just use "android.R.layout.simple_list_item_1" if the list only contains textview.

private class ExampleAdapter extends ArrayAdapter<String>{

    public ExampleAdapter(Context context, int textViewResourceId, String[] objects) {
        super(context, textViewResourceId, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        View view =  super.getView(position, convertView, parent);

        TextView tv = (TextView) view.findViewById(android.R.id.text1);
        tv.setTextColor(0);

        return view;
    }

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3

For a non-angular general answer for those who land on this question from Google:

Every time you face this error its probably because of a memory leak or difference between how Node <= 10 and Node > 10 manage memory. Usually just increasing the memory allocated to Node will allow your program to run but may not actually solve the real problem and the memory used by the node process could still exceed the new memory you allocate. I'd advise profiling memory usage in your node process when it starts running or updating to node > 10.

I had a memory leak. Here is a great article on debugging memory leaks in node.

That said, to increase the memory, in the terminal where you run your Node process:

export NODE_OPTIONS="--max-old-space-size=8192"

where values of max-old-space-size can be: [2048, 4096, 8192, 16384] etc

[UPDATE] More examples for further clarity:

export NODE_OPTIONS="--max-old-space-size=5120" #increase to 5gb
export NODE_OPTIONS="--max-old-space-size=6144" #increase to 6gb
export NODE_OPTIONS="--max-old-space-size=7168" #increase to 7gb
export NODE_OPTIONS="--max-old-space-size=8192" #increase to 8gb

# and so on...

# formula:
export NODE_OPTIONS="--max-old-space-size=(X * 1024)" #increase to Xgb

# Note: it doesn't have to be multiples of 1024. 
# max-old-space-size can be any number of memory megabytes(MB) you have available.

Create file path from variables

You want the path.join() function from os.path.

>>> from os import path
>>> path.join('foo', 'bar')
'foo/bar'

This builds your path with os.sep (instead of the less portable '/') and does it more efficiently (in general) than using +.

However, this won't actually create the path. For that, you have to do something like what you do in your question. You could write something like:

start_path = '/my/root/directory'
final_path = os.join(start_path, *list_of_vars)
if not os.path.isdir(final_path):
    os.makedirs (final_path)

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

In CSS how do you change font size of h1 and h2

h1 {
  font-weight: bold;
  color: #fff;
  font-size: 32px;
}

h2 {
  font-weight: bold;
  color: #fff;
  font-size: 24px;
}

Note that after color you can use a word (e.g. white), a hex code (e.g. #fff) or RGB (e.g. rgb(255,255,255)) or RGBA (e.g. rgba(255,255,255,0.3)).

How to make a GridLayout fit screen size

Note: The information below the horizontal line is no longer accurate with the introduction of Android 'Lollipop' 5, as GridLayout does accommodate the principle of weights since API level 21.

Quoted from the Javadoc:

Excess Space Distribution

As of API 21, GridLayout's distribution of excess space accomodates the principle of weight. In the event that no weights are specified, the previous conventions are respected and columns and rows are taken as flexible if their views specify some form of alignment within their groups. The flexibility of a view is therefore influenced by its alignment which is, in turn, typically defined by setting the gravity property of the child's layout parameters. If either a weight or alignment were defined along a given axis then the component is taken as flexible in that direction. If no weight or alignment was set, the component is instead assumed to be inflexible.

Multiple components in the same row or column group are considered to act in parallel. Such a group is flexible only if all of the components within it are flexible. Row and column groups that sit either side of a common boundary are instead considered to act in series. The composite group made of these two elements is flexible if one of its elements is flexible.

To make a column stretch, make sure all of the components inside it define a weight or a gravity. To prevent a column from stretching, ensure that one of the components in the column does not define a weight or a gravity.

When the principle of flexibility does not provide complete disambiguation, GridLayout's algorithms favour rows and columns that are closer to its right and bottom edges. To be more precise, GridLayout treats each of its layout parameters as a constraint in the a set of variables that define the grid-lines along a given axis. During layout, GridLayout solves the constraints so as to return the unique solution to those constraints for which all variables are less-than-or-equal-to the corresponding value in any other valid solution.

It's also worth noting that android.support.v7.widget.GridLayout contains the same information. Unfortunately it doesn't mention which version of the support library it was introduced with, but the commit that adds the functionality can be tracked back to July 2014. In November 2014, improvements in weight calculation and a bug was fixed.

To be safe, make sure to import the latest version of the gridlayout-v7 library.


The principle of 'weights', as you're describing it, does not exist with GridLayout. This limitation is clearly mentioned in the documentation; excerpt below. That being said, there are some possibilities to use 'gravity' for excess space distribution. I suggest you have read through the linked documentation.

Limitations

GridLayout does not provide support for the principle of weight, as defined in weight. In general, it is not therefore possible to configure a GridLayout to distribute excess space in non-trivial proportions between multiple rows or columns. Some common use-cases may nevertheless be accommodated as follows. To place equal amounts of space around a component in a cell group; use CENTER alignment (or gravity). For complete control over excess space distribution in a row or column; use a LinearLayout subview to hold the components in the associated cell group. When using either of these techniques, bear in mind that cell groups may be defined to overlap.

For an example and some practical pointers, take a look at last year's blog post introducing the GridLayout widget.


Edit: I don't think there's an xml-based approach to scaling the tiles like in the Google Play app to 'squares' or 'rectangles' twice the length of those squares. However, it is certainly possible if you build your layout programmatically. All you really need to know in order two accomplish that is the device's screen dimensions.

Below a (very!) quick 'n dirty approximation of the tiled layout in the Google Play app.

Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
int screenWidth = size.x;
int screenHeight = size.y;
int halfScreenWidth = (int)(screenWidth *0.5);
int quarterScreenWidth = (int)(halfScreenWidth * 0.5);

Spec row1 = GridLayout.spec(0, 2);
Spec row2 = GridLayout.spec(2);
Spec row3 = GridLayout.spec(3);
Spec row4 = GridLayout.spec(4, 2);

Spec col0 = GridLayout.spec(0);
Spec col1 = GridLayout.spec(1); 
Spec colspan2 = GridLayout.spec(0, 2);

GridLayout gridLayout = new GridLayout(this);
gridLayout.setColumnCount(2);
gridLayout.setRowCount(15);

TextView twoByTwo1 = new TextView(this);
GridLayout.LayoutParams first = new GridLayout.LayoutParams(row1, colspan2);
first.width = screenWidth;
first.height = quarterScreenWidth * 2;
twoByTwo1.setLayoutParams(first);
twoByTwo1.setGravity(Gravity.CENTER);
twoByTwo1.setBackgroundColor(Color.RED);
twoByTwo1.setText("TOP");
twoByTwo1.setTextAppearance(this, android.R.style.TextAppearance_Large);
gridLayout.addView(twoByTwo1, first);

TextView twoByOne1 = new TextView(this);
GridLayout.LayoutParams second = new GridLayout.LayoutParams(row2, col0);
second.width = halfScreenWidth;
second.height = quarterScreenWidth;
twoByOne1.setLayoutParams(second);
twoByOne1.setBackgroundColor(Color.BLUE);
twoByOne1.setText("Staff Choices");
twoByOne1.setTextAppearance(this, android.R.style.TextAppearance_Large);
gridLayout.addView(twoByOne1, second);

TextView twoByOne2 = new TextView(this);
GridLayout.LayoutParams third = new GridLayout.LayoutParams(row2, col1);
third.width = halfScreenWidth;
third.height = quarterScreenWidth;
twoByOne2.setLayoutParams(third);
twoByOne2.setBackgroundColor(Color.GREEN);
twoByOne2.setText("Games");
twoByOne2.setTextAppearance(this, android.R.style.TextAppearance_Large);
gridLayout.addView(twoByOne2, third);

TextView twoByOne3 = new TextView(this);
GridLayout.LayoutParams fourth = new GridLayout.LayoutParams(row3, col0);
fourth.width = halfScreenWidth;
fourth.height = quarterScreenWidth;
twoByOne3.setLayoutParams(fourth);
twoByOne3.setBackgroundColor(Color.YELLOW);
twoByOne3.setText("Editor's Choices");
twoByOne3.setTextAppearance(this, android.R.style.TextAppearance_Large_Inverse);
gridLayout.addView(twoByOne3, fourth);

TextView twoByOne4 = new TextView(this);
GridLayout.LayoutParams fifth = new GridLayout.LayoutParams(row3, col1);
fifth.width = halfScreenWidth;
fifth.height = quarterScreenWidth;
twoByOne4.setLayoutParams(fifth);
twoByOne4.setBackgroundColor(Color.MAGENTA);
twoByOne4.setText("Something Else");
twoByOne4.setTextAppearance(this, android.R.style.TextAppearance_Large);
gridLayout.addView(twoByOne4, fifth);

TextView twoByTwo2 = new TextView(this);
GridLayout.LayoutParams sixth = new GridLayout.LayoutParams(row4, colspan2);
sixth.width = screenWidth;
sixth.height = quarterScreenWidth * 2;
twoByTwo2.setLayoutParams(sixth);
twoByTwo2.setGravity(Gravity.CENTER);
twoByTwo2.setBackgroundColor(Color.WHITE);
twoByTwo2.setText("BOTOM");
twoByTwo2.setTextAppearance(this, android.R.style.TextAppearance_Large_Inverse);
gridLayout.addView(twoByTwo2, sixth);

The result will look somewhat like this (on my Galaxy Nexus):

Tiled layout using GridLayout

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

To remove spaces... please use LTRIM/RTRIM

 LTRIM(String)
 RTRIM(String)

The String parameter that is passed to the functions can be a column name, a variable, a literal string or the output of a user defined function or scalar query.

SELECT LTRIM(' spaces at start')
SELECT RTRIM(FirstName) FROM Customers

Read more: http://rockingshani.blogspot.com/p/sq.html#ixzz33SrLQ4Wi

Is it possible to refresh a single UITableViewCell in a UITableView?

I tried just calling -[UITableView cellForRowAtIndexPath:], but that didn't work. But, the following works for me for example. I alloc and release the NSArray for tight memory management.

- (void)reloadRow0Section0 {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
    [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
    [indexPaths release];
}

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

Can't beat Eric Leschinski's awesomely detailed answer, but here's a quick workaround to the original question that I don't think has been mentioned yet - put the string in a list and use .isin instead of ==

For example:

import pandas as pd
import numpy as np

df = pd.DataFrame({"Name": ["Peter", "Joe"], "Number": [1, 2]})

# Raises warning using == to compare different types:
df.loc[df["Number"] == "2", "Number"]

# No warning using .isin:
df.loc[df["Number"].isin(["2"]), "Number"]

Show whitespace characters in Visual Studio Code

Hit the F1 button, then type "Toggle Render Whitespace" or the parts of it you can remember :)

I use vscode version 1.22.2 so this could be a feature that did not exist back in 2015.

How to write macro for Notepad++?

I just did this in v5.9.1. Just go to the Macro Menu, click "Start Recording", perform your 3 replace all commands, then stop recording. You can then select "Save Current Recorded Macro", and play it back as often as you like, and it will perform the replaces as you expect.

How to set null to a GUID property

You can use typeof(Guid), "00000000-0000-0000-0000-000000000000" for DefaultValue of the property.

WCF error: The caller was not authenticated by the service

I also had the same problem in wsHtppBinding. And I just had to add security mode pointing to none, that solved my problem and no need to switch to basicHttpBinding. Check Here and check how to disable WCF security. Check the below config change for reference:

<wsHttpBinding>
    <binding name="soapBinding">
        <security mode="None">
            <transport clientCredentialType="None" />
            <message establishSecurityContext="false" />
        </security>
    </binding>
</wsHttpBinding>

In Visual Basic how do you create a block comment

There's not a way as of 11/2012, HOWEVER

Highlight Text (In visual Studio.net)

ctrl + k + c, ctrl + k + u

Will comment / uncomment, respectively

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

The first part of your question is a duplicate of Why do I get a JsonReaderException with this code?, but the most relevant part from that (my) answer is this:

[A] JObject isn't the elementary base type of everything in JSON.net, but JToken is. So even though you could say,

object i = new int[0];

in C#, you can't say,

JObject i = JObject.Parse("[0, 0, 0]");

in JSON.net.

What you want is JArray.Parse, which will accept the array you're passing it (denoted by the opening [ in your API response). This is what the "StartArray" in the error message is telling you.

As for what happened when you used JArray, you're using arr instead of obj:

var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);

Swap that, and I believe it should work.

Although I'd be tempted to deserialize arr directly as an IEnumerable<LocationData>, which would save some code and effort of looping through the array. If you aren't going to use the parsed version separately, it's best to avoid it.