Programs & Examples On #Http caching

Eliminate the need to send HTTP requests in many cases, and eliminate the need to send full HTTP responses in other cases, by storing web content closer to where it is consumed.

How do I print the percent sign(%) in c

Your problem is that you have to change:

printf("%"); 

to

printf("%%");

Or you could use ASCII code and write:

printf("%c", 37);

:)

How to call Stored Procedures with EntityFramework?

Based up the OP's original request to be able to called a stored proc like this...

using (Entities context = new Entities())
{
    context.MyStoreadProcedure(Parameters); 
}

Mindless passenger has a project that allows you to call a stored proc from entity frame work like this....

using (testentities te = new testentities())
{
    //-------------------------------------------------------------
    // Simple stored proc
    //-------------------------------------------------------------
    var parms1 = new testone() { inparm = "abcd" };
    var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
    var r1 = results1.ToList<TestOneResultSet>();
}

... and I am working on a stored procedure framework (here) which you can call like in one of my test methods shown below...

[TestClass]
public class TenantDataBasedTests : BaseIntegrationTest
{
    [TestMethod]
    public void GetTenantForName_ReturnsOneRecord()
    {
        // ARRANGE
        const int expectedCount = 1;
        const string expectedName = "Me";

        // Build the paraemeters object
        var parameters = new GetTenantForTenantNameParameters
        {
            TenantName = expectedName
        };

        // get an instance of the stored procedure passing the parameters
        var procedure = new GetTenantForTenantNameProcedure(parameters);

        // Initialise the procedure name and schema from procedure attributes
        procedure.InitializeFromAttributes();

        // Add some tenants to context so we have something for the procedure to return!
        AddTenentsToContext(Context);

        // ACT
        // Get the results by calling the stored procedure from the context extention method 
        var results = Context.ExecuteStoredProcedure(procedure);

        // ASSERT
        Assert.AreEqual(expectedCount, results.Count);
    }
}

internal class GetTenantForTenantNameParameters
{
    [Name("TenantName")]
    [Size(100)]
    [ParameterDbType(SqlDbType.VarChar)]
    public string TenantName { get; set; }
}

[Schema("app")]
[Name("Tenant_GetForTenantName")]
internal class GetTenantForTenantNameProcedure
    : StoredProcedureBase<TenantResultRow, GetTenantForTenantNameParameters>
{
    public GetTenantForTenantNameProcedure(
        GetTenantForTenantNameParameters parameters)
        : base(parameters)
    {
    }
}

If either of those two approaches are any good?

How do you disable viewport zooming on Mobile Safari?

user-scalable=0

This no longer works on iOS 10. Apple removed the feature.

There is no way yo can disable zoom website on iOS now, unless you make gross platform app.

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

If you're running SQL Server 2005, you can write a custom CLR aggregate function to handle this.

C# version:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Text;
using Microsoft.SqlServer.Server;
[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.UserDefined,MaxByteSize=8000)]
public class CSV:IBinarySerialize
{
    private StringBuilder Result;
    public void Init() {
        this.Result = new StringBuilder();
    }

    public void Accumulate(SqlString Value) {
        if (Value.IsNull) return;
        this.Result.Append(Value.Value).Append(",");
    }
    public void Merge(CSV Group) {
        this.Result.Append(Group.Result);
    }
    public SqlString Terminate() {
        return new SqlString(this.Result.ToString());
    }
    public void Read(System.IO.BinaryReader r) {
        this.Result = new StringBuilder(r.ReadString());
    }
    public void Write(System.IO.BinaryWriter w) {
        w.Write(this.Result.ToString());
    }
}

How to build query string with Javascript

querystring can help.

So, you can

const querystring = require('querystring')

url += '?' + querystring.stringify(parameters)

Python style - line continuation with strings?

Another possibility is to use the textwrap module. This also avoids the problem of "string just sitting in the middle of nowhere" as mentioned in the question.

import textwrap
mystr = """\
        Why, hello there
        wonderful stackoverfow people"""
print (textwrap.fill(textwrap.dedent(mystr)))

The following untracked working tree files would be overwritten by merge, but I don't care

In addition to the accepted answer you can of course remove the files if they are no longer needed by specifying the file:

git clean -f '/path/to/file/'

Remember to run it with the -n flag first if you would like to see which files git clean will remove. Note that these files will be deleted. In my case I didn't care about them anyway, so that was a better solution for me.

Height of an HTML select box (dropdown)

NO. It's not possible to change height of a select dropdown because that property is browser specific.

However if you want that functionality, then there are many options. You can use bootstrap dropdown-menu and define it's max-height property. Something like this.

_x000D_
_x000D_
$('.dropdown-menu').on( 'click', 'a', function() {_x000D_
    var text = $(this).html();_x000D_
    var htmlText = text + ' <span class="caret"></span>';_x000D_
    $(this).closest('.dropdown').find('.dropdown-toggle').html(htmlText);_x000D_
});
_x000D_
.dropdown-menu {_x000D_
    max-height: 146px;_x000D_
    overflow: scroll;_x000D_
    overflow-x: hidden;_x000D_
    margin-top: 0px;_x000D_
}_x000D_
_x000D_
.caret {_x000D_
   float: right;_x000D_
    margin-top: 5%;_x000D_
}_x000D_
_x000D_
#menu1 {_x000D_
    width: 160px; _x000D_
    text-align: left;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
   _x000D_
<div class="container" style="margin:10px">_x000D_
  <div class="dropdown">_x000D_
    <button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">Tutorials_x000D_
    <span class="caret"></span></button>_x000D_
    <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Send auto email programmatically

It might be an easiest way-

    String recipientList = mEditTextTo.getText().toString();
    String[] recipients = recipientList.split(",");

    String subject = mEditTextSubject.getText().toString();
    String message = mEditTextMessage.getText().toString();

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_EMAIL, recipients);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, message);

    intent.setType("message/rfc822");
    startActivity(Intent.createChooser(intent, "Choose an email client"));

How to create circular ProgressBar in android?

You can try this Circle Progress library

enter image description here

enter image description here

NB: please always use same width and height for progress views

DonutProgress:

 <com.github.lzyzsd.circleprogress.DonutProgress
        android:id="@+id/donut_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

CircleProgress:

  <com.github.lzyzsd.circleprogress.CircleProgress
        android:id="@+id/circle_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

ArcProgress:

<com.github.lzyzsd.circleprogress.ArcProgress
        android:id="@+id/arc_progress"
        android:background="#214193"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:arc_progress="55"
        custom:arc_bottom_text="MEMORY"/>

Find duplicate characters in a String and count the number of occurances using Java

import java.io.*;
public class CountChar 
{

    public static void main(String[] args) throws IOException
    {
      String ch;
      BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
      System.out.print("Enter the Statement:");
      ch=br.readLine();
      int count=0,len=0;
        do
        {  
          try
          {
          char name[]=ch.toCharArray();
              len=name.length;
              count=0;
              for(int j=0;j<len;j++)
               {
                  if((name[0]==name[j])&&((name[0]>=65&&name[0]<=91)||(name[0]>=97&&name[0]<=123))) 
                      count++;
               }
              if(count!=0)
                System.out.println(name[0]+" "+count+" Times");
              ch=ch.replace(""+name[0],"");          
          }
          catch(Exception ex){}
        }
        while(len!=1);
   }

}

Output

Enter the Statement:asdf23123sfsdf

a 1 Times

s 3 Times

d 2 Times

f 3 Times

CSS selector (id contains part of text)

The only selector I see is a[id$="name"] (all links with id finishing by "name") but it's not as restrictive as it should.

Using a SELECT statement within a WHERE clause

This is a correlated sub-query.

(It is a "nested" query - this is very non-technical term though)

The inner query takes values from the outer-query (WHERE st.Date = ScoresTable.Date) thus it is evaluated once for each row in the outer query.

There is also a non-correlated form in which the inner query is independent as as such is only executed once.

e.g.

 SELECT * FROM ScoresTable WHERE Score = 
   (SELECT MAX(Score) FROM Scores)

There is nothing wrong with using subqueries, except where they are not needed :)

Your statement may be rewritable as an aggregate function depending on what columns you require in your select statement.

SELECT Max(score), Date FROM ScoresTable 
Group By Date

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

In order to not have the Cannot recover key exception, I had to apply the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files to the installation of Java that was running my application. Version 8 of those files can be found here or the latest version should be listed on this page. The download includes a file that explains how to apply the policy files.


Since JDK 8u151 it isn't necessary to add policy files. Instead the JCE jurisdiction policy files are controlled by a Security property called crypto.policy. Setting that to unlimited with allow unlimited cryptography to be used by the JDK. As the release notes linked to above state, it can be set by Security.setProperty() or via the java.security file. The java.security file could also be appended to by adding -Djava.security.properties=my_security.properties to the command to start the program as detailed here.


Since JDK 8u161 unlimited cryptography is enabled by default.

How to test the type of a thrown exception in Jest

From my (albeit limited) exposure to Jest, I have found that expect().toThrow() is suitable if you want to only test an error is thrown of a specific type:

expect(() => functionUnderTest()).toThrow(TypeError);

Or an error is thrown with a specific message:

expect(() => functionUnderTest()).toThrow('Something bad happened!');

If you try to do both, you will get a false positive. For example, if your code throws RangeError('Something bad happened!'), this test will pass:

expect(() => functionUnderTest()).toThrow(new TypeError('Something bad happened!'));

The answer by bodolsog which suggests using a try/catch is close, but rather than expecting true to be false to ensure the expect assertions in the catch are hit, you can instead use expect.assertions(2) at the start of your test where 2 is the number of expected assertions. I feel this more accurately describes the intention of the test.

A full example of testing the type and message of an error:

describe('functionUnderTest', () => {
    it('should throw a specific type of error.', () => {
        expect.assertions(2);

        try {
            functionUnderTest();
        } catch (error) {
            expect(error).toBeInstanceOf(TypeError);
            expect(error).toHaveProperty('message', 'Something bad happened!');
        }
    });
});

If functionUnderTest() does not throw an error, the assertions will be be hit, but the expect.assertions(2) will fail and the test will fail.

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I would like to add an example of prototypical inheritance with javascript to @Scott Driscoll answer. We'll be using classical inheritance pattern with Object.create() which is a part of EcmaScript 5 specification.

First we create "Parent" object function

function Parent(){

}

Then add a prototype to "Parent" object function

 Parent.prototype = {
 primitive : 1,
 object : {
    one : 1
   }
}

Create "Child" object function

function Child(){

}

Assign child prototype (Make child prototype inherit from parent prototype)

Child.prototype = Object.create(Parent.prototype);

Assign proper "Child" prototype constructor

Child.prototype.constructor = Child;

Add method "changeProps" to a child prototype, which will rewrite "primitive" property value in Child object and change "object.one" value both in Child and Parent objects

Child.prototype.changeProps = function(){
    this.primitive = 2;
    this.object.one = 2;
};

Initiate Parent (dad) and Child (son) objects.

var dad = new Parent();
var son = new Child();

Call Child (son) changeProps method

son.changeProps();

Check the results.

Parent primitive property did not change

console.log(dad.primitive); /* 1 */

Child primitive property changed (rewritten)

console.log(son.primitive); /* 2 */

Parent and Child object.one properties changed

console.log(dad.object.one); /* 2 */
console.log(son.object.one); /* 2 */

Working example here http://jsbin.com/xexurukiso/1/edit/

More info on Object.create here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/create

XAMPP Start automatically on Windows 7 startup

Try following Steps for Apache

  • Go to your XAMPP installation folder. Right-click xampp-control.exe. Click "Run as administrator"
  • Stop Apache service action port
  • Tick this (in snapshot) check box. It will ask if you want to install as service. Click "Yes".
  • Go to Windows Services by typing Window + R, then typing services.msc

  • Enter a new service name as Apache2 (or similar)

  • Set it as automatic, if you want it to run as startup.

Repeat the steps for the MySQL service

enter image description here

How can I remove space (margin) above HTML header?

It is good practice when you start creating website to reset all the margins and paddings. So I recommend on start just to simple do:

* { margin: 0, padding: 0 }

This will make margins and paddings of all elements to be 0, and then you can style them as you wish, because each browser has a different default margin and padding of the elements.

How to use the divide function in the query?

Assuming all of these columns are int, then the first thing to sort out is converting one or more of them to a better data type - int division performs truncation, so anything less than 100% would give you a result of 0:

select (100.0 * (SPGI09_EARLY_OVER_T – SPGI09_OVER_WK_EARLY_ADJUST_T)) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T  + SPGR99_ON_TIME_Q)
from 
CSPGI09_OVERSHIPMENT 

Here, I've mutiplied one of the numbers by 100.0 which will force the result of the calculation to be done with floats rather than ints. By choosing 100, I'm also getting it ready to be treated as a %.

I was also a little confused by your bracketing - I think I've got it correct - but you had brackets around single values, and then in other places you had a mix of operators (- and /) at the same level, and so were relying on the precedence rules to define which operator applied first.

Convert a Unicode string to an escaped ASCII string

string StringFold(string input, Func<char, string> proc)
{
  return string.Concat(input.Select(proc).ToArray());
}

string FoldProc(char input)
{
  if (input >= 128)
  {
    return string.Format(@"\u{0:x4}", (int)input);
  }
  return input.ToString();
}

string EscapeToAscii(string input)
{
  return StringFold(input, FoldProc);
}

Android device chooser - My device seems offline

Had the same issue on my HTC Incredible S. The problem was that I used a third party docking station to connect. Connecting the phone directly solved the problem.

Case insensitive string compare in LINQ-to-SQL

Remember that there is a difference between whether the query works and whether it works efficiently! A LINQ statement gets converted to T-SQL when the target of the statement is SQL Server, so you need to think about the T-SQL that would be produced.

Using String.Equals will most likely (I am guessing) bring back all of the rows from SQL Server and then do the comparison in .NET, because it is a .NET expression that cannot be translated into T-SQL.

In other words using an expression will increase your data access and remove your ability to make use of indexes. It will work on small tables and you won't notice the difference. On a large table it could perform very badly.

That's one of the problems that exists with LINQ; people no longer think about how the statements they write will be fulfilled.

In this case there isn't a way to do what you want without using an expression - not even in T-SQL. Therefore you may not be able to do this more efficiently. Even the T-SQL answer given above (using variables with collation) will most likely result in indexes being ignored, but if it is a big table then it is worth running the statement and looking at the execution plan to see if an index was used.

Table with table-layout: fixed; and how to make one column wider

The important thing of table-layout: fixed is that the column widths are determined by the first row of the table.

So

if your table structure is as follow (standard table structure)

<table>
  <thead>
      <tr>
          <th> First column </th>
          <th> Second column </th>
          <th> Third column </th>        
      </tr>
  </thead>

   <tbody>
      <tr>
          <td> First column </td>
          <td> Second column </td>
          <td> Third column </td>        
      </tr>
  </tbody>

if you would like to give a width to second column then

<style> 
    table{
        table-layout:fixed;
        width: 100%;
    }

    table tr th:nth-child(2){
       width: 60%;
     }

</style>

Please look that we style the th not the td.

Debugging Spring configuration

Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this

<category name="org.springframework.beans">
    <priority value="debug" />
</category>

or

<category name="org.springframework">
    <priority value="debug" />
</category>

I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:springContext.xml"})
@Transactional
public class SpringDAOTest 
{
    @Autowired
    private SpringDAO dao;

    @Autowired
    private ApplicationContext appContext;

    @Test
    public void checkConfig()
    {
        AnySpringBean bean =  appContext.getBean(AnySpringBean.class);
        Assert.assertNotNull(bean);
    }
}

UPDATE

I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/log4j.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

UPDATE log4j config file


I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />
        </layout>
    </appender>

    <appender name="springAppender" class="org.apache.log4j.RollingFileAppender"> 
        <param name="file" value="C:/tomcatLogs/webApp/spring-details.log" /> 
        <param name="append" value="true" /> 
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{MM/dd/yyyy HH:mm:ss}  [%t]:%c{5}.%M()%L %m%n" />
        </layout>
    </appender>

    <category name="org.springframework">
        <priority value="debug" />
    </category>

    <category name="org.springframework.beans">
        <priority value="debug" />
    </category>

    <category name="org.springframework.security">
        <priority value="debug" />
    </category>

    <category
        name="org.springframework.beans.CachedIntrospectionResults">
        <priority value="debug" />
    </category>

    <category name="org.springframework.jdbc.core">
        <priority value="debug" />
    </category>

    <category name="org.springframework.transaction.support.TransactionSynchronizationManager">
        <priority value="debug" />
    </category>

    <root>
        <priority value="debug" />
        <appender-ref ref="springAppender" />
        <!-- <appender-ref ref="STDOUT"/>  -->
    </root>
</log4j:configuration>

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

check the no. of record in parent table that matches with child table and also primary key must match with foreign key reference. This works for me.

How to preSelect an html dropdown list with php?

First of all give a name to your select. Then do:

<select name="my_select">
<option value="1" <?= ($_POST['my_select'] == "1")? "selected":"";?>>Yes</options>
<option value="2" <?= ($_POST['my_select'] == "2")? "selected":"";?>>No</options>
<option value="3" <?= ($_POST['my_select'] == "3")? "selected":"";?>>Fine</options>
</select>

What that does is check if what was selected is the same for each and when its found echo "selected".

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

Using jQuery, Restricting File Size Before Uploading

I found that Apache2 (you might want to also check Apache 1.5) has a way to restrict this before uploading by dropping this in your .htaccess file:

LimitRequestBody 2097152

This restricts it to 2 megabytes (2 * 1024 * 1024) on file upload (if I did my byte math properly).

Note when you do this, the Apache error log will generate this entry when you exceed this limit on a form post or get request:

Requested content-length of 4000107 is larger than the configured limit of 2097152

And it will also display this message back in the web browser:

<h1>Request Entity Too Large</h1>

So, if you're doing AJAX form posts with something like the Malsup jQuery Form Plugin, you could trap for the H1 response like this and show an error result.

By the way, the error number returned is 413. So, you could use a directive in your .htaccess file like...

Redirect 413 413.html

...and provide a more graceful error result back.

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

Use above annotation if someone is facing :--org.hibernate.jpa.HibernatePersistenceProvider persistence provider when it attempted to create the container entity manager factory for the paymentenginePU persistence unit. The following error occurred: [PersistenceUnit: paymentenginePU] Unable to build Hibernate SessionFactory ** This is a solution if you are using Audit table.@Audit

Use:- @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) on superclass.

Get each line from textarea

You could use PHP constant:

$array = explode(PHP_EOL, $text);

additional notes:
1. For me this is the easiest and the safest way because it is cross platform compatible (Windows/Linux etc.)
2. It is better to use PHP CONSTANT whenever you can for faster execution

Angular 2: Get Values of Multiple Checked Checkboxes

I have find a solution thanks to Gunter! Here is my whole code if it could help anyone:

<div class="form-group">
            <label for="options">Options :</label>
            <div *ngFor="#option of options; #i = index">
                <label>
                    <input type="checkbox"
                           name="options"
                           value="{{option}}"
                           [checked]="options.indexOf(option) >= 0"
                           (change)="updateCheckedOptions(option, $event)"/>
                    {{option}}
                </label>
            </div>
        </div>

Here are the 3 objects I'm using:

options = ['OptionA', 'OptionB', 'OptionC'];
optionsMap = {
        OptionA: false,
        OptionB: false,
        OptionC: false,
};
optionsChecked = [];

And there are 3 useful methods:

1. To initiate optionsMap:

initOptionsMap() {
    for (var x = 0; x<this.order.options.length; x++) {
        this.optionsMap[this.options[x]] = true;
    }
}

2. to update the optionsMap:

updateCheckedOptions(option, event) {
   this.optionsMap[option] = event.target.checked;
}

3. to convert optionsMap into optionsChecked and store it in options before sending the POST request:

updateOptions() {
    for(var x in this.optionsMap) {
        if(this.optionsMap[x]) {
            this.optionsChecked.push(x);
        }
    }
    this.options = this.optionsChecked;
    this.optionsChecked = [];
}

How to iterate over arguments in a Bash script

aparse() {
while [[ $# > 0 ]] ; do
  case "$1" in
    --arg1)
      varg1=${2}
      shift
      ;;
    --arg2)
      varg2=true
      ;;
  esac
  shift
done
}

aparse "$@"

How to create the pom.xml for a Java project with Eclipse

If you have plugin for Maven in Eclipse, you can do following:

  • right click on your project -> Maven -> Enable Dependency Management

This will convert your project to Maven and creates a pom.xml. Fast and simple...

how to set length of an column in hibernate with maximum length

@Column(name = Columns.COLUMN_NAME, columnDefinition = "NVARCHAR(MAX)")

max indicates that the maximum storage size is 2^31-1 bytes (2 GB)

Reading rows from a CSV file in Python

The Easiest way is this way :

from csv import reader

# open file in read mode
with open('file.csv', 'r') as read_obj:
    # pass the file object to reader() to get the reader object
    csv_reader = reader(read_obj)
    # Iterate over each row in the csv using reader object
    for row in csv_reader:
        # row variable is a list that represents a row in csv
        print(row)

output:
['Year:', 'Dec:', 'Jan:']
['1', '50', '60']
['2', '25', '50']
['3', '30', '30']
['4', '40', '20']
['5', '10', '10']

Bootstrap - Removing padding or margin when screen size is smaller

Another css that can make the margin problem is that you have direction:someValue in your css, so just remove it by setting it to initial.

For example:

body {
     direction:rtl;
 }
@media (max-width: 480px) {
    body {
     direction:initial;
    }
}

What does the NS prefix mean?

It is the NextStep (= NS) heritage. NeXT was the computer company that Steve Jobs formed after he quit Apple in 1985, and NextStep was it's operating system (UNIX based) together with the Obj-C language and runtime. Together with it's libraries and tools, NextStep was later renamed OpenStep (which was also the name on an API that NeXT developed together with Sun), which in turn later became Cocoa.

These different names are actually quite confusing (especially since some of the names differs only in which characters are upper or lower case..), try this for an explanation:

TheMerger OpenstepConfusion

setAttribute('display','none') not working

It works for me

setAttribute('style', 'display:none');

display Java.util.Date in a specific format

You already has this (that's what you entered) parse will parse a date into a giving format and print the full date object (toString).

Get file content from URL?

Don't forget: to get HTTPS contents, your OPENSSL extension should be enabled in your php.ini. (how to get contents of site use HTTPS)

Check if the number is integer

Once can also use dplyr::near:

library(dplyr)

near(a, as.integer(a))

It applies to any vector a, and has an optional tolerance parameter.

creating list of objects in Javascript

Maybe you can create an array like this:

     var myList = new Array();
     myList.push('Hello');
     myList.push('bye');

     for (var i = 0; i < myList .length; i ++ ){
        window.console.log(myList[i]);
     }

get value from DataTable

You can try changing it to this:

If myTableData.Rows.Count > 0 Then
  For i As Integer = 0 To myTableData.Rows.Count - 1
    ''Dim DataType() As String = myTableData.Rows(i).Item(1)
    ListBox2.Items.Add(myTableData.Rows(i)(1))
  Next
End If

Note: Your loop needs to be one less than the row count since it's a zero-based index.

Removing the fragment identifier from AngularJS urls (# symbol)

This answer assumes that you are using nginx as reverse proxy and you already did set $locationProvider.html5mode to true.

->For the people who might still be struggling with all cool stuff above.

Surely, @maxim grach solution works fine, but for the solution for how to respond to requests that doesn't want the hashtag to be included in the first place what can be done is check if php is sending 404 and then rewrite the url. Following is the code for nginx,

In the php location, detect 404 php error and redirect to another location,

location ~ \.php${
  ...
  fastcgi_intercept_errors on;
  error_page 404 = /redirect/$request_uri ;
}

Then rewrite url in redirect location and proxy_pass the data, offcourse, put your website url at the place of my blog's url. (Request : Question this only after you tried it)

location /redirect {
  rewrite ^/redirect/(.*) /$1;
  proxy_pass http://www.techromance.com;
}

And see the magic.

And it definitely works, atleast for me.

Spring 3 MVC resources and tag <mvc:resources />

It works for me:

<mvc:resources mapping="/static/**" location="/static/"/>
<mvc:default-servlet-handler />
<mvc:annotation-driven />

What are CN, OU, DC in an LDAP search?

  • CN = Common Name
  • OU = Organizational Unit
  • DC = Domain Component

These are all parts of the X.500 Directory Specification, which defines nodes in a LDAP directory.

You can also read up on LDAP data Interchange Format (LDIF), which is an alternate format.

You read it from right to left, the right-most component is the root of the tree, and the left most component is the node (or leaf) you want to reach.

Each = pair is a search criteria.

With your example query

("CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com");

In effect the query is:

From the com Domain Component, find the google Domain Component, and then inside it the gl Domain Component and then inside it the gp Domain Component.

In the gp Domain Component, find the Organizational Unit called Distribution Groups and then find the the object that has a common name of Dev-India.

How to convert a string to integer in C?

Robust C89 strtol-based solution

With:

  • no undefined behavior (as could be had with the atoi family)
  • a stricter definition of integer than strtol (e.g. no leading whitespace nor trailing trash chars)
  • classification of the error case (e.g. to give useful error messages to users)
  • a "testsuite"
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

typedef enum {
    STR2INT_SUCCESS,
    STR2INT_OVERFLOW,
    STR2INT_UNDERFLOW,
    STR2INT_INCONVERTIBLE
} str2int_errno;

/* Convert string s to int out.
 *
 * @param[out] out The converted int. Cannot be NULL.
 *
 * @param[in] s Input string to be converted.
 *
 *     The format is the same as strtol,
 *     except that the following are inconvertible:
 *
 *     - empty string
 *     - leading whitespace
 *     - any trailing characters that are not part of the number
 *
 *     Cannot be NULL.
 *
 * @param[in] base Base to interpret string in. Same range as strtol (2 to 36).
 *
 * @return Indicates if the operation succeeded, or why it failed.
 */
str2int_errno str2int(int *out, char *s, int base) {
    char *end;
    if (s[0] == '\0' || isspace(s[0]))
        return STR2INT_INCONVERTIBLE;
    errno = 0;
    long l = strtol(s, &end, base);
    /* Both checks are needed because INT_MAX == LONG_MAX is possible. */
    if (l > INT_MAX || (errno == ERANGE && l == LONG_MAX))
        return STR2INT_OVERFLOW;
    if (l < INT_MIN || (errno == ERANGE && l == LONG_MIN))
        return STR2INT_UNDERFLOW;
    if (*end != '\0')
        return STR2INT_INCONVERTIBLE;
    *out = l;
    return STR2INT_SUCCESS;
}

int main(void) {
    int i;
    /* Lazy to calculate this size properly. */
    char s[256];

    /* Simple case. */
    assert(str2int(&i, "11", 10) == STR2INT_SUCCESS);
    assert(i == 11);

    /* Negative number . */
    assert(str2int(&i, "-11", 10) == STR2INT_SUCCESS);
    assert(i == -11);

    /* Different base. */
    assert(str2int(&i, "11", 16) == STR2INT_SUCCESS);
    assert(i == 17);

    /* 0 */
    assert(str2int(&i, "0", 10) == STR2INT_SUCCESS);
    assert(i == 0);

    /* INT_MAX. */
    sprintf(s, "%d", INT_MAX);
    assert(str2int(&i, s, 10) == STR2INT_SUCCESS);
    assert(i == INT_MAX);

    /* INT_MIN. */
    sprintf(s, "%d", INT_MIN);
    assert(str2int(&i, s, 10) == STR2INT_SUCCESS);
    assert(i == INT_MIN);

    /* Leading and trailing space. */
    assert(str2int(&i, " 1", 10) == STR2INT_INCONVERTIBLE);
    assert(str2int(&i, "1 ", 10) == STR2INT_INCONVERTIBLE);

    /* Trash characters. */
    assert(str2int(&i, "a10", 10) == STR2INT_INCONVERTIBLE);
    assert(str2int(&i, "10a", 10) == STR2INT_INCONVERTIBLE);

    /* int overflow.
     *
     * `if` needed to avoid undefined behaviour
     * on `INT_MAX + 1` if INT_MAX == LONG_MAX.
     */
    if (INT_MAX < LONG_MAX) {
        sprintf(s, "%ld", (long int)INT_MAX + 1L);
        assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);
    }

    /* int underflow */
    if (LONG_MIN < INT_MIN) {
        sprintf(s, "%ld", (long int)INT_MIN - 1L);
        assert(str2int(&i, s, 10) == STR2INT_UNDERFLOW);
    }

    /* long overflow */
    sprintf(s, "%ld0", LONG_MAX);
    assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);

    /* long underflow */
    sprintf(s, "%ld0", LONG_MIN);
    assert(str2int(&i, s, 10) == STR2INT_UNDERFLOW);

    return EXIT_SUCCESS;
}

GitHub upstream.

Based on: https://stackoverflow.com/a/6154614/895245

How to create a XML object from String in Java?

If you can create a string xml you can easily transform it to the xml document object e.g. -

String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";  

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
DocumentBuilder builder;  
try {  
    builder = factory.newDocumentBuilder();  
    Document document = builder.parse(new InputSource(new StringReader(xmlString)));  
} catch (Exception e) {  
    e.printStackTrace();  
} 

You can use the document object and xml parsing libraries or xpath to get back the ip address.

How to use JavaScript to change the form action

I wanted to use JavaScript to change a form's action, so I could have different submit inputs within the same form linking to different pages.

I also had the added complication of using Apache rewrite to change example.com/page-name into example.com/index.pl?page=page-name. I found that changing the form's action caused example.com/index.pl (with no page parameter) to be rendered, even though the expected URL (example.com/page-name) was displayed in the address bar.

To get around this, I used JavaScript to insert a hidden field to set the page parameter. I still changed the form's action, just so the address bar displayed the correct URL.

function setAction (element, page)
{
  if(checkCondition(page))
  {
    /* Insert a hidden input into the form to set the page as a parameter.
     */
    var input = document.createElement("input");
    input.setAttribute("type","hidden");
    input.setAttribute("name","page");
    input.setAttribute("value",page);
    element.form.appendChild(input);

    /* Change the form's action. This doesn't chage which page is displayed,
     * it just make the URL look right.
     */
    element.form.action = '/' + page;
    element.form.submit();
  }
}

In the form:

<input type="submit" onclick='setAction(this,"my-page")' value="Click Me!" />

Here are my Apache rewrite rules:

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/index.pl?page=$1&%{QUERY_STRING}

I'd be interested in any explanation as to why just setting the action didn't work.

Install a Nuget package in Visual Studio Code

If you're working with .net core, you can use the dotnet CLI, for instance

dotnet add package <package name>

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

Autoreload of modules in IPython

If you add file ipython_config.py into the ~/.ipython/profile_default directory with lines like below, then the autoreload functionality will be loaded on IPython startup (tested on 2.0.0):

print "--------->>>>>>>> ENABLE AUTORELOAD <<<<<<<<<------------"

c = get_config()
c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')

How can I restore the MySQL root user’s full privileges?

I had denied insert and reload privileges to root. So after updating permissions, FLUSH PRIVILEGES was not working (due to lack of reload privilege). So I used debian-sys-maint user on Ubuntu 16.04 to restore user.root privileges. You can find password of user.debian-sys-maint from this file

sudo cat /etc/mysql/debian.cnf

How do I use extern to share variables between source files?

extern simply means a variable is defined elsewhere (e.g., in another file).

How to align entire html body to the center?

You can try:

body{ margin:0 auto; }

Maximum and minimum values in a textbox

Here's a simple function that does what you need:

<script type="text/javascript">
function minmax(value, min, max) 
{
    if(parseInt(value) < min || isNaN(parseInt(value))) 
        return min; 
    else if(parseInt(value) > max) 
        return max; 
    else return value;
}
</script>
<input type="text" name="textWeight" id="txtWeight" maxlength="5" onkeyup="this.value = minmax(this.value, 0, 100)"/>

If the input is not numeric it replaces it with a zero

How to get current working directory in Java?

Who says your main class is in a file on a local harddisk? Classes are more often bundled inside JAR files, and sometimes loaded over the network or even generated on the fly.

So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.

Disable a Maven plugin defined in a parent POM

The thread is old, but maybe someone is still interested. The shortest form I found is further improvement on the example from ?lex and bmargulies. The execution tag will look like:

<execution>
    <id>TheNameOfTheRelevantExecution</id>
    <phase/>
</execution>

2 points I want to highlight:

  1. phase is set to nothing, which looks less hacky than 'none', though still a hack.
  2. id must be the same as execution you want to override. If you don't specify id for execution, Maven will do it implicitly (in a way not expected intuitively by you).

After posting found it is already in stackoverflow: In a Maven multi-module project, how can I disable a plugin in one child?

add new element in laravel collection object

I have solved this if you are using array called for 2 tables. Example you have, $tableA['yellow'] and $tableA['blue'] . You are getting these 2 values and you want to add another element inside them to separate them by their type.

foreach ($tableA['yellow'] as $value) {
    $value->type = 'YELLOW';  //you are adding new element named 'type'
}

foreach ($tableA['blue'] as $value) {
    $value->type = 'BLUE';  //you are adding new element named 'type'
}

So, both of the tables value will have new element called type.

What is the C# equivalent of NaN or IsNumeric?

You can still use the Visual Basic function in C#. The only thing you have to do is just follow my instructions shown below:

  1. Add the reference to the Visual Basic Library by right clicking on your project and selecting "Add Reference":

enter image description here

  1. Then import it in your class as shown below:

    using Microsoft.VisualBasic;

  2. Next use it wherever you want as shown below:

                if (!Information.IsNumeric(softwareVersion))
            {
                throw new DataException(string.Format("[{0}] is an invalid App Version!  Only numeric values are supported at this time.", softwareVersion));
            }
    

Hope, this helps and good luck!

Converting a year from 4 digit to 2 digit and back again in C#

This should work for you:

public int Get4LetterYear(int twoLetterYear)
{
    int firstTwoDigits =
        Convert.ToInt32(DateTime.Now.Year.ToString().Substring(2, 2));
    return Get4LetterYear(twoLetterYear, firstTwoDigits);
}

public int Get4LetterYear(int twoLetterYear, int firstTwoDigits)
{
    return Convert.ToInt32(firstTwoDigits.ToString() + twoLetterYear.ToString());
}

public int Get2LetterYear(int fourLetterYear)
{
    return Convert.ToInt32(fourLetterYear.ToString().Substring(2, 2));
}

I don't think there are any special built-in stuff in .NET.

Update: It's missing some validation that you maybe should do. Validate length of inputted variables, and so on.

Compare two Lists for differences

I think you're looking for a method like this:

public static IEnumerable<TResult> CompareSequences<T1, T2, TResult>(IEnumerable<T1> seq1,
    IEnumerable<T2> seq2, Func<T1, T2, TResult> comparer)
{
    var enum1 = seq1.GetEnumerator();
    var enum2 = seq2.GetEnumerator();

    while (enum1.MoveNext() && enum2.MoveNext())
    {
        yield return comparer(enum1.Current, enum2.Current);
    }
}

It's untested, but it should do the job nonetheless. Note that what's particularly useful about this method is that it's full generic, i.e. it can take two sequences of arbitrary (and different) types and return objects of any type.

This solution of course assumes that you want to compare the nth item of seq1 with the nth item in seq2. If you want to do match the elements in the two sequences based on a particular property/comparison, then you'll want to perform some sort of join operation (as suggested by danbruc using Enumerable.Join. Do let me know if it neither of these approaches is quite what I'm after and maybe I can suggest something else.

Edit: Here's an example of how you might use the CompareSequences method with the comparer function you originally posted.

// Prints out to the console all the results returned by the comparer function (CompareTwoClass_ReturnDifferences in this case).
var results = CompareSequences(list1, list2, CompareTwoClass_ReturnDifferences);
int index;    

foreach(var element in results)
{
    Console.WriteLine("{0:#000} {1}", index++, element.ToString());
}

Understanding the Gemfile.lock file

What does the exclamation mark after the gem name in the 'DEPENDECIES' group mean?

The exclamation mark appears when the gem was installed using a source other than "https://rubygems.org".

Regular expression for a string that does not start with a sequence

You could use a negative look-ahead assertion:

^(?!tbd_).+

Or a negative look-behind assertion:

(^.{1,3}$|^.{4}(?<!tbd_).*)

Or just plain old character sets and alternations:

^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*

Import CSV file into SQL Server

I know this is not the exact solution to the question above, but for me, it was a nightmare when I was trying to Copy data from one database located at a separate server to my local.

I was trying to do that by first export data from the Server to CSV/txt and then import it to my local table.

Both solutions: with writing down the query to import CSV or using the SSMS Import Data wizard was always producing errors (errors were very general, saying that there is parsing problem). And although I wasn't doing anything special, just export to CSV and then trying to import CSV to the local DB, the errors were always there.

I was trying to look at the mapping section and the data preview, but there was always a big mess. And I know the main problem was comming from one of the table columns, which was containing JSON and SQL parser was treating that wrongly.

So eventually, I came up with a different solution and want to share it in case if someone else will have a similar problem.


What I did is that I've used the Exporting Wizard on the external Server.

Here are the steps to repeat the same process:
1) Right click on the database and select Tasks -> Export Data...

2) When Wizard will open, choose Next and in the place of "Data Source:" choose "SQL Server Native Client".

enter image description here

In case of external Server you will most probably have to choose "Use SQL Server Authentication" for the "Authentication Mode:".

3) After hitting Next, you have to select the Destionation.
For that, select again "SQL Server Native Client".
This time you can provide your local (or some other external DB) DB.

enter image description here

4) After hitting the Next button, you have two options either to copy the entire table from one DB to another or write down the query to specify the exact data to be copied. In my case, I didn't need the entire table (it was too large), but just some part of it, so I've chosen "Write a query to specify the data to transfer".

enter image description here

I would suggest writing down and testing the query on a separate query editor before moving to Wizard.

5) And finally, you need to specify the destination table where the data will be selected.

enter image description here

I suggest to leave it as [dbo].[Query] or some custom Table name in case if you will have errors exporting the data or if you are not sure about the data and want further analyze it before moving to the exact table you want.

And now go straight to the end of the Wizard by hitting Next/Finish buttons.

Excel formula to display ONLY month and year?

There are a number of ways to go about this. One way would be to enter the date 8/1/2013 manually in the first cell (say A1 for example's sake) and then in B1 type the following formula (and then drag it across):

=DATE(YEAR(A1),MONTH(A1)+1,1)

Since you only want to see month and year, you can format accordingly using the different custom date formats available.

The format you're looking for is YY-Mmm.

Trying to get property of non-object in

$sidemenu is not an object, so you can't call methods on it. It is probably not being sent to your view, or $sidemenus is empty.

Delete a dictionary item if the key exists

You can use dict.pop:

 mydict.pop("key", None)

Note that if the second argument, i.e. None is not given, KeyError is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.

How to test web service using command line curl

From the documentation on http://curl.haxx.se/docs/httpscripting.html :

HTTP Authentication

curl --user name:password http://www.example.com 

Put a file to a HTTP server with curl:

curl --upload-file uploadfile http://www.example.com/receive.cgi

Send post data with curl:

curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi

How to prevent downloading images and video files from my website?

Images must be downloaded in order to be viewed by the client. Videos are a similar case, in many scenarios. You can setup proxy scripts to serve the files out, but that doesn't really solve the issue of preventing the user from getting their own copy. For a more thorough discussion of this topic, see the question How can I prevent/make it hard to download my flash video?

Query grants for a table in postgres

Adding on to @shruti's answer

To query grants for all tables in a schema for a given user

select a.tablename, 
       b.usename, 
       HAS_TABLE_PRIVILEGE(usename,tablename, 'select') as select,
       HAS_TABLE_PRIVILEGE(usename,tablename, 'insert') as insert, 
       HAS_TABLE_PRIVILEGE(usename,tablename, 'update') as update, 
       HAS_TABLE_PRIVILEGE(usename,tablename, 'delete') as delete, 
       HAS_TABLE_PRIVILEGE(usename,tablename, 'references') as references 
from pg_tables a, 
     pg_user b 
where schemaname='your_schema_name' 
      and b.usename='your_user_name' 
order by tablename;

android edittext onchange listener

TextWatcher didn't work for me as it kept firing for every EditText and messing up each others values.

Here is my solution:

public class ConsultantTSView extends Activity {
    .....

    //Submit is called when I push submit button.
    //I wanted to retrieve all EditText(tsHours) values in my HoursList

    public void submit(View view){

        ListView TSDateListView = (ListView) findViewById(R.id.hoursList);
        String value = ((EditText) TSDateListView.getChildAt(0).findViewById(R.id.tsHours)).getText().toString();
    }
}

Hence by using the getChildAt(xx) method you can retrieve any item in the ListView and get the individual item using findViewById. And it will then give the most recent value.

HTML code for an apostrophe

Firstly, it would appear that &apos; should be avoided - The curse of &apos;

Secondly, if there is ever any chance that you're going to generate markup to be returned via AJAX calls, you should avoid the entity names (As not all of the HTML entities are valid in XML) and use the &#XXXX; syntax instead.

Failure to do so may result in the markup being considered as invalid XML.

The entity that is most likely to be affected by this is &nbsp;, which should be replaced by &#160;

Could not find an implementation of the query pattern

Make sure these references are included:

  • System.Data.Linq
  • System.Data.Entity

Then add the using statement

using System.Linq;

Python: What OS am I running on?

For Jython the only way to get os name I found is to check os.name Java property (tried with sys, os and platform modules for Jython 2.5.3 on WinXP):

def get_os_platform():
    """return platform name, but for Jython it uses os.name Java property"""
    ver = sys.platform.lower()
    if ver.startswith('java'):
        import java.lang
        ver = java.lang.System.getProperty("os.name").lower()
    print('platform: %s' % (ver))
    return ver

How to get the file name from a full path using JavaScript?

The following line of JavaScript code will give you the file name.

var z = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
alert(z);

Getting rid of bullet points from <ul>

Assuming that didn't work, you might want to combine the id-based selector with the li in order to apply the css to the li elements:

#otis li {
    list-style-type: none;
}

Reference:

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

Use SELECT inside an UPDATE query

I had a similar problem. I wanted to find a string in one column and put that value in another column in the same table. The select statement below finds the text inside the parens.

When I created the query in Access I selected all fields. On the SQL view for that query, I replaced the mytable.myfield for the field I wanted to have the value from inside the parens with

SELECT Left(Right(OtherField,Len(OtherField)-InStr((OtherField),"(")), 
            Len(Right(OtherField,Len(OtherField)-InStr((OtherField),"(")))-1) 

I ran a make table query. The make table query has all the fields with the above substitution and ends with INTO NameofNewTable FROM mytable

CMake not able to find OpenSSL library

Same problem, and fixed it on my centos 6.5 using the following command.

yum install openssl-devel

git push rejected: error: failed to push some refs

I did the following steps to resolve the issue. On the branch which was giving me the error:

  1. git pull origin [branch-name]<current branch>
  2. After pulling, got some merge issues, solved them, pushed the changes to the same branch.
  3. Created the Pull request with the pushed branch... tada, My changes were reflecting, all of them.

How to distinguish mouse "click" and "drag"

All these solutions either break on tiny mouse movements, or are overcomplicated.

Here is a simple adaptable solution using two event listeners. Delta is the distance in pixels that you must move horizontally or vertically between the up and down events for the code to classify it as a drag rather than a click. This is because sometimes you will move the mouse or your finger a few pixels before lifting it.

const delta = 6;
let startX;
let startY;

element.addEventListener('mousedown', function (event) {
  startX = event.pageX;
  startY = event.pageY;
});

element.addEventListener('mouseup', function (event) {
  const diffX = Math.abs(event.pageX - startX);
  const diffY = Math.abs(event.pageY - startY);

  if (diffX < delta && diffY < delta) {
    // Click!
  }
});

Java multiline string

JEP 378: Text Blocks covers this functionality and is included in JDK 15. It first appeared as JEP 355: Text Blocks (Preview) in JDK 13 and JEP 368: Text Blocks (Second Preview) in JDK 14 and can be enabled in these versions with the ––enable–preview javac option.

The syntax allows to write something like:

String s = """
           text
           text
           text
           """;

Previous to this JEP, in JDK 12, JEP 326: Raw String Literals aimed to implement a similar feature, but it was eventually withdrawn:

Please note: This was intended to be a preview language feature in JDK 12, but it was withdrawn and did not appear in JDK 12. It was superseded by Text Blocks (JEP 355) in JDK 13.

How to convert string to XML using C#

Use LoadXml Method of XmlDocument;

string xml = "<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer></body></head>";
xDoc.LoadXml(xml);

How to Implement DOM Data Binding in JavaScript

Things have changed a lot in the last 7 years, we have native web components in most browsers now. IMO the core of the problem is sharing state between elements, once you have that its trivial to update the ui when state changes and vice versa.

To share data between elements you can create a StateObserver class, and extend your web components from that. A minimal implementation looks something like this:

_x000D_
_x000D_
// create a base class to handle state_x000D_
class StateObserver extends HTMLElement {_x000D_
 constructor () {_x000D_
   super()_x000D_
    StateObserver.instances.push(this)_x000D_
  }_x000D_
 stateUpdate (update) {_x000D_
   StateObserver.lastState = StateObserver.state_x000D_
    StateObserver.state = update_x000D_
    StateObserver.instances.forEach((i) => {_x000D_
     if (!i.onStateUpdate) return_x000D_
     i.onStateUpdate(update, StateObserver.lastState)_x000D_
    })_x000D_
  }_x000D_
}_x000D_
_x000D_
StateObserver.instances = []_x000D_
StateObserver.state = {}_x000D_
StateObserver.lastState = {}_x000D_
_x000D_
// create a web component which will react to state changes_x000D_
class CustomReactive extends StateObserver {_x000D_
 onStateUpdate (state, lastState) {_x000D_
   if (state.someProp === lastState.someProp) return_x000D_
    this.innerHTML = `input is: ${state.someProp}`_x000D_
  }_x000D_
}_x000D_
customElements.define('custom-reactive', CustomReactive)_x000D_
_x000D_
class CustomObserved extends StateObserver {_x000D_
 connectedCallback () {_x000D_
   this.querySelector('input').addEventListener('input', (e) => {_x000D_
     this.stateUpdate({ someProp: e.target.value })_x000D_
    })_x000D_
  }_x000D_
}_x000D_
customElements.define('custom-observed', CustomObserved)
_x000D_
<custom-observed>_x000D_
  <input>_x000D_
</custom-observed>_x000D_
<br />_x000D_
<custom-reactive></custom-reactive>
_x000D_
_x000D_
_x000D_

fiddle here

I like this approach because:

  • no dom traversal to find data- properties
  • no Object.observe (deprecated)
  • no Proxy (which provides a hook but no communication mechanism anyway)
  • no dependencies, (other than a polyfill depending on your target browsers)
  • it's reasonably centralised & modular... describing state in html, and having listeners everywhere would get messy very quickly.
  • it's extensible. This basic implementation is 20 lines of code, but you could easily build up some convenience, immutability, and state shape magic to make it easier to work with.

Entity framework self referencing loop detected

The message error means that you have a self referencing loop.

The json you produce is like this example (with a list of one employee) :

[
employee1 : {
    name: "name",
    department : {
        name: "departmentName",
        employees : [
            employee1 : {
                name: "name",
                department : {
                    name: "departmentName",
                    employees : [
                        employee1 : {
                            name: "name",
                            department : {
                                and again and again....
                            }
                    ]
                }
            }
        ]
    }
}

]

You have to tell the db context that you don't want to get all linked entities when you request something. The option for DbContext is Configuration.LazyLoadingEnabled

The best way I found is to create a context for serialization :

public class SerializerContext : LabEntities 
{
    public SerializerContext()
    {
        this.Configuration.LazyLoadingEnabled = false;
    }
}

Check if current date is between two dates Oracle SQL

SELECT to_char(emp_login_date,'DD-MON-YYYY HH24:MI:SS'),A.* 
FROM emp_log A
WHERE emp_login_date BETWEEN to_date(to_char('21-MAY-2015 11:50:14'),'DD-MON-YYYY HH24:MI:SS')
AND
to_date(to_char('22-MAY-2015 17:56:52'),'DD-MON-YYYY HH24:MI:SS') 
ORDER BY emp_login_date

Create normal zip file programmatically

My 2 cents:

    using (ZipArchive archive = ZipFile.Open(zFile, ZipArchiveMode.Create))
    {
        foreach (var fPath in filePaths)
        {
            archive.CreateEntryFromFile(fPath,Path.GetFileName(fPath));
        }
    }

So Zip files could be created directly from files/dirs.

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 set cellpadding and cellspacing in table with CSS?

The padding inside a table-divider (TD) is a padding property applied to the cell itself.

CSS

td, th {padding:0}

The spacing in-between the table-dividers is a space between cell borders of the TABLE. To make it effective, you have to specify if your table cells borders will 'collapse' or be 'separated'.

CSS

table, td, th {border-collapse:separate}
table {border-spacing:6px}

Try this : https://www.google.ca/search?num=100&newwindow=1&q=css+table+cellspacing+cellpadding+site%3Astackoverflow.com ( 27 100 results )

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();

Create a asmx web service in C# using visual studio 2013

on the web site box, you have selected .NETFramework 4.5 and it doesn show, so click there and choose the 3.5...i hope it helps.

How to pass multiple parameters in thread in VB

Dim evaluator As New Thread(Sub() Me.testthread(goodList, 1))
With evaluator
.IsBackground = True ' not necessary...
.Start()
End With

generate random double numbers in c++

Here's how

double fRand(double fMin, double fMax)
{
    double f = (double)rand() / RAND_MAX;
    return fMin + f * (fMax - fMin);
}

Remember to call srand() with a proper seed each time your program starts.

[Edit] This answer is obsolete since C++ got it's native non-C based random library (see Alessandro Jacopsons answer) But, this still applies to C

Good Java graph algorithm library?

Instructional graph algorithm implementations in java could be found here (by prof. Sedgewick et al.): http://algs4.cs.princeton.edu/code/

I was introduced to them while attending these exceptional algorithm courses on coursera (also taught by prof. Sedgewick):

https://www.coursera.org/course/algs4partI

https://www.coursera.org/course/algs4partII

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

in Xcode 8 use:

DispatchQueue.global(qos: .userInitiated).async { }

Stored procedure with default parameters

I wrote with parameters that are predefined

They are not "predefined" logically, somewhere inside your code. But as arguments of SP they have no default values and are required. To avoid passing those params explicitly you have to define default values in SP definition:

Alter Procedure [Test]
    @StartDate AS varchar(6) = NULL, 
    @EndDate AS varchar(6) = NULL
AS
...

NULLs or empty strings or something more sensible - up to you. It does not matter since you are overwriting values of those arguments in the first lines of SP.

Now you can call it without passing any arguments e.g. exec dbo.TEST

how to make password textbox value visible when hover an icon

As these guys said, just change input type.
But do not forget to change type back as well.

See my simple jquery demo: http://jsfiddle.net/kPJbU/1/

HTML:

<input name="password" class="password" type="password" />
<div class="icon">icon</div>

jQuery:

$('.icon').hover(function () {
    $('.password').attr('type', 'text');
}, function () {
    $('.password').attr('type', 'password');
});

Find when a file was deleted in Git

Git log but you need to prefix the path with --

Eg:

dan-mac:test dani$ git log file1.txt
fatal: ambiguous argument 'file1.txt': unknown revision or path not in the working tree.

dan-mac:test dani$ git log -- file1.txt
 commit 0f7c4e1c36e0b39225d10b26f3dea40ad128b976
 Author: Daniel Palacio <[email protected]>
 Date:   Tue Jul 26 23:32:20 2011 -0500

 foo

script to map network drive

Here a JScript variant of JohnB's answer

// Below the MSDN page for MapNetworkDrive Method with link and in case if Microsoft breaks it like every now and then the path to the documentation of now.
// https://msdn.microsoft.com/en-us/library/8kst88h6(v=vs.84).aspx
// MSDN Library -> Web Development -> Scripting -> JScript and VBScript -> Windows Scripting -> Windows Script Host -> Reference (Windows Script Host) -> Methods (Windows Script Host) -> MapNetworkDrive Method

var WshNetwork = WScript.CreateObject('WScript.Network');
function localNameInUse(localName) {
    var driveIterator = WshNetwork.EnumNetworkDrives();
    for (var i=0, l=driveIterator.length; i < l; i += 2) {
        if (driveIterator.Item(i) == localName) {
            return true;
        }
    }
    return false;
}

function mount(localName, remoteName) {
    if (localNameInUse(localName)) {
        WScript.Echo('"' + localName + '" drive letter already in use.');
    } else {
        WshNetwork.MapNetworkDrive(localName, remoteName);
    }
}

function unmount(localName) {
    if (localNameInUse(localName)) {
        WshNetwork.RemoveNetworkDrive(localName);
    }
}

HTTP response code for POST when resource already exists

Late to the game maybe but I stumbled upon this semantics issue while trying to make a REST API.

To expand a little on Wrikken's answer, I think you could use either 409 Conflict or 403 Forbidden depending on the situation - in short, use a 403 error when the user can do absolutely nothing to resolve the conflict and complete the request (e.g. they can't send a DELETE request to explicitly remove the resource), or use 409 if something could possibly be done.

10.4.4 403 Forbidden

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

Nowadays, someone says "403" and a permissions or authentication issue comes to mind, but the spec says that it's basically the server telling the client that it's not going to do it, don't ask it again, and here's why the client shouldn't.

As for PUT vs. POST... POST should be used to create a new instance of a resource when the user has no means to or shouldn't create an identifier for the resource. PUT is used when the resource's identity is known.

9.6 PUT

...

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,

it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

You could also do a for loop as you would for an array but instead of array[i] you would use list.get(i)

for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
}

How do I create directory if it doesn't exist to create a file?

As @hitec said, you have to be sure that you have the right permissions, if you do, you can use this line to ensure the existence of the directory:

Directory.CreateDirectory(Path.GetDirectoryName(filePath))

Changing SVG image color with javascript

For the background color - the fill property can be accessed like so:

svgElement.style.fill = '#fff';

To set the border color, do the same for the stroke property.

Please refer to the W3C reference on SVG, as it's a broad issue.

Shell script to get the process ID on Linux

You can use the command killall:

$ killall ruby

How to add property to a class dynamically?

Only way to dynamically attach a property is to create a new class and its instance with your new property.

class Holder: p = property(lambda x: vs[i], self.fn_readonly)
setattr(self, k, Holder().p)

Measure the time it takes to execute a t-sql query

If you want a more accurate measurement than the answer above:

set statistics time on 

-- Query 1 goes here

-- Query 2 goes here

set statistics time off

The results will be in the Messages window.

Update (2015-07-29):

By popular request, I have written a code snippet that you can use to time an entire stored procedure run, rather than its components. Although this only returns the time taken by the last run, there are additional stats returned by sys.dm_exec_procedure_stats that may also be of value:

-- Use the last_elapsed_time from sys.dm_exec_procedure_stats
-- to time an entire stored procedure.

-- Set the following variables to the name of the stored proc
-- for which which you would like run duration info
DECLARE @DbName NVARCHAR(128);
DECLARE @SchemaName SYSNAME;
DECLARE @ProcName SYSNAME=N'TestProc';

SELECT CONVERT(TIME(3),DATEADD(ms,ROUND(last_elapsed_time/1000.0,0),0)) 
       AS LastExecutionTime
FROM sys.dm_exec_procedure_stats
WHERE OBJECT_NAME(object_id,database_id)=@ProcName AND
      (OBJECT_SCHEMA_NAME(object_id,database_id)=@SchemaName OR @SchemaName IS NULL) AND
      (DB_NAME(database_id)=@DbName OR @DbName IS NULL)

How to copy text programmatically in my Android app?

Unless your app is the default input method editor (IME) or is the app that currently has focus, your app cannot access clipboard data on Android 10 or higher. https://developer.android.com/about/versions/10/privacy/changes#clipboard-data

Datetime in where clause

select * from tblErrorLog
where errorDate BETWEEN '12/20/2008' AND DATEADD(DAY, 1, '12/20/2008')

How do I configure git to ignore some files locally?

Both --assume-unchanged and --skip-worktree are NOT A CORRECT WAY to ignore files locally... Kindly check this answer and the notes in the documentation of git update-index. Files that for any reason keep changing frequently (and/or change from a clone to another) and their changes should not be committed, then these files SHOULD NOT be tracked in the first place.

However, the are two proper ways to ignore files locally (both work with untracked files). Either to put files names in .git/info/exclude file which is the local alternative of .gitignore but specific to the current clone. Or to use a global .gitignore (which should be properly used only for common auxiliary files e.g. pyz, pycache, etc) and the file will be ignored in any git repo in your machine.

To make the above as kind of automated (adding to exclude or global .gitignore), you can use the following commands (add to your bash-profile):

  • Per clone local exclude (Note that you should be in the root of the repository when calling the command because of using the relative path), change ##FILE-NAME## to .git/info/exclude
  • Global .gitignore, first make global .gitignore here then change ##FILE-NAME## to ~/.gitignore

Linux

alias git-ignore='echo $1 >> ##FILE-NAME##'
alias git-show-ignored='cat ##FILE-NAME##'
git-unignore(){
  GITFILETOUNIGNORE=${1//\//\\\/}
  sed -i "/$GITFILETOUNIGNORE/d" ##FILE-NAME##
  unset GITFILETOUNIGNORE
}

MacOS (you need the .bak for sed inplace modifications (i.e. you are forced to add a file extension to inplace sed. i.e. make a backup before replacing something), therefore to delete the .bak file I added rm filename.bak)

alias git-ignore='echo $1 >> ##FILE-NAME##'
alias git-show-ignored='cat ##FILE-NAME##'
git-unignore(){
  GITFILETOUNIGNORE=${1//\//\\\/}
  sed -i.bak "/$GITFILETOUNIGNORE/d" ##FILE-NAME##
  rm ##FILE-NAME##.bak
  unset GITFILETOUNIGNORE
}

Then you can do:

git-ignore example_file.txt
git-unignore example_file.txt

Unique on a dataframe with only selected columns

Ok, if it doesn't matter which value in the non-duplicated column you select, this should be pretty easy:

dat <- data.frame(id=c(1,1,3),id2=c(1,1,4),somevalue=c("x","y","z"))
> dat[!duplicated(dat[,c('id','id2')]),]
  id id2 somevalue
1  1   1         x
3  3   4         z

Inside the duplicated call, I'm simply passing only those columns from dat that I don't want duplicates of. This code will automatically always select the first of any ambiguous values. (In this case, x.)

Create a HTML table where each TR is a FORM

I second Harmen's div suggestion. Alternatively, you can wrap the table in a form, and use javascript to capture the row focus and adjust the form action via javascript before submit.

How do I escape a string inside JavaScript code inside an onClick handler?

In JavaScript you can encode single quotes as "\x27" and double quotes as "\x22". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \x27 \x22 with impunity without fear of any embedded quotes "breaking out" of your string.

\xXX is for chars < 127, and \uXXXX for Unicode, so armed with this knowledge you can create a robust JSEncode function for all characters that are out of the usual whitelist.

For example,

<a href="#" onclick="SelectSurveyItem('<% JSEncode(itemid) %>', '<% JSEncode(itemname) %>'); return false;">Select</a>

How to perform Join between multiple tables in LINQ lambda

What you've seen is what you get - and it's exactly what you asked for, here:

(ppc, c) => new { productproductcategory = ppc, category = c}

That's a lambda expression returning an anonymous type with those two properties.

In your CategorizedProducts, you just need to go via those properties:

CategorizedProducts catProducts = query.Select(
      m => new { 
             ProdId = m.productproductcategory.product.Id, 
             CatId = m.category.CatId, 
             // other assignments 
           });

Iframe transparent background

I've used this creating an IFrame through Javascript and it worked for me:

// IFrame points to the IFrame element, obviously
IFrame.src = 'about: blank';
IFrame.style.backgroundColor = "transparent";
IFrame.frameBorder = "0";
IFrame.allowTransparency="true";

Not sure if it makes any difference, but I set those properties before adding the IFrame to the DOM. After adding it to the DOM, I set its src to the real URL.

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

---- Remove Constraint ----
EXEC sp_MSForEachTable "ALTER TABLE ? NOCHECK CONSTRAINT all"

---- Delete Data ----
EXEC sp_MSForEachTable "DELETE FROM ?"

---- Add Constraint ----
EXEC sp_MSForEachTable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

---- Reset Identity value ----
EXEC sp_MSForEachTable "DBCC CHECKIDENT ( '?', RESEED, 0)"

Keyboard shortcuts with jQuery

I recently wrote a standalone library for this. It does not require jQuery, but you can use it with jQuery no problem. It's called Mousetrap.

You can check it out at http://craig.is/killing/mice

How to get last key in an array?

It is strange, but why this topic is not have this answer:

$lastKey = array_keys($array)[count($array)-1];

Number input type that takes only integers?

From the specs

step="any" or positive floating-point number
Specifies the value granularity of the element’s value.

So you could simply set it to 1:

How to output only captured groups with sed?

Try

sed -n -e "/[0-9]/s/^[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\).*$/\1 \2 \3 \4 \5 \6 \7 \8 \9/p"

I got this under cygwin:

$ (echo "asdf"; \
   echo "1234"; \
   echo "asdf1234adsf1234asdf"; \
   echo "1m2m3m4m5m6m7m8m9m0m1m2m3m4m5m6m7m8m9") | \
  sed -n -e "/[0-9]/s/^[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\).*$/\1 \2 \3 \4 \5 \6 \7 \8 \9/p"

1234
1234 1234
1 2 3 4 5 6 7 8 9
$

WAMP shows error 'MSVCR100.dll' is missing when install

Step 1. Uninstall WAMP

Step 2. Install the latest Microsoft Visual C++ 2015 Redistributable Update 3

Step 3. Restart System

Step 4. Re-install WAMP

Make sure Skype is not signed in. You don't want to know details if you are a newbie :)

how to prevent css inherit

The short story is that it's not possible to do what you want here. There's no CSS rule which is to "ignore some other rule". The only way around it is to write a more-specific CSS rule for the inner elements which reverts it to how it was before, which is a pain in the butt.

Take the example below:

<div class="red"> <!-- ignore the semantics, it's an example, yo! -->
    <p class="blue">
        Blue text blue text!
        <span class="notBlue">this shouldn't be blue</span>
    </p>
</div>
<div class="green">
    <p class="blue">
        Blue text!
        <span class="notBlue">blah</span>
    </p>
</div>

There's no way to make the .notBlue class revert to the parent styling. The best you can do is this:

.red, .red .notBlue {
    color: red;
}
.green, .green .notBlue {
    color: green;
}

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

Got stupid error. So post here, if anyone find it useful

  1. [-\._] - means hyphen, dot and underscore
  2. [\.-_] - means all signs in range from dot to underscore

How do I get the width and height of a HTML5 canvas?

Here's a CodePen that uses canvas.height/width, CSS height/width, and context to correctly render any canvas at any size.

HTML:

<button onclick="render()">Render</button>
<canvas id="myCanvas" height="100" width="100" style="object-fit:contain;"></canvas>

CSS:

canvas {
  width: 400px;
  height: 200px;
  border: 1px solid red;
  display: block;
}

Javascript:

const myCanvas = document.getElementById("myCanvas");
const originalHeight = myCanvas.height;
const originalWidth = myCanvas.width;
render();
function render() {
  let dimensions = getObjectFitSize(
    true,
    myCanvas.clientWidth,
    myCanvas.clientHeight,
    myCanvas.width,
    myCanvas.height
  );
  myCanvas.width = dimensions.width;
  myCanvas.height = dimensions.height;

  let ctx = myCanvas.getContext("2d");
  let ratio = Math.min(
    myCanvas.clientWidth / originalWidth,
    myCanvas.clientHeight / originalHeight
  );
  ctx.scale(ratio, ratio); //adjust this!
  ctx.beginPath();
  ctx.arc(50, 50, 50, 0, 2 * Math.PI);
  ctx.stroke();
}

// adapted from: https://www.npmjs.com/package/intrinsic-scale
function getObjectFitSize(
  contains /* true = contain, false = cover */,
  containerWidth,
  containerHeight,
  width,
  height
) {
  var doRatio = width / height;
  var cRatio = containerWidth / containerHeight;
  var targetWidth = 0;
  var targetHeight = 0;
  var test = contains ? doRatio > cRatio : doRatio < cRatio;

  if (test) {
    targetWidth = containerWidth;
    targetHeight = targetWidth / doRatio;
  } else {
    targetHeight = containerHeight;
    targetWidth = targetHeight * doRatio;
  }

  return {
    width: targetWidth,
    height: targetHeight,
    x: (containerWidth - targetWidth) / 2,
    y: (containerHeight - targetHeight) / 2
  };
}

Basically, canvas.height/width sets the size of the bitmap you are rendering to. The CSS height/width then scales the bitmap to fit the layout space (often warping it as it scales it). The context can then modify it's scale to draw, using vector operations, at different sizes.

Does java.util.List.isEmpty() check if the list itself is null?

In addition to Lion's answer i can say that you better use if(CollectionUtils.isNotEmpty(test)){...} This also checks for null, so no manual check is not needed.

Process list on Linux via Python

You can use a third party library, such as PSI:

PSI is a Python package providing real-time access to processes and other miscellaneous system information such as architecture, boottime and filesystems. It has a pythonic API which is consistent accross all supported platforms but also exposes platform-specific details where desirable.

How to remove element from ArrayList by checking its value?

You should check API for these questions.

You can use remove methods.

a.remove(1);

OR

a.remove("acbd");

How do I center a window onscreen in C#?

If you want to center your windows during runtime use the code below, copy it into your application:

protected void ReallyCenterToScreen()
{
  Screen screen = Screen.FromControl(this);

  Rectangle workingArea = screen.WorkingArea;
  this.Location = new Point() {
    X = Math.Max(workingArea.X, workingArea.X + (workingArea.Width - this.Width) / 2),
    Y = Math.Max(workingArea.Y, workingArea.Y + (workingArea.Height - this.Height) / 2)};
}

And finally call the method above to get it working:

ReallyCenterToScreen();

C# - Fill a combo box with a DataTable

string strConn = "Data Source=SEZSW08;Initial Catalog=Nidhi;Integrated Security=True";
SqlConnection Con = new SqlConnection(strConn);
Con.Open();
string strCmd = "select companyName from companyinfo where CompanyName='" + cmbCompName.SelectedValue + "';";
SqlDataAdapter da = new SqlDataAdapter(strCmd, Con);
DataSet ds = new DataSet();
Con.Close();
da.Fill(ds);
cmbCompName.DataSource = ds;
cmbCompName.DisplayMember = "CompanyName";
cmbCompName.ValueMember = "CompanyName";
//cmbCompName.DataBind();
cmbCompName.Enabled = true;

How to disable spring security for particular url

If you want to ignore multiple API endpoints you can use as follow:

 @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests() 
            .antMatchers("/api/v1/**").authenticated()
            .antMatchers("api/v1/authenticate**").permitAll()
            .antMatchers("**").permitAll()
            .and().exceptionHandling().and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

Simply install Win64 OpenSSL v1.0.2a or Win32 OpenSSL v1.0.2a, you can download these from http://slproweb.com/products/Win32OpenSSL.html. Works out of the box, no configuration needed.

Using the "start" command with parameters passed to the started program

Change The "Virtual PC.exe" to a name without space like "VirtualPC.exe" in the folder. When you write start "path" with "" the CMD starts a new cmd window with the path as the title. Change the name to a name without space,write this on Notepad and after this save like Name.cmd or Name.bat:

CD\
CD Program Files
CD Microsoft Virtual PC
start VirtualPC.exe
timeout 2
exit

This command will redirect the CMD to the folder,start the VirualPC.exe,wait 2 seconds and exit.

Call a VBA Function into a Sub Procedure

Calling a Sub Procedure – 3 Way technique

Once you have a procedure, whether you created it or it is part of the Visual Basic language, you can use it. Using a procedure is also referred to as calling it.

Before calling a procedure, you should first locate the section of code in which you want to use it. To call a simple procedure, type its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"

msgbox strFullName
End Sub

Sub Exercise()
    CreateCustomer
End Sub

Besides using the name of a procedure to call it, you can also precede it with the Call keyword. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    Call CreateCustomer
End Sub

When calling a procedure, without or without the Call keyword, you can optionally type an opening and a closing parentheses on the right side of its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    CreateCustomer()
End Sub

Procedures and Access Levels

Like a variable access, the access to a procedure can be controlled by an access level. A procedure can be made private or public. To specify the access level of a procedure, precede it with the Private or the Public keyword. Here is an example:

Private Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

The rules that were applied to global variables are the same:

Private: If a procedure is made private, it can be called by other procedures of the same module. Procedures of outside modules cannot access such a procedure.

Also, when a procedure is private, its name does not appear in the Macros dialog box

Public: A procedure created as public can be called by procedures of the same module and by procedures of other modules.

Also, if a procedure was created as public, when you access the Macros dialog box, its name appears and you can run it from there

Create or update mapping in elasticsearch

Generally speaking, you can update your index mapping using the put mapping api (reference here) :

curl -XPUT 'http://localhost:9200/advert_index/_mapping/advert_type' -d '
{
    "advert_type" : {
        "properties" : {

          //your new mapping properties

        }
    }
}
'

It's especially useful for adding new fields. However, in your case, you will try to change the location type, which will cause a conflict and prevent the new mapping from being used.

You could use the put mapping api to add another property containing the location as a lat/lon array, but you won't be able to update the previous location field itself.

Finally, you will have to reindex your data for your new mapping to be taken into account.

The best solution would really be to create a new index.

If your problem with creating another index is downtime, you should take a look at aliases to make things go smoothly.

What does "select count(1) from table_name" on any database tables mean?

Depending on who you ask, some people report that executing select count(1) from random_table; runs faster than select count(*) from random_table. Others claim they are exactly the same.

This link claims that the speed difference between the 2 is due to a FULL TABLE SCAN vs FAST FULL SCAN.

Why java.security.NoSuchProviderException No such provider: BC?

you can add security provider by editing java.security by adding security.provider.=org.bouncycastle.jce.provider.BouncyCastleProvider

or add a line in your top of your class

Security.addProvider(new BouncyCastleProvider());

you can use below line to specify provider while specifying algorithms

Cipher cipher = Cipher.getInstance("AES", "SunJCE");

if you are using other provider like Bouncy Castle then

Cipher cipher =  Cipher.getInstance("AES", "BC");

How to install a specific version of a ruby gem?

Linux

To install different version of ruby, check the latest version of package using apt as below:

$ apt-cache madison ruby
      ruby |    1:1.9.3 | http://ftp.uk.debian.org/debian/ wheezy/main amd64 Packages
      ruby |        4.5 | http://ftp.uk.debian.org/debian/ squeeze/main amd64 Packages

Then install it:

$ sudo apt-get install ruby=1:1.9.3

To check what's the current version, run:

$ gem --version # Check for the current user.
$ sudo gem --version # Check globally.

If the version is still old, you may try to switch the version to new by using ruby version manager (rvm) by:

rvm 1.9.3

Note: You may prefix it by sudo if rvm was installed globally. Or run /usr/local/rvm/scripts/rvm if your command rvm is not in your global PATH. If rvm installation process failed, see the troubleshooting section.


Troubleshooting:

  • If you still have the old version, you may try to install rvm (ruby version manager) via:

    sudo apt-get install curl # Install curl first
    curl -sSL https://get.rvm.io | bash -s stable --ruby # Install only for the user.
    #or:# curl -sSL https://get.rvm.io | sudo bash -s stable --ruby # Install globally. 
    

    then if installed locally (only for current user), load rvm via:

    source /usr/local/rvm/scripts/rvm; rvm 1.9.3
    

    if globally (for all users), then:

    sudo bash -c "source /usr/local/rvm/scripts/rvm; rvm 1.9.3"
    
  • if you still having problem with the new ruby version, try to install it by rvm via:

    source /usr/local/rvm/scripts/rvm && rvm install ruby-1.9.3 # Locally.
    sudo bash -c "source /usr/local/rvm/scripts/rvm && rvm install ruby-1.9.3" # Globally.
    
  • if you'd like to install some gems globally and you have rvm already installed, you may try:

    rvmsudo gem install [gemname]
    

    instead of:

      gem install [gemname] # or:
      sudo gem install [gemname]
    

Note: It's prefered to NOT use sudo to work with RVM gems. When you do sudo you are running commands as root, another user in another shell and hence all of the setup that RVM has done for you is ignored while the command runs under sudo (such things as GEM_HOME, etc...). So to reiterate, as soon as you 'sudo' you are running as the root system user which will clear out your environment as well as any files it creates are not able to be modified by your user and will result in strange things happening.

Connect over ssh using a .pem file

You can connect to a AWS ec-2 instance using the following commands.

chmod 400 mykey.pem

ssh -i mykey.pem username@your-ip

by default the machine name usually be like ubuntu since usually ubuntu machine is used as a server so the following command will work in that case.

ssh -i mykey.pem ubuntu@your-ip

MySQL Trigger - Storing a SELECT in a variable

`CREATE TRIGGER `category_before_ins_tr` BEFORE INSERT ON `category`
  FOR EACH ROW
BEGIN
    **SET @tableId= (SELECT id FROM dummy LIMIT 1);**

END;`;

I cannot access tomcat admin console?

Your tomcat-users.xml looks good.

Make sure you have the manager/ application inside your $CATALINA_BASE/webapps/

  • Linux:

You have to install tomcat-admin package: sudo apt-get install tomcat8-admin (for version 8)

  • Windows:

I am using Eclipse. I had to copy the manager/ folder from C:\Program Files\apache-tomcat-8.5.20\webapps to my Eclipse workspace (~\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\).

How to handle the new window in Selenium WebDriver using Java?

                string BaseWindow = driver.CurrentWindowHandle;
                ReadOnlyCollection<string> handles = driver.WindowHandles;
                foreach (string handle in handles)
                {
                    if (handle != BaseWindow)
                    {
                        string title = driver.SwitchTo().Window(handle).Title;
                        Thread.Sleep(3000);
                        driver.SwitchTo().Window(handle).Title.Equals(title);
                        Thread.Sleep(3000);
                    }
                }

How to set a string's color

I created an API called JCDP, former JPrinter, which stands for Java Colored Debug Printer. For Linux it uses the ANSI escape codes that WhiteFang mentioned, but abstracts them using words instead of codes which is much more intuitive. For Windows it actually includes the JAnsi library but creates an abstraction layer over it, maintaining the intuitive and simple interface created for Linux.

This library is licensed under the MIT License so feel free to use it.

Have a look at JCDP's github repository.

Put byte array to JSON and vice versa

If your byte array may contain runs of ASCII characters that you'd like to be able to see, you might prefer BAIS (Byte Array In String) format instead of Base64. The nice thing about BAIS is that if all the bytes happen to be ASCII, they are converted 1-to-1 to a string (e.g. byte array {65,66,67} becomes simply "ABC") Also, BAIS often gives you a smaller file size than Base64 (this isn't guaranteed).

After converting the byte array to a BAIS string, write it to JSON like you would any other string.

Here is a Java class (ported from the original C#) that converts byte arrays to string and back.

import java.io.*;
import java.lang.*;
import java.util.*;

public class ByteArrayInString
{
  // Encodes a byte array to a string with BAIS encoding, which 
  // preserves runs of ASCII characters unchanged.
  //
  // For simplicity, this method's base-64 encoding always encodes groups of 
  // three bytes if possible (as four characters). This decision may 
  // unfortunately cut off the beginning of some ASCII runs.
  public static String convert(byte[] bytes) { return convert(bytes, true); }
  public static String convert(byte[] bytes, boolean allowControlChars)
  {
    StringBuilder sb = new StringBuilder();
    int i = 0;
    int b;
    while (i < bytes.length)
    {
      b = get(bytes,i++);
      if (isAscii(b, allowControlChars))
        sb.append((char)b);
      else {
        sb.append('\b');
        // Do binary encoding in groups of 3 bytes
        for (;; b = get(bytes,i++)) {
          int accum = b;
          System.out.println("i="+i);
          if (i < bytes.length) {
            b = get(bytes,i++);
            accum = (accum << 8) | b;
            if (i < bytes.length) {
              b = get(bytes,i++);
              accum = (accum << 8) | b;
              sb.append(encodeBase64Digit(accum >> 18));
              sb.append(encodeBase64Digit(accum >> 12));
              sb.append(encodeBase64Digit(accum >> 6));
              sb.append(encodeBase64Digit(accum));
              if (i >= bytes.length)
                break;
            } else {
              sb.append(encodeBase64Digit(accum >> 10));
              sb.append(encodeBase64Digit(accum >> 4));
              sb.append(encodeBase64Digit(accum << 2));
              break;
            }
          } else {
            sb.append(encodeBase64Digit(accum >> 2));
            sb.append(encodeBase64Digit(accum << 4));
            break;
          }
          if (isAscii(get(bytes,i), allowControlChars) &&
            (i+1 >= bytes.length || isAscii(get(bytes,i), allowControlChars)) &&
            (i+2 >= bytes.length || isAscii(get(bytes,i), allowControlChars))) {
            sb.append('!'); // return to ASCII mode
            break;
          }
        }
      }
    }
    return sb.toString();
  }

  // Decodes a BAIS string back to a byte array.
  public static byte[] convert(String s)
  {
    byte[] b;
    try {
      b = s.getBytes("UTF8");
    } catch(UnsupportedEncodingException e) { 
      throw new RuntimeException(e.getMessage());
    }
    for (int i = 0; i < b.length - 1; ++i) {
      if (b[i] == '\b') {
        int iOut = i++;

        for (;;) {
          int cur;
          if (i >= b.length || ((cur = get(b, i)) < 63 || cur > 126))
            throw new RuntimeException("String cannot be interpreted as a BAIS array");
          int digit = (cur - 64) & 63;
          int zeros = 16 - 6; // number of 0 bits on right side of accum
          int accum = digit << zeros;

          while (++i < b.length)
          {
            if ((cur = get(b, i)) < 63 || cur > 126)
              break;
            digit = (cur - 64) & 63;
            zeros -= 6;
            accum |= digit << zeros;
            if (zeros <= 8)
            {
              b[iOut++] = (byte)(accum >> 8);
              accum <<= 8;
              zeros += 8;
            }
          }

          if ((accum & 0xFF00) != 0 || (i < b.length && b[i] != '!'))
            throw new RuntimeException("String cannot be interpreted as BAIS array");
          i++;

          // Start taking bytes verbatim
          while (i < b.length && b[i] != '\b')
            b[iOut++] = b[i++];
          if (i >= b.length)
            return Arrays.copyOfRange(b, 0, iOut);
          i++;
        }
      }
    }
    return b;
  }

  static int get(byte[] bytes, int i) { return ((int)bytes[i]) & 0xFF; }

  public static int decodeBase64Digit(char digit)
    { return digit >= 63 && digit <= 126 ? (digit - 64) & 63 : -1; }
  public static char encodeBase64Digit(int digit)
    { return (char)((digit + 1 & 63) + 63); }
  static boolean isAscii(int b, boolean allowControlChars)
    { return b < 127 && (b >= 32 || (allowControlChars && b != '\b')); }
}

See also: C# unit tests.

How to enable CORS on Firefox?

This Firefox add-on may work for you:

https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/

It can toggle CORS on and off for development purposes.

Parse JSON from HttpURLConnection object

The JSON string will just be the body of the response you get back from the URL you have called. So add this code

...
BufferedReader in = new BufferedReader(new InputStreamReader(
                            conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) 
    System.out.println(inputLine);
in.close();

That will allow you to see the JSON being returned to the console. The only missing piece you then have is using a JSON library to read that data and provide you with a Java representation.

Here's an example using JSON-LIB

How do I encode URI parameter values?

I think that the URI class is the one that you are looking for.

How to fix missing dependency warning when using useEffect React Hook?

Add this comment on the top of your file to disable warning.

/* eslint-disable react-hooks/exhaustive-deps */

Default nginx client_max_body_size

Pooja Mane's answer worked for me, but I had to put the client_max_body_size variable inside of http section.

enter image description here

GSON - Date format

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create();

Above format seems better to me as it has precision up to millis.

Running Jupyter via command line on Windows

In windows 10: If you used anaconda3 for Jupyter notebook installation and forgot to check the box to add the environment variables to the system during installation, you need to add the following environment variables to the "Path" variable manually: (search windows settings for Edit environment variables")

Environment variables for Anaconda3

Standard Android menu icons, for example refresh

After seeing this post I found a useful link:

http://developer.android.com/design/downloads/index.html

You can download a lot of sources editable with Fireworks, Illustrator, Photoshop, etc...
And there's also fonts and icon packs.

Here is a stencil example.

How to set Spring profile from system variable?

You can set the spring profile by supplying -Dspring.profiles.active=<env>

For java files in source(src) directory, you can use by System.getProperty("spring.profiles.active")

For java files in test directory you can supply

  • SPRING_PROFILES_ACTIVE to <env>

OR

Since, "environment", "jvmArgs" and "systemProperties" are ignored for the "test" task. In root build.gradle add a task to set jvm property and environment variable.

test {
    def profile = System.properties["spring.profiles.active"]
    systemProperty "spring.profiles.active",profile
    environment "SPRING.PROFILES_ACTIVE", profile
    println "Running ${project} tests with profile: ${profile}"
}

How to SHUTDOWN Tomcat in Ubuntu?

I had a similar problem and found the following command to work:

sudo systemctl stop tomcat

After running this command you can type the following to verify that it is "disabled":

systemctl list-units

output for systemctl list-units

How to maximize a plt.show() window using Python

Try using 'Figure.set_size_inches' method, with the extra keyword argument forward=True. According to the documentation, this should resize the figure window.

Whether that actually happens will depend on the operating system you are using.

Spring: @Component versus @Bean

@Component and @Bean do two quite different things, and shouldn't be confused.

@Component (and @Service and @Repository) are used to auto-detect and auto-configure beans using classpath scanning. There's an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach, since it's purely declarative.

@Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically as above. It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose.

To answer your question...

would it have been possible to re-use the @Component annotation instead of introducing @Bean annotation?

Sure, probably; but they chose not to, since the two are quite different. Spring's already confusing enough without muddying the waters further.

How to use the start command in a batch file?

An extra pair of rabbits' ears should do the trick.

start "" "C:\Program...

START regards the first quoted parameter as the window-title, unless it's the only parameter - and any switches up until the executable name are regarded as START switches.

Are table names in MySQL case sensitive?

Table names in MySQL are file system entries, so they are case insensitive if the underlying file system is.

How to count the NaN values in a column in pandas DataFrame

One other simple option not suggested yet, to just count NaNs, would be adding in the shape to return the number of rows with NaN.

df[df['col_name'].isnull()]['col_name'].shape

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Another option is to add the M2_HOME variable at: IntelliJ IDEA=>Preferences=>IDE Settings=>Path Variables

After a restart of IntelliJ, IntelliJ IDEA=>Preferences=>Project Settings=>Maven=>Maven home directory should be set to your M2_HOME variable.

How to auto-generate a C# class file from a JSON string

If you install Web Essentials into Visual studio you can go to Edit => Past special => paste JSON as class.

That is probably the easiest there is.

Web Essentials: http://vswebessentials.com/

If a DOM Element is removed, are its listeners also removed from memory?

regarding jQuery:

the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

Reference: http://api.jquery.com/remove/

jQuery v1.8.2 .remove() source code:

remove: function( selector, keepData ) {
    var elem,
        i = 0;

    for ( ; (elem = this[i]) != null; i++ ) {
        if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
            if ( !keepData && elem.nodeType === 1 ) {
                jQuery.cleanData( elem.getElementsByTagName("*") );
                jQuery.cleanData( [ elem ] );
            }

            if ( elem.parentNode ) {
                elem.parentNode.removeChild( elem );
            }
        }
    }

    return this;
}

apparently jQuery uses node.removeChild()

According to this : https://developer.mozilla.org/en-US/docs/DOM/Node.removeChild ,

The removed child node still exists in memory, but is no longer part of the DOM. You may reuse the removed node later in your code, via the oldChild object reference.

ie event listeners might get removed, but node still exists in memory.

Calculate distance between two points in google maps V3

Just add this to the beginning of your JavaScript code:

google.maps.LatLng.prototype.distanceFrom = function(latlng) {
  var lat = [this.lat(), latlng.lat()]
  var lng = [this.lng(), latlng.lng()]
  var R = 6378137;
  var dLat = (lat[1]-lat[0]) * Math.PI / 180;
  var dLng = (lng[1]-lng[0]) * Math.PI / 180;
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
  Math.cos(lat[0] * Math.PI / 180 ) * Math.cos(lat[1] * Math.PI / 180 ) *
  Math.sin(dLng/2) * Math.sin(dLng/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
  return Math.round(d);
}

and then use the function like this:

var loc1 = new GLatLng(52.5773139, 1.3712427);
var loc2 = new GLatLng(52.4788314, 1.7577444);
var dist = loc2.distanceFrom(loc1);
alert(dist/1000);

Cannot implicitly convert type 'int?' to 'int'.

You can change the last line to following (assuming you want to return 0 when there is nothing in db):

return OrdersPerHour == null ? 0 : OrdersPerHour.Value;

Delete files in subfolder using batch script

I had to complete the same task and I used a "for" loop and a "del" command as follows:

@ECHO OFF

set dir=%cd%

FOR /d /r %dir% %%x in (archive\) do (
    if exist "%%x" del %%x\*.txt /f /q
)

You can set the dir variable with any start directory you want or used the current directory (%cd%) variable.

These are the options for "for" command:

  • /d For directories
  • /r For recursive

These are the options for "del" command:

  • /f Force deletes read-only files
  • /q Quiet mode; suppresses prompts for delete confirmations.

should use size_t or ssize_t

ssize_t is not included in the standard and isn't portable. size_t should be used when handling the size of objects (there's ptrdiff_t too, for pointer differences).

Unicode character as bullet for list-item in CSS

Try this code...

li:before {
    content: "? "; /* caractère UTF-8 */
}

Get current URL with jQuery?

See purl.js. This will really help and can also be used, depending on jQuery. Use it like this:

$.url().param("yourparam");

When to use the JavaScript MIME type application/javascript instead of text/javascript?

The problem with Javascript's MIME type is that there hasn't been a standard for years. Now we've got application/javascript as an official MIME type.

But actually, the MIME type doesn't matter at all, as the browser can determine the type itself. That's why the HTML5 specs state that the type="text/javascript" is no longer required.

Messagebox with input field

You can do it by making form and displaying it using ShowDialogBox....

Form.ShowDialog Method - Shows the form as a modal dialog box.

Example:

public void ShowMyDialogBox()
{
   Form2 testDialog = new Form2();

   // Show testDialog as a modal dialog and determine if DialogResult = OK.
   if (testDialog.ShowDialog(this) == DialogResult.OK)
   {
      // Read the contents of testDialog's TextBox.
      this.txtResult.Text = testDialog.TextBox1.Text;
   }
   else
   {
      this.txtResult.Text = "Cancelled";
   }
   testDialog.Dispose();
}

Submit form without page reloading

You'll need to submit an ajax request to send the email without reloading the page. Take a look at http://api.jquery.com/jQuery.ajax/

Your code should be something along the lines of:

$('#submit').click(function() {
    $.ajax({
        url: 'send_email.php',
        type: 'POST',
        data: {
            email: '[email protected]',
            message: 'hello world!'
        },
        success: function(msg) {
            alert('Email Sent');
        }               
    });
});

The form will submit in the background to the send_email.php page which will need to handle the request and send the email.

Write Array to Excel Range

The kind of array definition seems the key: In my case it is a one dimension array of 17 items which have to convert to a two dimension array

Defintion for columns: object[,] Array = new object[17, 1];

Defintion for rows object[,] Array= new object[1,17];

The code for value2 is in both cases the same Excel.Range cell = activeWorksheet.get_Range(Range); cell.Value2 = Array;

LG Georg

Reading a plain text file in Java

This code I programmed is much faster for very large files:

public String readDoc(File f) {
    String text = "";
    int read, N = 1024 * 1024;
    char[] buffer = new char[N];

    try {
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);

        while(true) {
            read = br.read(buffer, 0, N);
            text += new String(buffer, 0, read);

            if(read < N) {
                break;
            }
        }
    } catch(Exception ex) {
        ex.printStackTrace();
    }

    return text;
}

How to convert 'binary string' to normal string in Python3?

If the answer from falsetru didn't work you could also try:

>>> b'a string'.decode('utf-8')
'a string'

How to pass an object into a state using UI-router?

In version 0.2.13, You should be able to pass objects into $state.go,

$state.go('myState', {myParam: {some: 'thing'}})

$stateProvider.state('myState', {
                url: '/myState/{myParam:json}',
                params: {myParam: null}, ...

and then access the parameter in your controller.

$stateParams.myParam //should be {some: 'thing'}

myParam will not show up in the URL.

Source:

See the comment by christopherthielen https://github.com/angular-ui/ui-router/issues/983, reproduced here for convenience:

christopherthielen: Yes, this should be working now in 0.2.13.

.state('foo', { url: '/foo/:param1?param2', params: { param3: null } // null is the default value });

$state.go('foo', { param1: 'bar', param2: 'baz', param3: { id: 35, name: 'what' } });

$stateParams in 'foo' is now { param1: 'bar', param2: 'baz', param3: { id: 35, name: 'what' } }

url is /foo/bar?param2=baz.

Excel: Searching for multiple terms in a cell

Another way

=IF(SUMPRODUCT(--(NOT(ISERR(SEARCH({"Gingrich","Obama","Romney"},C1)))))>0,"1","")

Also, if you keep a list of values in, say A1 to A3, then you can use

=IF(SUMPRODUCT(--(NOT(ISERR(SEARCH($A$1:$A$3,C1)))))>0,"1","")

The wildcards are not necessary at all in the Search() function, since Search() returns the position of the found string.

Converting int to bytes in Python 3

Some answers don't work with large numbers.

Convert integer to the hex representation, then convert it to bytes:

def int_to_bytes(number):
    hrepr = hex(number).replace('0x', '')
    if len(hrepr) % 2 == 1:
        hrepr = '0' + hrepr
    return bytes.fromhex(hrepr)

Result:

>>> int_to_bytes(2**256 - 1)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'

C++: what regex library should I use?

In C++ projects past, I have used PCRE with good success. It's very complete and well-tested since it's used in many high profile projects. And I see that Google has contributed a set of C++ wrappers for PCRE recently, too.

Determine if string is in list in JavaScript

EcmaScript 6 and up

If you're using ES6 or higher, the cleanest way is to construct an array of the items and use Array.includes:

['a', 'b', 'c'].includes('b')

This has some inherent benefits over indexOf because it can properly test for the presence of NaN in the list, and can match missing array elements such as the middle one in [1, , 2] to undefined. includes also works on JavaScript typed arrays such as Uint8Array.

If you're concerned about browser support (such as for IE or Edge), you can check Array.includes at CanIUse.Com, and if you want to target a browser or browser version that's missing includes, I recommend polyfill.io for polyfilling.

Without An Array

You could add a new isInList property to strings as follows:

if (!String.prototype.isInList) {
  Object.defineProperty(String.prototype, 'isInList', {
    get: () => function(...args) {
      let value = this.valueOf();
      for (let i = 0, l = args.length; i < l; i += 1) {
        if (arguments[i] === value) return true;
      }
      return false;
    }
  });
}

Then use it like so:

'fox'.isInList('weasel', 'fox', 'stoat') // true
'fox'.isInList('weasel', 'stoat') // false

You can do the same thing for Number.prototype.

Note that Object.defineProperty cannot be used in IE8 and earlier, or very old versions of other browsers. However, it is a far superior solution to String.prototype.isInList = function() { ... } because using simple assignment like that will create an enumerable property on String.prototype, which is more likely to break code.

Array.indexOf

If you are using a modern browser, indexOf always works. However, for IE8 and earlier you'll need a polyfill.

If indexOf returns -1, the item is not in the list. Be mindful though, that this method will not properly check for NaN, and while it can match an explicit undefined, it can’t match a missing element to undefined as in the array [1, , 2].

Polyfill for indexOf or includes in IE, or any other browser/version lacking support

If you don't want to use a service like polyfill.io as mentioned above, you can always include in your own source code standards-compliant custom polyfills. For example, Mozilla Developer Network has one for indexOf.

In this situation where I had to make a solution for Internet Explorer 7, I "rolled my own" simpler version of the indexOf() function that is not standards-compliant:

if (!Array.prototype.indexOf) {
   Array.prototype.indexOf = function(item) {
      var i = this.length;
      while (i--) {
         if (this[i] === item) return i;
      }
      return -1;
   }
}

However, I don't think modifying Array.prototype is the best answer in the long term. Modifying Object and Array prototypes in JavaScript can lead to serious bugs. You need to decide whether doing so is safe in your own environment. Of primary note is that iterating an array (when Array.prototype has added properties) with for ... in will return the new function name as one of the keys:

Array.prototype.blah = function() { console.log('blah'); };
let arr = [1, 2, 3];
for (let x in arr) { console.log(x); }
// Result:
0
1
2
blah // Extra member iterated over!

Your code may work now, but the moment someone in the future adds a third-party JavaScript library or plugin that isn't zealously guarding against inherited keys, everything can break.

The old way to avoid that breakage is, during enumeration, to check each value to see if the object actually has it as a non-inherited property with if (arr.hasOwnProperty(x)) and only then work with that x.

The new ES6 ways to avoid this extra-key problem are:

  1. Use of instead of in, for (let x of arr). However, unless you can guarantee that all of your code and third-party libraries strictly stick to this method, then for the purposes of this question you'll probably just want to use includes as stated above.

  2. Define your new properties on the prototype using Object.defineProperty(), as this will make the property (by default) non-enumerable. This only truly solves the problem if all the JavaScript libraries or modules you use also do this.

Evaluate if list is empty JSTL

There's also the function tags, a bit more flexible:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">

And here's the tag documentation.

Eclipse error: "Editor does not contain a main type"

private int user_movie_matrix[][];Th. should be `private int user_movie_matrix[][];.

private int user_movie_matrix[][]; should be private static int user_movie_matrix[][];

cfiltering(numberOfUsers, numberOfMovies); should be new cfiltering(numberOfUsers, numberOfMovies);

Whether or not the code works as intended after these changes is beyond the scope of this answer; there were several syntax/scoping errors.

Android: How to overlay a bitmap and draw over a bitmap?

I can't believe no one has answered this yet! A rare occurrence on SO!

1

The question doesn't quite make sense to me. But I'll give it a stab. If you're asking about direct drawing to a canvas (polygons, shading, text etc...) vs. loading a bitmap and blitting it onto the canvas that would depend on the complexity of your drawing. As the drawing gets more complex the CPU time required will increase accordingly. However, blitting a bitmap onto a canvas will always be a constant time which is proportional to the size of the bitmap.

2

Without knowing what "something" is how can I show you how to do it? You should be able to figure out #2 from the answer for #3.

3

Assumptions:

  • bmp1 is larger than bmp2.
  • You want them both overlaid from the top left corner.

        private Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
            Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
            Canvas canvas = new Canvas(bmOverlay);
            canvas.drawBitmap(bmp1, new Matrix(), null);
            canvas.drawBitmap(bmp2, new Matrix(), null);
            return bmOverlay;
        }
    

Merge / convert multiple PDF files into one PDF

Yet another option, useful is you want to select also the pages inside the documents to be merged:

pdfjoin image.jpg '-' doc_only_first_pages.pdf '1,2' doc_with_all_pages.pdf '-'

It comes with package texlive-extra-utils

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

In my case, it was related to the node version.

My project was using 12.18.3 but I was on 14.5.0

So npm rebuild node-sass didn't solve the issue on the wrong node version(14.5.0).

I switched to the correct version(12.18.3) so it worked.

Maven skip tests

The parameter -DskipTests may not work depending on your surefire-plugin version.

You can use "-Dmaven.test.skip.exec" instead of "-DskipTests"

Source: Surefire Parameter Details

Remove a folder from git tracking

I know this is an old thread but I just wanted to add a little as the marked solution didn't solve the problem for me (although I tried many times).

The only way I could actually stop git form tracking the folder was to do the following:

  1. Make a backup of the local folder and put in a safe place.
  2. Delete the folder from your local repo
  3. Make sure cache is cleared git rm -r --cached your_folder/
  4. Add your_folder/ to .gitignore
  5. Commit changes
  6. Add the backup back into your repo

You should now see that the folder is no longer tracked.

Don't ask me why just clearing the cache didn't work for me, I am not a Git super wizard but this is how I solved the issue.

How to use the read command in Bash?

Other bash alternatives that do not involve a subshell:

read str <<END             # here-doc
hello
END

read str <<< "hello"       # here-string

read str < <(echo hello)   # process substitution

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

You can still use NSDictionaries in Swift:

For Swift 4

 var nsDictionary: NSDictionary?
 if let path = Bundle.main.path(forResource: "Config", ofType: "plist") {
    nsDictionary = NSDictionary(contentsOfFile: path)
 }

For Swift 3+

if let path = Bundle.main.path(forResource: "Config", ofType: "plist"),
   let myDict = NSDictionary(contentsOfFile: path){
    // Use your myDict here
}

And older versions of Swift

var myDict: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") {
    myDict = NSDictionary(contentsOfFile: path)
}
if let dict = myDict {
    // Use your dict here
}

The NSClasses are still available and perfectly fine to use in Swift. I think they'll probably want to shift focus to swift soon, but currently the swift APIs don't have all the functionality of the core NSClasses.

How do I execute a program using Maven?

In order to execute multiple programs, I also needed a profiles section:

<profiles>
  <profile>
    <id>traverse</id>
    <activation>
      <property>
        <name>traverse</name>
      </property>
    </activation>
    <build>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <configuration>
            <executable>java</executable>
            <arguments>
              <argument>-classpath</argument>
              <argument>org.dhappy.test.NeoTraverse</argument>
            </arguments>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

This is then executable as:

mvn exec:exec -Ptraverse

jQuery get text as number

If anyone came here trying to do this with a decimal like me:

myFloat = parseFloat(myString);

If you just need an Int, that's well covered in the other answers.

What is the easiest way to install BLAS and LAPACK for scipy?

The SciPy installation page already recommends several ways of installing python with SciPy already included, such as WinPython.

Another way is to use wheels (a built-package format):

pip install SomePackage-1.0-py2.py3-none-any.whl

The wheel packages you can find on: http://www.lfd.uci.edu/~gohlke/pythonlibs/

For SciPy you need:

How to implement a Map with multiple keys?

It would seem to me that the methods you want in your question are supported directly by Map. The one(s) you'd seem to want are

put(K1 key, K2 key, V value)
put(K1 key, V value)
put(K2 key, V value)

Note that in map, get() and containsKey() etc all take Object arguments. There's nothing stopping you from using the one get() method to delegate to all the composite maps that you combine (as noted in your question and other answers). Perhaps you'd need type registration so you don't get class casting problems (if they're special + implemented naively.

A typed based registration would also allow you to retrieve the "correct" map to be used:

Map<T,V> getMapForKey(Class<T> keyClass){
  //Completely naive implementation - you actually need to 
  //iterate through the keys of the maps, and see if the keyClass argument
  //is a sub-class of the defined map type.  And then ordering matters with 
  //classes that implement multiple interfaces...
  Map<T,V> specificTypeMap = (Map<T,V) maps.get(keyClass);
  if (specificTypeMap == null){
     throw new IllegalArgumentException("There is no map keyed by class" + keyClass);
  }
  return maps.get(keyClass);
}

V put(Object key, V value) {
  //This bit requires generic suppression magic - but 
  //nothing leaves this class and you're testing it right? 
  //(You can assert that it *is* type-safe)
  Map map = getMapForKey(key.getClass());
  map.put(object, key);
}

void put(Object[] keys, V value) { //Or put(V value, Object ... keys)
   //Might want to catch exceptions for unsupported keys and log instead?
   .....
}

Just some ideas...

XML Schema (XSD) validation tool?

An XML editor for quick and easy XML validation is available at http://www.xml-buddy.com

You just need to run the installer and after that you can validate your XML files with an easy to use desktop application or the command-line. In addition you also get support for Schematron and RelaxNG. Batch validation is also supported...

Update 1/13/2012: The command line tool is free to use and uses Xerces as XML parser.

Conditionally Remove Dataframe Rows with R

Use the which function:

A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)

r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]

Efficiently sorting a numpy array in descending order?

Hello I was searching for a solution to reverse sorting a two dimensional numpy array, and I couldn't find anything that worked, but I think I have stumbled on a solution which I am uploading just in case anyone is in the same boat.

x=np.sort(array)
y=np.fliplr(x)

np.sort sorts ascending which is not what you want, but the command fliplr flips the rows left to right! Seems to work!

Hope it helps you out!

I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work. Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.

How to play .wav files with java

A class that will play a WAV file, blocking until the sound has finished playing:

class Sound implements Playable {

    private final Path wavPath;
    private final CyclicBarrier barrier = new CyclicBarrier(2);

    Sound(final Path wavPath) {

        this.wavPath = wavPath;
    }

    @Override
    public void play() throws LineUnavailableException, IOException, UnsupportedAudioFileException {

        try (final AudioInputStream audioIn = AudioSystem.getAudioInputStream(wavPath.toFile());
             final Clip clip = AudioSystem.getClip()) {

            listenForEndOf(clip);
            clip.open(audioIn);
            clip.start();
            waitForSoundEnd();
        }
    }

    private void listenForEndOf(final Clip clip) {

        clip.addLineListener(event -> {
            if (event.getType() == LineEvent.Type.STOP) waitOnBarrier();
        });
    }

    private void waitOnBarrier() {

        try {

            barrier.await();
        } catch (final InterruptedException ignored) {
        } catch (final BrokenBarrierException e) {

            throw new RuntimeException(e);
        }
    }

    private void waitForSoundEnd() {

        waitOnBarrier();
    }
}