Programs & Examples On #Kernel extension

Check if a value is in an array (C#)

Not very clear what your issue is, but it sounds like you want something like this:

    List<string> printer = new List<string>( new [] { "jupiter", "neptune", "pangea", "mercury", "sonic" } );

    if( printer.Exists( p => p.Equals( "jupiter" ) ) )
    {
        ...
    }

How to comment/uncomment in HTML code

I find this to be the bane of XML style document commenting too. There are XML editors like eclipse that can perform block commenting. Basically automatically add extra per line and remove them. May be they made it purposefully hard to comment that style of document it was supposed to be self explanatory with the tags after all.

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

This is the job for style property:

document.getElementById("remember").style.visibility = "visible";

How do you kill a Thread in Java?

The question is rather vague. If you meant “how do I write a program so that a thread stops running when I want it to”, then various other responses should be helpful. But if you meant “I have an emergency with a server I cannot restart right now and I just need a particular thread to die, come what may”, then you need an intervention tool to match monitoring tools like jstack.

For this purpose I created jkillthread. See its instructions for usage.

Windows 8.1 gets Error 720 on connect VPN

This solved my 720 problem. The idea is to change the driver of the faulty WAN to another network adaptar driver, and then we are able to uninstall the WAN device and then reboot the system.

https://forums.lenovo.com/t5/Windows-8-and-8-1/SOLVED-WAN-Miniport-2-yellow-exclamation-mark-in-Device-Manager/td-p/1051981

Algorithm to generate all possible permutations of a list?

Here's an implementation for ColdFusion (requires CF10 because of the merge argument to ArrayAppend() ):

public array function permutateArray(arr){

    if (not isArray(arguments.arr) ) {
        return ['The ARR argument passed to the permutateArray function is not of type array.'];    
    }

    var len = arrayLen(arguments.arr);
    var perms = [];
    var rest = [];
    var restPerms = [];
    var rpLen = 0;
    var next = [];

    //for one or less item there is only one permutation 
    if (len <= 1) {
        return arguments.arr;
    }

    for (var i=1; i <= len; i++) {
        // copy the original array so as not to change it and then remove the picked (current) element
        rest = arraySlice(arguments.arr, 1);
        arrayDeleteAt(rest, i);

         // recursively get the permutation of the rest of the elements
         restPerms = permutateArray(rest);
         rpLen = arrayLen(restPerms);

        // Now concat each permutation to the current (picked) array, and append the concatenated array to the end result
        for (var j=1; j <= rpLen; j++) {
            // for each array returned, we need to make a fresh copy of the picked(current) element array so as to not change the original array
            next = arraySlice(arguments.arr, i, 1);
            arrayAppend(next, restPerms[j], true);
            arrayAppend(perms, next);
        }
     }

    return perms;
}

Based on KhanSharp's js solution above.

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

In my case finish() executed immediately after a dialog has shown.

MySQL Workbench: "Can't connect to MySQL server on 127.0.0.1' (10061)" error

I have tried all the method. I will suggest you to reinstall it.

"replace" function examples

Be aware that the third parameter (value) in the examples given above: the value is a constant (e.g. 'Z' or c(20,30)).

Defining the third parameter using values from the data frame itself can lead to confusion.

E.g. with a simple data frame such as this (using dplyr::data_frame):

tmp <- data_frame(a=1:10, b=sample(LETTERS[24:26], 10, replace=T))

This will create somthing like this:

       a     b
   (int) (chr)
1      1     X
2      2     Y
3      3     Y
4      4     X
5      5     Z

..etc

Now suppose you want wanted to do, was to multiply the values in column 'a' by 2, but only where column 'b' is "X". My immediate thought would be something like this:

with(tmp, replace(a, b=="X", a*2))

That will not provide the desired outcome, however. The a*2 will defined as a fixed vector rather than a reference to the 'a' column. The vector 'a*2' will thus be

[1]  2  4  6  8 10 12 14 16 18 20

at the start of the 'replace' operation. Thus, the first row where 'b' equals "X", the value in 'a' will be placed by 2. The second time, it will be replaced by 4, etc ... it will not be replaced by two-times-the-value-of-a in that particular row.

How do I insert datetime value into a SQLite database?

You have to change the format of the date string you are supplying in order to be able to insert it using the STRFTIME function. Reason being, there is no option for a month abbreviation:

%d  day of month: 00
%f  fractional seconds: SS.SSS
%H  hour: 00-24
%j  day of year: 001-366
%J  Julian day number
%m  month: 01-12
%M  minute: 00-59
%s  seconds since 1970-01-01
%S  seconds: 00-59
%w  day of week 0-6 with sunday==0
%W  week of year: 00-53
%Y  year: 0000-9999
%%  % 

The alternative is to format the date/time into an already accepted format:

  1. YYYY-MM-DD
  2. YYYY-MM-DD HH:MM
  3. YYYY-MM-DD HH:MM:SS
  4. YYYY-MM-DD HH:MM:SS.SSS
  5. YYYY-MM-DDTHH:MM
  6. YYYY-MM-DDTHH:MM:SS
  7. YYYY-MM-DDTHH:MM:SS.SSS
  8. HH:MM
  9. HH:MM:SS
  10. HH:MM:SS.SSS
  11. now

Reference: SQLite Date & Time functions

Python: How do I make a subclass from a superclass?

class MySubClass(MySuperClass):
    def __init__(self):
        MySuperClass.__init__(self)

        # <the rest of your custom initialization code goes here>

The section on inheritance in the python documentation explains it in more detail

Comparing two .jar files

I use to ZipDiff lib (have both Java and ant API).

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

If getting this error while unit testing please write this.

import { RouterTestingModule } from '@angular/router/testing';
beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [RouterTestingModule],
    declarations: [AppComponent],
  });
}));

Conda command is not recognized on Windows 10

case #1 You should set 3 path:

%ANACONDAPATH%;
%ANACONDAPATH%\Scripts;
%ANACONDAPATH%\Library\bin;

It will solve problem:

C:\WINDOWS\system32>conda update conda
Solving environment: failed

CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.com/pkgs/msys2/noarch/repodata.json.bz2>
Elapsed: -
...

case #2 Also you can use Anaconda Promd (for Win10) instead CLI (cmd.exe)

The name 'ViewBag' does not exist in the current context

For MVC5, in case you are building an application from scratch. You need to add a web.config file to the Views folder and paste the following code in it.

<?xml version="1.0"?>
<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>
</configuration>

Note that for MVC 3 you will have to change version to 3.0.0.0 at

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

You may have to close and open the *.cshtml page again to see the changes.

Getting the application's directory from a WPF application

Try this. Don't forget using System.Reflection.

string baseDir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

The given key was not present in the dictionary. Which key?

In the general case, the answer is No.

However, you can set the debugger to break at the point where the exception is first thrown. At that time, the key which was not present will be accessible as a value in the call stack.

In Visual Studio, this option is located here:

Debug → Exceptions... → Common Language Runtime Exceptions → System.Collections.Generic

There, you can check the Thrown box.


For more specific instances where information is needed at runtime, provided your code uses IDictionary<TKey, TValue> and not tied directly to Dictionary<TKey, TValue>, you can implement your own dictionary class which provides this behavior.

Entity Framework 6 Code first Default value

It's been a while, but leaving a note for others. I achieved what is needed with an attribute and I decorated my model class fields with that attribute as I want.

[SqlDefaultValue(DefaultValue = "getutcdate()")]
public DateTime CreatedDateUtc { get; set; }

Got the help of these 2 articles:

What I did:

Define Attribute

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SqlDefaultValueAttribute : Attribute
{
    public string DefaultValue { get; set; }
}

In the "OnModelCreating" of the context

modelBuilder.Conventions.Add( new AttributeToColumnAnnotationConvention<SqlDefaultValueAttribute, string>("SqlDefaultValue", (p, attributes) => attributes.Single().DefaultValue));

In the custom SqlGenerator

private void SetAnnotatedColumn(ColumnModel col)
{
    AnnotationValues values;
    if (col.Annotations.TryGetValue("SqlDefaultValue", out values))
    {
         col.DefaultValueSql = (string)values.NewValue;
    }
}

Then in the Migration Configuration constructor, register the custom SQL generator.

SetSqlGenerator("System.Data.SqlClient", new CustomMigrationSqlGenerator());

Java Error: "Your security settings have blocked a local application from running"

After reading Java 7 Update 21 Security Improvements in Detail mention..

With the introduced changes it is most likely that no end-user is able to run your application when they are either self-signed or unsigned.

..I was wondering how this would go for loose class files - the 'simplest' applets of all.

Local file system

Dialog: Your security settings have blocked a local application from running
Your security settings have blocked a local application from running

That is the dialog seen for an applet consisting of loose class files being loaded off the local file system when the JRE is set to the default 'High' security setting.


Note that a slight quirk of the JRE only produced that on point 3 of.

  1. Load the applet page to see a broken applet symbol that leads to an empty console.
    Open the Java settings and set the level to Medium.
    Close browser & Java settings.
  2. Load the applet page to see the applet.
    Open the Java settings and set the level to High.
    Close browser & Java settings.
  3. Load the applet page to see a broken applet symbol & the above dialog.

Internet

If you load the simple applet (loose class file) seen at this resizable applet demo off the internet - which boasts an applet element of:

<applet
    code="PlafChanger.class"
    codebase="."
    alt="Pluggable Look'n'Feel Changer appears here if Java is enabled"
    width='100%'
    height='250'>
<p>Pluggable Look'n'Feel Changer appears here in a Java capable browser.</p>
</applet>

It also seems to load successfully. Implying that:-

Applets loaded from the local file system are now subject to a stricter security sandbox than those loaded from the internet or a local server.

Security settings descriptions

As of Java 7 update 51.

  • Very High: Most secure setting - Only Java applications identified by a non-expired certificate from a trusted authority will be allowed to run.
  • High (minimum recommended): Java applications identified by a certificate from a trusted authority will be allowed to run.
  • Medium - All Java applications will be allowed to run after presenting a security prompt.

Cannot refer to a non-final variable inside an inner class defined in a different method

Declare the variable as a static and reference it in the required method using className.variable

Java - Abstract class to contain variables?

Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.

Can Android Studio be used to run standard Java projects?

Here's exactly what the setup looks like.

enter image description here

Edit Configurations > '+' > Application: enter image description here

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

By initializing the min/max values to their extreme opposite, you avoid any edge cases of values in the input: Either one of min/max is in fact one of those values (in the case where the input consists of only one of those values), or the correct min/max will be found.

It should be noted that primitive types must have a value. If you used Objects (ie Integer), you could initialize value to null and handle that special case for the first comparison, but that creates extra (needless) code. However, by using these values, the loop code doesn't need to worry about the edge case of the first comparison.

Another alternative is to set both initial values to the first value of the input array (never a problem - see below) and iterate from the 2nd element onward, since this is the only correct state of min/max after one iteration. You could iterate from the 1st element too - it would make no difference, other than doing one extra (needless) iteration over the first element.

The only sane way of dealing with inout of size zero is simple: throw an IllegalArgumentException, because min/max is undefined in this case.

CSS-Only Scrollable Table with fixed headers

This answer will be used as a placeholder for the not fully supported position: sticky and will be updated over time. It is currently advised to not use the native implementation of this in a production environment.

See this for the current support: https://caniuse.com/#feat=css-sticky


Use of position: sticky

An alternative answer would be using position: sticky. As described by W3C:

A stickily positioned box is positioned similarly to a relatively positioned box, but the offset is computed with reference to the nearest ancestor with a scrolling box, or the viewport if no ancestor has a scrolling box.

This described exactly the behavior of a relative static header. It would be easy to assign this to the <thead> or the first <tr> HTML-tag, as this should be supported according to W3C. However, both Chrome, IE and Edge have problems assigning a sticky position property to these tags. There also seems to be no priority in solving this at the moment.

What does seem to work for a table element is assigning the sticky property to a table-cell. In this case the <th> cells.

Because a table is not a block-element that respects the static size you assign to it, it is best to use a wrapper element to define the scroll-overflow.

The code

_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
  height: 150px;_x000D_
  overflow: auto_x000D_
}_x000D_
_x000D_
table th {_x000D_
  position: -webkit-sticky;_x000D_
  position: sticky;_x000D_
  top: 0;_x000D_
}_x000D_
_x000D_
_x000D_
/* == Just general styling, not relevant :) == */_x000D_
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
th {_x000D_
  background-color: #1976D2;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
th,_x000D_
td {_x000D_
  padding: 1em .5em;_x000D_
}_x000D_
_x000D_
table tr {_x000D_
  color: #212121;_x000D_
}_x000D_
_x000D_
table tr:nth-child(odd) {_x000D_
  background-color: #BBDEFB;_x000D_
}
_x000D_
<div>_x000D_
  <table border="0">_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>head1</th>_x000D_
        <th>head2</th>_x000D_
        <th>head3</th>_x000D_
        <th>head4</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tr>_x000D_
      <td>row 1, cell 1</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In this example I use a simple <div> wrapper to define the scroll-overflow done with a static height of 150px. This can of course be any size. Now that the scrolling box has been defined, the sticky <th> elements will corespondent "to the nearest ancestor with a scrolling box", which is the div-wrapper.


Use of a position: sticky polyfill

Non-supported devices can make use of a polyfill, which implements the behavior through code. An example is stickybits, which resembles the same behavior as the browser's implemented position: sticky.

Example with polyfill: http://jsfiddle.net/7UZA4/6957/

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

"R cannot be resolved to a variable"?

I had the same error. Error was that, I had placed a file in res/raw folder with invalid filename. As soon as I corrected the file name to a valid one, error was resolved!

Allowed characters for naming a file:-

1. a-z
2. . _
3. 0-9
4. no capital letters

Capital letters were the issue in my case!

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

If you need a body in your response, you can call

return StatusCode(StatusCodes.Status500InternalServerError, responseObject);

This will return a 500 with the response object...

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

Here's how I resolved it:

  1. Deleted the bin folder in the project directory.
  2. Click on Build Solution. In VS2017(Run as Admin) > Build > Build Solution.

Difference between char* and const char*?

The first you can actually change if you want to, the second you can't. Read up about const correctness (there's some nice guides about the difference). There is also char const * name where you can't repoint it.

How do I fix this "TypeError: 'str' object is not callable" error?

You are trying to use the string as a function:

"Your new price is: $"(float(price) * 0.1)

Because there is nothing between the string literal and the (..) parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument:

>>> "Hello World!"(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

Seems you forgot to concatenate (and call str()):

easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))

The next line needs fixing as well:

easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))

Alternatively, use string formatting with str.format():

easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.1))
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.2))

where {:02.2f} will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.

How to pass a URI to an intent?

The Uri.parse(extras.getString("imageUri")) was causing an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.putExtra(java.lang.String, android.os.Parcelable)' on a null object reference 

So I changed to the following:

intent.putExtra("imageUri", imageUri)

and

Uri uri = (Uri) getIntent().get("imageUri");

This solved the problem.

How to export non-exportable private key from store

Unfortunately, the tool mentioned above is blocked by several antivirus vendors. If this is the case for you then take a look at the following.

Open the non-exportable cert in the cert store and locate the Thumbprint value.

Next, open regedit to the path below and locate the registry key matching the thumbprint value.

An export of the registry key will contain the complete certificate including the private key. Once exported, copy the export to the other server and import it into the registry.

The cert will appear in the certificate manager with the private key included.

Machine Store: HKLM\SOFTWARE\Microsoft\SystemCertificates\MY\Certificates User Store: HKCU\SOFTWARE\Microsoft\SystemCertificates\MY\Certificates

In a pinch, you could save the export as a backup of the certificate.

How to get records randomly from the oracle database?

SELECT *
FROM   (
    SELECT *
    FROM   table
    ORDER BY DBMS_RANDOM.RANDOM)
WHERE  rownum < 21;

How to make Sonar ignore some classes for codeCoverage metric?

I am able to achieve the necessary code coverage exclusions by updating jacoco-maven-plugin configuration in pom.xml

<plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.6</version>
                <executions>
                    <execution>
                        <id>pre-test</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <propertyName>jacocoArgLine</propertyName>
                            <destFile>${project.test.result.directory}/jacoco/jacoco.exec</destFile>
                        </configuration>
                    </execution>
                    <execution>
                        <id>post-test</id>
                        <phase>test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <dataFile>${project.test.result.directory}/jacoco/jacoco.exec</dataFile>
                            <outputDirectory>${project.test.result.directory}/jacoco</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <excludes>
                        <exclude>**/GlobalExceptionHandler*.*</exclude>
                        <exclude>**/ErrorResponse*.*</exclude>
                    </excludes>
                </configuration>
            </plugin>

this configuration excludes the GlobalExceptionHandler.java and ErrorResponse.java in the jacoco coverage.

And the following two lines does the same for sonar coverage .

    <sonar.exclusions> **/*GlobalExceptionHandler*.*, **/*ErrorResponse*.</sonar.exclusions>
        <sonar.coverage.exclusions> **/*GlobalExceptionHandler*.*, **/*ErrorResponse*.* </sonar.coverage.exclusions>

Create a string with n characters

int c = 10; String spaces = String.format("%" +c+ "c", ' '); this will solve your problem.

Changing the child element's CSS when the parent is hovered

.parent:hover > .child {
    /*do anything with this child*/
}

C++ calling base class constructors

Why the base class' default constructor is called? Turns out it's not always be the case. Any constructor of the base class (with different signatures) can be invoked from the derived class' constructor. In your case, the default constructor is called because it has no parameters so it's default.

When a derived class is created, the order the constructors are called is always Base -> Derived in the hierarchy. If we have:

class A {..}
class B : A {...}
class C : B {...}
C c;

When c is create, the constructor for A is invoked first, and then the constructor for B, and then the constructor for C.

To guarantee that order, when a derived class' constructor is called, it always invokes the base class' constructor before the derived class' constructor can do anything else. For that reason, the programmer can manually invoke a base class' constructor in the only initialisation list of the derived class' constructor, with corresponding parameters. For instance, in the following code, Derived's default constructor will invoke Base's constructor Base::Base(int i) instead of the default constructor.

Derived() : Base(5)
{      
}

If there's no such constructor invoked in the initialisation list of the derived class' constructor, then the program assumes a base class' constructor with no parameters. That's the reason why a constructor with no parameters (i.e. the default constructor) is invoked.

How to rename files and folder in Amazon S3?

I've just got this working. You can use the AWS SDK for PHP like this:

use Aws\S3\S3Client;

$sourceBucket = '*** Your Source Bucket Name ***';
$sourceKeyname = '*** Your Source Object Key ***';
$targetBucket = '*** Your Target Bucket Name ***';
$targetKeyname = '*** Your Target Key Name ***';        

// Instantiate the client.
$s3 = S3Client::factory();

// Copy an object.
$s3->copyObject(array(
    'Bucket'     => $targetBucket,
    'Key'        => $targetKeyname,
    'CopySource' => "{$sourceBucket}/{$sourceKeyname}",
));

http://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjectUsingPHP.html

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

next - it's like return, but for blocks! (So you can use this in any proc/lambda too.)

That means you can also say next n to "return" n from the block. For instance:

puts [1, 2, 3].map do |e|
  next 42 if e == 2
  e
end.inject(&:+)

This will yield 46.

Note that return always returns from the closest def, and never a block; if there's no surrounding def, returning is an error.

Using return from within a block intentionally can be confusing. For instance:

def my_fun
  [1, 2, 3].map do |e|
    return "Hello." if e == 2
    e
  end
end

my_fun will result in "Hello.", not [1, "Hello.", 2], because the return keyword pertains to the outer def, not the inner block.

Parsing json and searching through it

ObjectPath is a library that provides ability to query JSON and nested structures of dicts and lists. For example, you can search for all attributes called "foo" regardless how deep they are by using $..foo.

While the documentation focuses on the command line interface, you can perform the queries programmatically by using the package's Python internals. The example below assumes you've already loaded the data into Python data structures (dicts & lists). If you're starting with a JSON file or string you just need to use load or loads from the json module first.

import objectpath

data = [
    {'foo': 1, 'bar': 'a'},
    {'foo': 2, 'bar': 'b'},
    {'NoFooHere': 2, 'bar': 'c'},
    {'foo': 3, 'bar': 'd'},
]

tree_obj = objectpath.Tree(data)

tuple(tree_obj.execute('$..foo'))
# returns: (1, 2, 3)

Notice that it just skipped elements that lacked a "foo" attribute, such as the third item in the list. You can also do much more complex queries, which makes ObjectPath handy for deeply nested structures (e.g. finding where x has y that has z: $.x.y.z). I refer you to the documentation and tutorial for more information.

Get local IP address

Using these:

using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Linq;

You can use a series of LINQ methods to grab the most preferred IP address.

public static bool IsIPv4(IPAddress ipa) => ipa.AddressFamily == AddressFamily.InterNetwork;

public static IPAddress GetMainIPv4() => NetworkInterface.GetAllNetworkInterfaces()
.Select((ni)=>ni.GetIPProperties())
.Where((ip)=> ip.GatewayAddresses.Where((ga) => IsIPv4(ga.Address)).Count() > 0)
.FirstOrDefault()?.UnicastAddresses?
.Where((ua) => IsIPv4(ua.Address))?.FirstOrDefault()?.Address;

This simply finds the first Network Interface that has an IPv4 Default Gateway, and gets the first IPv4 address on that interface. Networking stacks are designed to have only one Default Gateway, and therefore the one with a Default Gateway, is the best one.

WARNING: If you have an abnormal setup where the main adapter has more than one IPv4 Address, this will grab only the first one. (The solution to grabbing the best one in that scenario involves grabbing the Gateway IP, and checking to see which Unicast IP is in the same subnet as the Gateway IP Address, which would kill our ability to create a pretty LINQ method based solution, as well as being a LOT more code)

How do I get the Session Object in Spring?

I try with next code and work excellent

    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;

    /**
     * Created by jaime on 14/01/15.
     */

    @Controller
    public class obteinUserSession {
        @RequestMapping(value = "/loginds", method = RequestMethod.GET)
        public String UserSession(ModelMap modelMap) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String name = auth.getName();
            modelMap.addAttribute("username", name);
            return "hellos " + name;
        }

Using Ansible set_fact to create a dictionary from register results

I think I got there in the end.

The task is like this:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
  with_items: "{{ people.results }}"

It loops through each of the dicts (item) in the people.results array, each time creating a new dict like {Bob: "male"}, and combine()s that new dict in the genders array, which ends up like:

{
    "Bob": "male",
    "Thelma": "female"
}

It assumes the keys (the name in this case) will be unique.


I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
  with_items: "{{ people.results }}"

This keeps combining the existing list with a list containing a single dict. We end up with a genders array like this:

[
    {'name': 'Bob', 'gender': 'male'},
    {'name': 'Thelma', 'gender': 'female'}
]

HTML: how to make 2 tables with different CSS

In your html

<table class="table1">
<tr>
<td>
...
</table>

<table class="table2">

<tr>
<td>
...
</table>

In your css:

table.table1 {...}
table.table1 tr {...}
table.table1 td {...}

table.table2 {...}
table.table2 tr {...}
table.table2 td {...}

SQL RANK() versus ROW_NUMBER()

You will only see the difference if you have ties within a partition for a particular ordering value.

RANK and DENSE_RANK are deterministic in this case, all rows with the same value for both the ordering and partitioning columns will end up with an equal result, whereas ROW_NUMBER will arbitrarily (non deterministically) assign an incrementing result to the tied rows.

Example: (All rows have the same StyleID so are in the same partition and within that partition the first 3 rows are tied when ordered by ID)

WITH T(StyleID, ID)
     AS (SELECT 1,1 UNION ALL
         SELECT 1,1 UNION ALL
         SELECT 1,1 UNION ALL
         SELECT 1,2)
SELECT *,
       RANK() OVER(PARTITION BY StyleID ORDER BY ID)       AS 'RANK',
       ROW_NUMBER() OVER(PARTITION BY StyleID ORDER BY ID) AS 'ROW_NUMBER',
       DENSE_RANK() OVER(PARTITION BY StyleID ORDER BY ID) AS 'DENSE_RANK'
FROM   T  

Returns

StyleID     ID       RANK      ROW_NUMBER      DENSE_RANK
----------- -------- --------- --------------- ----------
1           1        1         1               1
1           1        1         2               1
1           1        1         3               1
1           2        4         4               2

You can see that for the three identical rows the ROW_NUMBER increments, the RANK value remains the same then it leaps to 4. DENSE_RANK also assigns the same rank to all three rows but then the next distinct value is assigned a value of 2.

VBA using ubound on a multidimensional array

In addition to the already excellent answers, also consider this function to retrieve both the number of dimensions and their bounds, which is similar to John's answer, but works and looks a little differently:

Function sizeOfArray(arr As Variant) As String
    Dim str As String
    Dim numDim As Integer

    numDim = NumberOfArrayDimensions(arr)
    str = "Array"

    For i = 1 To numDim
        str = str & "(" & LBound(arr, i) & " To " & UBound(arr, i)
        If Not i = numDim Then
            str = str & ", "
        Else
            str = str & ")"
        End If
    Next i

    sizeOfArray = str
End Function


Private Function NumberOfArrayDimensions(arr As Variant) As Integer
' By Chip Pearson
' http://www.cpearson.com/excel/vbaarrays.htm
Dim Ndx As Integer
Dim Res As Integer
On Error Resume Next
' Loop, increasing the dimension index Ndx, until an error occurs.
' An error will occur when Ndx exceeds the number of dimension
' in the array. Return Ndx - 1.
    Do
        Ndx = Ndx + 1
        Res = UBound(arr, Ndx)
    Loop Until Err.Number <> 0
NumberOfArrayDimensions = Ndx - 1
End Function

Example usage:

Sub arrSizeTester()
    Dim arr(1 To 2, 3 To 22, 2 To 9, 12 To 18) As Variant
    Debug.Print sizeOfArray(arr())
End Sub

And its output:

Array(1 To 2, 3 To 22, 2 To 9, 12 To 18)

do { ... } while (0) — what is it good for?

It helps to group multiple statements into a single one so that a function-like macro can actually be used as a function. Suppose you have:

#define FOO(n)   foo(n);bar(n)

and you do:

void foobar(int n) {
  if (n)
     FOO(n);
}

then this expands to:

void foobar(int n) {
  if (n)
     foo(n);bar(n);
}

Notice that the second call bar(n) is not part of the if statement anymore.

Wrap both into do { } while(0), and you can also use the macro in an if statement.

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

Possible to iterate backwards through a foreach?

This works pretty well

List<string> list = new List<string>();

list.Add("Hello");
list.Add("Who");
list.Add("Are");
list.Add("You");

foreach (String s in list)
{
    Console.WriteLine(list[list.Count - list.IndexOf(s) - 1]);
}

How to merge two arrays in JavaScript and de-duplicate items

_x000D_
_x000D_
/**_x000D_
 * De-duplicate an array keeping only unique values._x000D_
 * Use hash table (js object) to filter-out duplicates._x000D_
 * The order of array elements is maintained._x000D_
 * This algorithm is particularly efficient for large arrays (linear time)._x000D_
 */_x000D_
function arrayUniqueFast(arr) {_x000D_
 var seen = {};_x000D_
 var result = [];_x000D_
 var i, len = arr.length;_x000D_
 for (i = 0; i < len; i++) {_x000D_
  var item = arr[i];_x000D_
  // hash table lookup_x000D_
  if (!seen[item]) {_x000D_
   result.push(item);_x000D_
   seen[item] = true;_x000D_
  }_x000D_
 }_x000D_
 return result;_x000D_
}_x000D_
_x000D_
///// test_x000D_
var array1 = ["Vijendra", "Singh"];_x000D_
var array2 = ["Singh", "Shakya"];_x000D_
_x000D_
var result = arrayUniqueFast(array1.concat(array2));_x000D_
document.write('<br>result: ' + result);
_x000D_
_x000D_
_x000D_

For other methods to dedup an array, please see my benchmarks at: https://jsperf.com/de-duplicate-an-array-keeping-only-unique-values

sqldeveloper error message: Network adapter could not establish the connection error

I have had the same problem. I am using windows 7 and this should also work for windows 8. The services responsible for the TNS listener and database were stopped when I looked in the Task Manager.

1: Hit Ctrl-Alt-Del and select "Start Task Manager".

From there go to the "Services" tab.

There are 5 services that need to be running for the database to be accessed correctly.

In the list below "databasename" is the database name you assigned during creation without the quotes.

I am also using database 11g, if you are using another type those fields would be different below. the * after home is the home install, if you have more than 1 database there would be home1, and home2

These are the 5 services

  1. OracleVssWriter"databasename"
  2. OracleService"databasename"
  3. OracleOraDb11g_home*TNSListener
  4. OracleOraDb11g_home*ClrAgent
  5. OracleDBConsole"databasename"

If any of these services are stopped right click on them and start them. After they have all started go back into SQL developer and re-try the connection and it should work.

How to find a text inside SQL Server procedures / triggers?

This one i tried in SQL2008, which can search from all the db at one go.

Create table #temp1 
(ServerName varchar(64), dbname varchar(64)
,spName varchar(128),ObjectType varchar(32), SearchString varchar(64))

Declare @dbid smallint, @dbname varchar(64), @longstr varchar(5000)
Declare @searhString VARCHAR(250)

set  @searhString='firstweek'

declare db_cursor cursor for 
select dbid, [name] 
from master..sysdatabases
where [name] not in ('master', 'model', 'msdb', 'tempdb', 'northwind', 'pubs')



open db_cursor
fetch next from db_cursor into @dbid, @dbname

while (@@fetch_status = 0)
begin
    PRINT 'DB='+@dbname
    set @longstr = 'Use ' + @dbname + char(13) +        
        'insert into #temp1 ' + char(13) +  
        'SELECT @@ServerName,  ''' + @dbname + ''', Name 
        , case  when [Type]= ''P'' Then ''Procedure''
                when[Type]= ''V'' Then ''View''
                when [Type]=  ''TF'' Then ''Table-Valued Function'' 
                when [Type]=  ''FN'' Then ''Function'' 
                when [Type]=  ''TR'' Then ''Trigger'' 
                else [Type]/*''Others''*/
                end 
        , '''+ @searhString +''' FROM  [SYS].[SYSCOMMEnTS]
        JOIN  [SYS].objects ON ID = object_id
        WHERE TEXT LIKE ''%' + @searhString + '%'''

 exec (@longstr)
 fetch next from db_cursor into @dbid, @dbname
end

close db_cursor
deallocate db_cursor
select * from #temp1
Drop table #temp1

Multiple models in a view

  1. Create one new class in your model and properties of LoginViewModel and RegisterViewModel:

    public class UserDefinedModel() 
    {
        property a1 as LoginViewModel 
        property a2 as RegisterViewModel 
    }
    
  2. Then use UserDefinedModel in your view.

Postgres DB Size Command

Start pgAdmin, connect to the server, click on the database name, and select the statistics tab. You will see the size of the database at the bottom of the list.

Then if you click on another database, it stays on the statistics tab so you can easily see many database sizes without much effort. If you open the table list, it shows all tables and their sizes.

Git commit in terminal opens VIM, but can't get back to terminal

You need to return to normal mode and save the commit message with either

<Esc>:wq

or

<Esc>:x

or

<Esc>ZZ

The Esc key returns you from insert mode to normal mode. The :wq, :x or ZZ sequence writes the changes and exits the editor.

Evaluate list.contains string in JSTL

there is no built-in feature to check that - what you would do is write your own tld function which takes a list and an item, and calls the list's contains() method. e.g.

//in your own WEB-INF/custom-functions.tld file add this
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
        PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
        "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib
        xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
        version="2.0"
        >
    <tlib-version>1.0</tlib-version>
    <function>
        <name>contains</name>
        <function-class>com.Yourclass</function-class>
        <function-signature>boolean contains(java.util.List,java.lang.Object)
        </function-signature>
    </function>
</taglib>

Then create a class called Yourclass, and add a static method called contains with the above signature. I m sure the implementation of that method is pretty self explanatory:

package com; // just to illustrate how to represent the package in the tld
public class Yourclass {
   public static boolean contains(List list, Object o) {
      return list.contains(o);
   }
}

Then you can use it in your jsp:

<%@ taglib uri="/WEB-INF/custom-functions.tld" prefix="fn" %>
<c:if test="${  fn:contains( mylist, myValue ) }">style='display:none;'</c:if>

The tag can be used from any JSP in the site.

edit: more info regarding the tld file - more info here

Add/delete row from a table

I suggest using jQuery. What you are doing right now is easy to achieve without jQuery, but as you will want new features and more functionality, jQuery will save you a lot of time. I would also like to mention that you shouldn't have multiple DOM elements with the same ID in one document. In such case use class attribute.

html:

<table id="dsTable">
  <tr>
     <td> Relationship Type </td>
     <td> Date of Birth </td>
     <td> Gender </td>
  </tr>
  <tr>
     <td> Spouse </td>
     <td> 1980-22-03 </td>
     <td> female </td>
     <td> <input type="button" class="addDep" value="Add"/></td>
     <td> <input type="button" class="deleteDep" value="Delete"/></td>
  </tr>
   <tr>
     <td> Child </td>
     <td> 2008-23-06 </td>
     <td> female </td>
     <td> <input type="button" class="addDep" value="Add"/></td>
     <td> <input type="button" class="deleteDep" value="Delete"/></td>
  </tr>
</table>

javascript:

$('body').on('click', 'input.deleteDep', function() {
   $(this).parents('tr').remove();  
});

Remember that you need to reference jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>

Here a working jsfiddle example: http://jsfiddle.net/p9dey/1/

Send inline image in email

The other solution is attaching the image as attachment and then referencing it html code using cid. HTML Code:

<html>
<head>
</head>
<body>
    <img width=100 height=100 id=""1"" src=""cid:Logo.jpg"">
</body>
</html>

C# Code:

EmailMessage email = new EmailMessage(service);
email.Subject = "Email with Image";
email.Body = new MessageBody(BodyType.HTML, html);
email.ToRecipients.Add("[email protected]");
string file = @"C:\Users\acv\Pictures\Logo.jpg";
email.Attachments.AddFileAttachment("Logo.jpg", file);
email.Attachments[0].IsInline = true;
email.Attachments[0].ContentId = "Logo.jpg";
email.SendAndSaveCopy();

Embed Youtube video inside an Android app

How it looks:

enter image description here

Best solution to my case. I need video fit web view size. Use embed youtube link with your video id. Example:

WebView youtubeWebView; //todo find or bind web view
String myVideoYoutubeId = "-bvXmLR3Ozc";

outubeWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });

WebSettings webSettings = youtubeWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);

youtubeWebView.loadUrl("https://www.youtube.com/embed/" + myVideoYoutubeId);

Web view xml code

<WebView
        android:id="@+id/youtube_web_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"/>

Razor View throwing "The name 'model' does not exist in the current context"

Here is what I did:

  1. Close Visual Studio
  2. Delete the SUO file
  3. Restart Visual Studio

The .suo file is a hidden file in the same folder as the .svn solution file and contains the Visual Studio User Options.

Changing default startup directory for command prompt in Windows 7

hi if you want cmd to automatically open when the machine starts up you can place the cmd.exe executable in the startup folder(just search for startup and place a shortcut of cmd.exe there)

VMware Workstation and Device/Credential Guard are not compatible

install the latest vmware workstation > 15.5.5 version

which has support of Hyper-V Host

With the release of VMware Workstation/Player 15.5. 5 or >, we are very excited and proud to announce support for Windows hosts with Hyper-V mode enabled! As you may know, this is a joint project from both Microsoft and VMware

https://blogs.vmware.com/workstation/2020/05/vmware-workstation-now-supports-hyper-v-mode.html

i installed the VMware.Workstation.Pro.16.1.0

and now it fixed my issue now i am using docker & vmware same time even my window Hyper-V mode is enabled

echo key and value of an array without and with loop

If you must not use a loop (why?), you could use array_walk,

function printer($v, $k) {
   echo "$k is at $v\n";
}

array_walk($page, "printer");

See http://www.ideone.com/aV5X6.

How do I include the string header?

You want to include <string> and use std::string:

#include <string>
#include <iostream>

int main()
{
    std::string s = "a string";
    std::cout << s << std::endl;
}

But what you really need to do is get an introductory level book. You aren't going to learn properly any other way, certainly not scrapping for information online.

How do I make a burn down chart in Excel?

No macros required. Data as below, two columns, dates don't need to be in order. Select range, convert to a Table (Ctrl+T). When data is added to the table, a chart based on the table will automatically include the added data.

Select table, insert a line chart. Right click chart, choose Select Data, click on Blank and Hidden Cells button, choose Interpolate option.

Burndown Chart of Pages Read

Why does "return list.sort()" return None, not the list?

To understand why it does not return the list:

sort() doesn't return any value while the sort() method just sorts the elements of a given list in a specific order - ascending or descending without returning any value.

So problem is with answer = newList.sort() where answer is none.

Instead you can just do return newList.sort().

The syntax of the sort() method is:

list.sort(key=..., reverse=...)

Alternatively, you can also use Python's in-built function sorted() for the same purpose.

sorted(list, key=..., reverse=...)

Note: The simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.

So in your case answer = sorted(newList).

Internet Access in Ubuntu on VirtualBox

it could be a problem with your specific network adapter. I have a Dell 15R and there are no working drivers for ubuntu or ubuntu server; I even tried compiling wireless drivers myself, but to no avail.

However, in virtualbox, I was able to get wireless working by using the default configuration. It automatically bridged my internal wireless adapter and hence used my native OS's wireless connection for wireless.

If you are trying to get a separate wireless connection from within ubuntu in virtualbox, then it would take more configuring. If so, let me know, if not, I will not bother typing up instructions to something you are not looking to do, as it is quite complicated in some instances.

p.s. you should be using Windows 7 if you have any technical inclination. Do you live under a rock? No offense intended.

Reminder - \r\n or \n\r?

From Wikipedia (you can read which is correct for your OS at that article):

Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, '\r\n', 0x0D0A).

How to toggle boolean state of react component?

Set: const [state, setState] = useState(1);

Toggle: setState(state*-1);

Use: state > 0 ? 'on' : 'off';

cmd line rename file with date and time

problem in %time:~0,2% can't set to 24 hrs format, ended with space(1-9), instead of 0(1-9)

go around with:

set HR=%time:~0,2%

set HR=%Hr: =0% (replace space with 0 if any <has a space in between : =0>)

then replace %time:~0,2% with %HR%

good luck

How to override Bootstrap's Panel heading background color?

Just check the bootstrap. CSS and search for the class panel-heading and copy the default code.

Copy the default CSS to your personal CSS but vive it a diference classname like my-panel-header for example.

Edit the css Code from the new clones class created.

SQL Server: the maximum number of rows in table

Partition the table monthly.That is the best way to handle tables with large daily influx ,be it oracle or MSSQL.

Gradle Sync failed could not find constraint-layout:1.0.0-alpha2

Just to make sure that in studio version 2.3 you won't see a dropdown near constraint-layout in sdk tools, it will by default install the latest version

To get the desired version check the box saying show package details and boom you can now choose the desired version you want to install

Select single item from a list

List<string> items = new List<string>();

items.Find(p => p == "blah");

or

items.Find(p => p.Contains("b"));

but this allows you to define what you are looking for via a match predicate...

I guess if you are talking linqToSql then:

example looking for Account...

DataContext dc = new DataContext();

Account item = dc.Accounts.FirstOrDefault(p => p.id == 5);

If you need to make sure that there is only 1 item (throws exception when more than 1)

DataContext dc = new DataContext();

Account item = dc.Accounts.SingleOrDefault(p => p.id == 5);

compareTo with primitives -> Integer / int

For performance, it usually best to make the code as simple and clear as possible and this will often perform well (as the JIT will optimise this code best). In your case, the simplest examples are also likely to be the fastest.


I would do either

int cmp = a > b ? +1 : a < b ? -1 : 0;

or a longer version

int cmp;
if (a > b)
   cmp = +1;
else if (a < b)
   cmp = -1;
else
   cmp = 0;

or

int cmp = Integer.compare(a, b); // in Java 7
int cmp = Double.compare(a, b); // before Java 7

It's best not to create an object if you don't need to.

Performance wise, the first is best.

If you know for sure that you won't get an overflow you can use

int cmp = a - b; // if you know there wont be an overflow.

you won't get faster than this.

How can I show figures separately in matplotlib?

As @arpanmangal, the solutions above do not work for me (matplotlib 3.0.3, python 3.5.2).

It seems that using .show() in a figure, e.g., figure.show(), is not recommended, because this method does not manage a GUI event loop and therefore the figure is just shown briefly. (See figure.show() documentation). However, I do not find any another way to show only a figure.

In my solution I get to prevent the figure for instantly closing by using click events. We do not have to close the figure — closing the figure deletes it.

I present two options: - waitforbuttonpress(timeout=-1) will close the figure window when clicking on the figure, so we cannot use some window functions like zooming. - ginput(n=-1,show_clicks=False) will wait until we close the window, but it releases an error :-.

Example:

import matplotlib.pyplot as plt

fig1, ax1 = plt.subplots(1) # Creates figure fig1 and add an axes, ax1
fig2, ax2 = plt.subplots(1) # Another figure fig2 and add an axes, ax2

ax1.plot(range(20),c='red') #Add a red straight line to the axes of fig1.
ax2.plot(range(100),c='blue') #Add a blue straight line to the axes of fig2.

#Option1: This command will hold the window of fig2 open until you click on the figure
fig2.waitforbuttonpress(timeout=-1) #Alternatively, use fig1

#Option2: This command will hold the window open until you close the window, but
#it releases an error.
#fig2.ginput(n=-1,show_clicks=False) #Alternatively, use fig1

#We show only fig2
fig2.show() #Alternatively, use fig1

SQL Server 2008 Row Insert and Update timestamps

try

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    [CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [smalldatetime] NOT NULL

)

PS I think a smalldatetime is good enough. You may decide differently.

Can you not do this at the "moment of impact" ?

In Sql Server, this is common:

Update dbo.MyTable 
Set 

ColA = @SomeValue , 
UpdateDS = CURRENT_TIMESTAMP
Where...........

Sql Server has a "timestamp" datatype.

But it may not be what you think.

Here is a reference:

http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx

Here is a little RowVersion (synonym for timestamp) example:

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)


INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Maybe a complete working example:

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS

BEGIN

Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where 
triggerInsertedTable.Name = myAlias.Name

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Matching on the "Name" value is probably not wise.

Try this more mainstream example with a SurrogateKey

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    SurrogateKey int not null Primary Key Identity (1001,1),
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS

BEGIN

   UPDATE dbo.Names
    SET UpdateTS = CURRENT_TIMESTAMP
    From  dbo.Names myAlias
    WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Access event to call preventdefault from custom function originating from onclick attribute of tag

<script type="text/javascript">
$('a').click(function(){
   return false;
});
<script>

Generate Row Serial Numbers in SQL Query

Sometime we might don't want to apply ordering on our result set to add serial number. But if we are going to use ROW_NUMBER() then we have to have a ORDER BY clause. So, for that we can simply apply a tricks to avoid any ordering on the result set.

SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS ItemNo, ItemName FROM ItemMastetr

For that we don't need to apply order by on our result set. We'll just add ItemNo on our given result set.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

Just went to build.gradle and deleted the line:

implementation 'com.android.support:appcompat-v7:26.1.0'

After that, I re-synced the Gradle. Then, I pasted the line of code back, re-synced the Gradle again and it worked.

Note: While I was making this changes, I also updated all the SDK Tools that needed update.

How to stop event propagation with inline onclick attribute?

<div onclick="alert('you clicked the header')" class="header">
  <span onclick="alert('you clicked inside the header'); event.stopPropagation()">
    something inside the header
  </span>
</div>

Convert a python dict to a string and back

If in Chinses

import codecs
fout = codecs.open("xxx.json", "w", "utf-8")
dict_to_json = json.dumps({'text':"??"},ensure_ascii=False,indent=2)
fout.write(dict_to_json + '\n')

How to get the current branch name in Git?

You have also git symbolic-ref HEAD which displays the full refspec.

To show only the branch name in Git v1.8 and later (thank's to Greg for pointing that out):

git symbolic-ref --short HEAD

On Git v1.7+ you can also do:

git rev-parse --abbrev-ref HEAD

Both should give the same branch name if you're on a branch. If you're on a detached head answers differ.

Note:

On an earlier client, this seems to work:

git symbolic-ref HEAD | sed -e "s/^refs\/heads\///"

Darien 26. Mar 2014

Is it possible to run an .exe or .bat file on 'onclick' in HTML

Here's what I did. I wanted a HTML page setup on our network so I wouldn't have to navigate to various folders to install or upgrade our apps. So what I did was setup a .bat file on our "shared" drive that everyone has access to, in that .bat file I had this code:

start /d "\\server\Software\" setup.exe

The HTML code was:

<input type="button" value="Launch Installer" onclick="window.open('file:///S:Test/Test.bat')" />

(make sure your slashes are correct, I had them the other way and it didn't work)

I preferred to launch the EXE directly but that wasn't possible, but the .bat file allowed me around that. Wish it worked in FF or Chrome, but only IE.

Better way to find last used row

How is this?

dim rownum as integer
dim colnum as integer
dim lstrow as integer
dim lstcol as integer
dim r as range

'finds the last row

lastrow = ActiveSheet.UsedRange.Rows.Count

'finds the last column

lastcol = ActiveSheet.UsedRange.Columns.Count

'sets the range

set r = range(cells(rownum,colnum), cells(lstrow,lstcol))

How to make a programme continue to run after log out from ssh?

Start in the background:

./long_running_process options &

And disown the job before you log out:

disown

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

Copy the diff file to the root of your repository, and then do:

git apply yourcoworkers.diff

More information about the apply command is available on its man page.

By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch on the sender and then git am on the receiver, because it also transfers the authorship info and the commit message.

If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3 option of apply that tries to merge in the changes.

It also works with Unix pipe as follows:

git diff d892531 815a3b5 | git apply

To the power of in C?

There's no operator for such usage in C, but a family of functions:

double pow (double base , double exponent);
float powf (float base  , float exponent);
long double powl (long double base, long double exponent);

Note that the later two are only part of standard C since C99.

If you get a warning like:

"incompatible implicit declaration of built in function 'pow' "

That's because you forgot #include <math.h>.

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

This implementation wrap entity exception to exception with detail text. It handles DbEntityValidationException, DbUpdateException, datetime2 range errors (MS SQL), and include key of invalid entity in message (useful when savind many entities at one SaveChanges call).

First, override SaveChanges in DbContext class:

public class AppDbContext : DbContext
{
    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException dbEntityValidationException)
        {
            throw ExceptionHelper.CreateFromEntityValidation(dbEntityValidationException);
        }
        catch (DbUpdateException dbUpdateException)
        {
            throw ExceptionHelper.CreateFromDbUpdateException(dbUpdateException);
        }
    }   

    public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken)
    {
        try
        {
            return await base.SaveChangesAsync(cancellationToken);
        }
        catch (DbEntityValidationException dbEntityValidationException)
        {
            throw ExceptionHelper.CreateFromEntityValidation(dbEntityValidationException);
        }
        catch (DbUpdateException dbUpdateException)
        {
            throw ExceptionHelper.CreateFromDbUpdateException(dbUpdateException);
        }
    }

ExceptionHelper class:

public class ExceptionHelper
{
    public static Exception CreateFromEntityValidation(DbEntityValidationException ex)
    {
        return new Exception(GetDbEntityValidationMessage(ex), ex);
    }

    public static string GetDbEntityValidationMessage(DbEntityValidationException ex)
    {
        // Retrieve the error messages as a list of strings.
        var errorMessages = ex.EntityValidationErrors
            .SelectMany(x => x.ValidationErrors)
            .Select(x => x.ErrorMessage);

        // Join the list to a single string.
        var fullErrorMessage = string.Join("; ", errorMessages);

        // Combine the original exception message with the new one.
        var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
        return exceptionMessage;
    }

    public static IEnumerable<Exception> GetInners(Exception ex)
    {
        for (Exception e = ex; e != null; e = e.InnerException)
            yield return e;
    }

    public static Exception CreateFromDbUpdateException(DbUpdateException dbUpdateException)
    {
        var inner = GetInners(dbUpdateException).Last();
        string message = "";
        int i = 1;
        foreach (var entry in dbUpdateException.Entries)
        {
            var entry1 = entry;
            var obj = entry1.CurrentValues.ToObject();
            var type = obj.GetType();
            var propertyNames = entry1.CurrentValues.PropertyNames.Where(x => inner.Message.Contains(x)).ToList();
            // check MS SQL datetime2 error
            if (inner.Message.Contains("datetime2"))
            {
                var propertyNames2 = from x in type.GetProperties()
                                        where x.PropertyType == typeof(DateTime) ||
                                            x.PropertyType == typeof(DateTime?)
                                        select x.Name;
                propertyNames.AddRange(propertyNames2);
            }

            message += "Entry " + i++ + " " + type.Name + ": " + string.Join("; ", propertyNames.Select(x =>
                string.Format("'{0}' = '{1}'", x, entry1.CurrentValues[x])));
        }
        return new Exception(message, dbUpdateException);
    }
}

Inserting string at position x of another string

Quick fix! If you don't want to manually add a space, you can do this:

_x000D_
_x000D_
var a = "I want apple";_x000D_
var b = "an";_x000D_
var position = 6;_x000D_
var output = [a.slice(0, position + 1), b, a.slice(position)].join('');_x000D_
console.log(output);
_x000D_
_x000D_
_x000D_

(edit: i see that this is actually answered above, sorry!)

Add space between cells (td) using css

cellspacing (distance between cells) parameter of the TABLE tag is precisely what you want. The disadvantage is it's one value, used both for x and y, you can't choose different spacing or padding vertically/horizontally. There is a CSS property too, but it's not widely supported.

Drop shadow for PNG image in CSS

Yes, it is possible using filter: dropShadow(x y blur? spread? color?), either in CSS or inline:

_x000D_
_x000D_
img {_x000D_
  width: 150px;_x000D_
  -webkit-filter: drop-shadow(5px 5px 5px #222);_x000D_
  filter: drop-shadow(5px 5px 5px #222);_x000D_
}
_x000D_
<img src="https://cdn.freebiesupply.com/logos/large/2x/stackoverflow-com-logo-png-transparent.png">_x000D_
_x000D_
<img src="https://cdn.freebiesupply.com/logos/large/2x/stackoverflow-com-logo-png-transparent.png" style="-webkit-filter: drop-shadow(5px 5px 5px #222); filter: drop-shadow(5px 5px 5px #222);">
_x000D_
_x000D_
_x000D_

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

What is a reasonable length limit on person "Name" fields?

The average first name is about 6 letters. That leaves 43 for a last name. :) Seems like you could probably shorten it if you like.

The main question is how many rows do you think you will have? I don't think varchar(50) is going to kill you until you get several million rows.

How to store an array into mysql?

Consider normalizing the table structure into a comments, and a separate votes table.

Table "comments":

id
comment
user
...

Table "votes":

user_id  
comment_id
vote (downvote/upvote)

this would allow an unlimited number of votes without having to deal with the limits of a database field.

Also, you may have future needs for operations like "show all votes a user has cast", removing specific votes or limiting the maximum number of votes per day. These operations are dead easy and fast to implement with a normalized structure, and horribly slow and complex in a serialized array.

Cannot delete or update a parent row: a foreign key constraint fails

Disable the foreign key check and make the changes then re-enable foreign key check.

SET FOREIGN_KEY_CHECKS=0; -- to disable them
DELETE FROM `jobs` WHERE `job_id` = 1 LIMIT 1 
SET FOREIGN_KEY_CHECKS=1; -- to re-enable them

How to remove Left property when position: absolute?

left: initial

This will also set left back to the browser default.

But important to know property: initial is not supported in IE.

PHP - Debugging Curl

If you just want a very quick way to debug the result:

$ch = curl_init();
curl_exec($ch);
$curl_error = curl_error($ch);
echo "<script>console.log($curl_error);</script>"

"Proxy server connection failed" in google chrome

I had the same problem with a freshly installed copy of Chrome. If nothing works, and your Use a proxy server your LAN setting is unchecked, check it and then uncheck it . Believe it or not it might work. I don't know if I should consider it a bug or not.

Kendo grid date column not formatting

I found this piece of information and got it to work correctly. The data given to me was in string format so I needed to parse the string using kendo.parseDate before formatting it with kendo.toString.

columns: [
    {
        field: "FirstName",
        title: "FIRST NAME"
    },
    {
        field: "LastName",
        title: "LAST NAME"
    },
    {
        field: "DateOfBirth",
        title: "DATE OF BIRTH",
        template: "#= kendo.toString(kendo.parseDate(DateOfBirth, 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
    },
...


References:

  1. format-date-in-grid
  2. jsfiddle
  3. kendo ui date formatting

How does MySQL process ORDER BY and LIMIT in a query?

It will order first, then get the first 20. A database will also process anything in the WHERE clause before ORDER BY.

warning: implicit declaration of function

The right way is to declare function prototype in header.

Example

main.h

#ifndef MAIN_H
#define MAIN_H

int some_main(const char *name);

#endif

main.c

#include "main.h"

int main()
{
    some_main("Hello, World\n");
}

int some_main(const char *name)
{
    printf("%s", name);
}

Alternative with one file (main.c)

static int some_main(const char *name);

int some_main(const char *name)
{
    // do something
}

Convert JSON string to array of JSON objects in Javascript

As Luca indicated, add extra [] to your string and use the code below:

var myObject = eval('(' + myJSONtext + ')');

to test it you can use the snippet below.

var s =" [{'id':1,'name':'Test1'},{'id':2,'name':'Test2'}]";
var myObject = eval('(' + s + ')');
for (i in myObject)
{
   alert(myObject[i]["name"]);
}

hope it helps..

How to query for today's date and 7 days before data?

Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):

select * from tab
where DateCol between adddate(now(),-7) and now() 

PHP: If internet explorer 6, 7, 8 , or 9

A version that will continue to work with both IE10 and IE11:

preg_match('/MSIE (.*?);/', $_SERVER['HTTP_USER_AGENT'], $matches);
if(count($matches)<2){
  preg_match('/Trident\/\d{1,2}.\d{1,2}; rv:([0-9]*)/', $_SERVER['HTTP_USER_AGENT'], $matches);
}

if (count($matches)>1){
  //Then we're using IE
  $version = $matches[1];

  switch(true){
    case ($version<=8):
      //IE 8 or under!
      break;

    case ($version==9 || $version==10):
      //IE9 & IE10!
      break;

    case ($version==11):
      //Version 11!
      break;

    default:
      //You get the idea
  }
}

How can I order a List<string>?

List<string> myCollection = new List<string>()
{
    "Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};

myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
    Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}

output: Abdi 3 Alex 2 Bob 4

Javascript Uncaught TypeError: Cannot read property '0' of undefined

The error is here:

hasLetter("a",words[]);

You are passing the first item of words, instead of the array.

Instead, pass the array to the function:

hasLetter("a",words);

Problem solved!


Here's a breakdown of what the problem was:

I'm guessing in your browser (chrome throws a different error), words[] == words[0], so when you call hasLetter("a",words[]);, you are actually calling hasLetter("a",words[0]);. So, in essence, you are passing the first item of words to your function, not the array as a whole.

Of course, because words is just an empty array, words[0] is undefined. Therefore, your function call is actually:

hasLetter("a", undefined);

which means that, when you try to access d[ascii], you are actually trying to access undefined[0], hence the error.

How to customise file type to syntax associations in Sublime Text?

I put my customized changes in the User package:

*nix: ~/.config/sublime-text-2/Packages/User/Scala.tmLanguage
*Windows: %APPDATA%\Sublime Text 2\Packages\User\Scala.tmLanguage

Which also means it's in JSON format:

{
  "extensions":
  [
    "sbt"
  ]
}

This is the same place the

View -> Syntax -> Open all with current extension as ...

menu item adds it (creating the file if it doesn't exist).

Reset all the items in a form

foreach (Control field in container.Controls)
            {
                if (field is TextBox)
                    ((TextBox)field).Clear();
                else if (field is ComboBox)
                    ((ComboBox)field).SelectedIndex=0;
                else
                    dgView.DataSource = null;
                    ClearAllText(field);
            }

How do I make the method return type generic?

You could implement it like this:

@SuppressWarnings("unchecked")
public <T extends Animal> T callFriend(String name) {
    return (T)friends.get(name);
}

(Yes, this is legal code; see Java Generics: Generic type defined as return type only.)

The return type will be inferred from the caller. However, note the @SuppressWarnings annotation: that tells you that this code isn't typesafe. You have to verify it yourself, or you could get ClassCastExceptions at runtime.

Unfortunately, the way you're using it (without assigning the return value to a temporary variable), the only way to make the compiler happy is to call it like this:

jerry.<Dog>callFriend("spike").bark();

While this may be a little nicer than casting, you are probably better off giving the Animal class an abstract talk() method, as David Schmitt said.

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

I had the same error today, with XCode 6.1

What I found was that, no matter what I tried, I couldn't get XCode to stop complaining about this Provisioning Profile with a GUID as its name.

The solution was to search for this GUID in the .pbxproj file, which lives within the XCode .xcodeproj folder.

Just find the line containing your GUID:

PROVISIONING_PROFILE = "A9234343-.....34"

and change it to:

PROVISIONING_PROFILE = ""

One other thing to check: Your XCode PROJECT settings contain your Provisioning Profile & Code Signing settings, but, there is a second set under your project's "TARGETS" tab.

So, if XCode is complaining about a Provisioning Profile which isn't the one quoted in your project settings, then go have have a look at the settings shown under "TARGETS" in your XCode project.

(I wish someone had given me this advice, 4 painful hours ago..)

How can I run a php without a web server?

You can use these kind of programs to emulate an apache web server and run PHP on your computer:

http://www.wampserver.com/en/

http://www.apachefriends.org/en/xampp.html

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

Here is what I did.

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

and restart the docker service

docker run -ti node:latest /bin/bash

run this command to verify

user@4d04d06d5022:/# ulimit -a

should see this in the result

open files (-n) 32000

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

Android - How to download a file from a webserver

Using Async task

call when you want to download file : new DownloadFileFromURL().execute(file_url);

public class MainActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;
    public static final int progress_bar_type = 0;

    // File url to download
    private static String file_url = "http://www.qwikisoft.com/demo/ashade/20001.kml";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        new DownloadFileFromURL().execute(file_url);

    }

    /**
     * Showing Dialog
     * */

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type: // we set this to 0
            pDialog = new ProgressDialog(this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
            return pDialog;
        default:
            return null;
        }
    }

    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection connection = url.openConnection();
                connection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                int lenghtOfFile = connection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);

                // Output stream
                OutputStream output = new FileOutputStream(Environment
                        .getExternalStorageDirectory().toString()
                        + "/2011.kml");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

        }

    }
}

if not working in 4.0 then add:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Another great option is the free V-Tools addin for Microsoft Access. Among other helpful tools it has a form to edit and save the Import/Export specifications.

enter image description here

enter image description here

Note: As of version 1.83, there is a bug in enumerating the code pages on Windows 10. (Apparently due to a missing/changed API function in Windows 10) The tools still works great, you just need to comment out a few lines of code or step past it in the debug window.

This has been a real life-saver for me in editing a complex import spec for our online orders.

How to create a DataFrame from a text file in Spark

A txt File with PIPE (|) delimited file can be read as :


df = spark.read.option("sep", "|").option("header", "true").csv("s3://bucket_name/folder_path/file_name.txt")

create array from mysql query php

while($row = mysql_fetch_assoc($result)) {
  echo $row['type'];
}

Round double value to 2 decimal places

I was going to go with Jason's answer but I noticed that in My version of Xcode (4.3.3) I couldn't do that. so after a bit of research I found they had recently changed the class methods and removed all the old ones. so here's how I had to do it:

NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];

[fmt setMaximumFractionDigits:2];
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.342]]);

Clear form fields with jQuery

This won't handle cases where form input fields have non empty default values.

Something like should work

$('yourdiv').find('form')[0].reset();

How do you right-justify text in an HTML textbox?

Did you try setting the style:

input {
    text-align:right;
}

Just tested, this works fine (in FF3 at least):

<html>
    <head>
        <title>Blah</title>
        <style type="text/css">
        input { text-align:right; }
        </style>
    </head>
    <body>
        <input type="text" value="2">
    </body>
</html>

You'll probably want to throw a class on these inputs, and use that class as the selector. I would shy away from "rightAligned" or something like that. In a class name, you want to describe what the element's function is, not how it should be rendered. "numeric" might be good, or perhaps the business function of the text boxes.

How can I obtain the element-wise logical NOT of a pandas Series?

@unutbu's answer is spot on, just wanted to add a warning that your mask needs to be dtype bool, not 'object'. Ie your mask can't have ever had any nan's. See here - even if your mask is nan-free now, it will remain 'object' type.

The inverse of an 'object' series won't throw an error, instead you'll get a garbage mask of ints that won't work as you expect.

In[1]: df = pd.DataFrame({'A':[True, False, np.nan], 'B':[True, False, True]})
In[2]: df.dropna(inplace=True)
In[3]: df['A']
Out[3]:
0    True
1   False
Name: A, dtype object
In[4]: ~df['A']
Out[4]:
0   -2
0   -1
Name: A, dtype object

After speaking with colleagues about this one I have an explanation: It looks like pandas is reverting to the bitwise operator:

In [1]: ~True
Out[1]: -2

As @geher says, you can convert it to bool with astype before you inverse with ~

~df['A'].astype(bool)
0    False
1     True
Name: A, dtype: bool
(~df['A']).astype(bool)
0    True
1    True
Name: A, dtype: bool

Can I set a breakpoint on 'memory access' in GDB?

I just tried the following:

 $ cat gdbtest.c
 int abc = 43;

 int main()
 {
   abc = 10;
 }
 $ gcc -g -o gdbtest gdbtest.c
 $ gdb gdbtest
 ...
 (gdb) watch abc
 Hardware watchpoint 1: abc
 (gdb) r
 Starting program: /home/mweerden/gdbtest 
 ...

 Old value = 43
 New value = 10
 main () at gdbtest.c:6
 6       }
 (gdb) quit

So it seems possible, but you do appear to need some hardware support.

How do I consume the JSON POST data in an Express application

For those getting an empty object in req.body

I had forgotten to set headers: {"Content-Type": "application/json"} in the request. Changing it solved the problem.

How do I simulate a hover with a touch in touch enabled browsers?

The mouse hover effect cannot be implemented in touch device . When I'm appeared with same situation in safari ios I used :active in css to make effect.

ie.

p:active {
  color:red;
}

In my case its working .May be this is also the case that can be used with out using javascript. Just give a try.

CSS body background image fixed to full screen even when zooming in/out

Add this in your css file:

.custom_class
 {
    background-image: url(../img/beach.jpg);
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
 }

and then, in your .html (or .php) file call this class like that:

<div class="custom_class">
   ...
</div>

Excel how to find values in 1 column exist in the range of values in another

This is what you need:

 =NOT(ISERROR(MATCH(<cell in col A>,<column B>, 0)))  ## pseudo code

For the first cell of A, this would be:

 =NOT(ISERROR(MATCH(A2,$B$2:$B$5, 0)))

Enter formula (and drag down) as follows:

enter image description here

You will get:

enter image description here

C# Numeric Only TextBox Control

I think it will help you

<script type="text/javascript">
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 32 && (charCode < 48 || charCode > 57) && (charCode != 45) && (charCode != 43) && (charCode != 40) && (charCode != 41))
        return false;

    return true;
}

force line break in html table cell

Try using

<table  border="1" cellspacing="0" cellpadding="0" class="template-table" 
style="table-layout: fixed; width: 100%"> 

as table style along with

<td style="word-break:break-word">long text</td>

for td it works for normal/real scenario text with words, not for random typed letters without gaps

Filtering Pandas DataFrames on dates

If you have already converted the string to a date format using pd.to_datetime you can just use:

df = df[(df['Date']> "2018-01-01") & (df['Date']< "2019-07-01")]

How to downgrade or install an older version of Cocoapods

If you need to install an older version (for example 0.25):

pod _0.25.0_ install

How to change default text color using custom theme?

You can't use @android:style/TextAppearance as the parent for the whole app's theme; that's why koopaking3's solution seems quite broken.

To change default text colour everywhere in your app using a custom theme, try something like this. Works at least on Android 4.0+ (API level 14+).

res/values/themes.xml:

<resources>    
    <style name="MyAppTheme" parent="android:Theme.Holo.Light">
        <!-- Change default text colour from dark grey to black -->
        <item name="android:textColor">@android:color/black</item>
    </style>
</resources>

Manifest:

<application
    ...
    android:theme="@style/MyAppTheme">

Update

A shortcoming with the above is that also disabled Action Bar overflow menu items use the default colour, instead of being greyed out. (Of course, if you don't use disabled menu items anywhere in your app, this may not matter.)

As I learned by asking this question, a better way is to define the colour using a drawable:

<item name="android:textColor">@drawable/default_text_color</item>

...with res/drawable/default_text_color.xml specifying separate state_enabled="false" colour:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="@android:color/darker_gray"/>
    <item android:color="@android:color/black"/>
</selector>

Taking pictures with camera on Android programmatically

Look at following demo code.

Here is your XML file for UI,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnCapture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Camera" />

</LinearLayout>

And here is your Java class file,

public class CameraDemoActivity extends Activity {
    int TAKE_PHOTO_CODE = 0;
    public static int count = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Here, we are making a folder named picFolder to store
        // pics taken by the camera using this application.
        final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
        File newdir = new File(dir);
        newdir.mkdirs();

        Button capture = (Button) findViewById(R.id.btnCapture);
        capture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                // Here, the counter will be incremented each time, and the
                // picture taken by camera will be stored as 1.jpg,2.jpg
                // and likewise.
                count++;
                String file = dir+count+".jpg";
                File newfile = new File(file);
                try {
                    newfile.createNewFile();
                }
                catch (IOException e)
                {
                }

                Uri outputFileUri = Uri.fromFile(newfile);

                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

                startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
            Log.d("CameraDemo", "Pic saved");
        }
    }
}

Note:

Specify the following permissions in your manifest file,

<uses-permission android:name="android.permission.CAMERA"/>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

For me it turned out that I had a @JsonManagedReferece in one entity without a @JsonBackReference in the other referenced entity. This caused the marshaller to throw an error.

Regex (grep) for multi-line search needed

Without the need to install the grep variant pcregrep, you can do multiline search with grep.

$ grep -Pzo "(?s)^(\s*)\N*main.*?{.*?^\1}" *.c

Explanation:

-P activate perl-regexp for grep (a powerful extension of regular expressions)

-z suppress newline at the end of line, substituting it for null character. That is, grep knows where end of line is, but sees the input as one big line.

-o print only matching. Because we're using -z, the whole file is like a single big line, so if there is a match, the entire file would be printed; this way it won't do that.

In regexp:

(?s) activate PCRE_DOTALL, which means that . finds any character or newline

\N find anything except newline, even with PCRE_DOTALL activated

.*? find . in non-greedy mode, that is, stops as soon as possible.

^ find start of line

\1 backreference to the first group (\s*). This is a try to find the same indentation of method.

As you can imagine, this search prints the main method in a C (*.c) source file.

Listen to changes within a DIV and act accordingly

There is an excellent jquery plugin, LiveQuery, that does just this.

Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.

For example you could use the following code to bind a click event to all A tags, even any A tags you might add via AJAX.

$('a').livequery('click', function(event) { 
    alert('clicked'); 
    return false; 
}); 

Once you add new A tags to your document, Live Query will bind the click event and there is nothing else that needs to be called or done.

Here is a working example of its magic...

enter image description here

Drop rows with all zeros in pandas data frame

Couple of solutions I found to be helpful while looking this up, especially for larger data sets:

df[(df.sum(axis=1) != 0)]       # 30% faster 
df[df.values.sum(axis=1) != 0]  # 3X faster 

Continuing with the example from @U2EF1:

In [88]: df = pd.DataFrame({'a':[0,0,1,1], 'b':[0,1,0,1]})

In [91]: %timeit df[(df.T != 0).any()]
1000 loops, best of 3: 686 µs per loop

In [92]: df[(df.sum(axis=1) != 0)]
Out[92]: 
   a  b
1  0  1
2  1  0
3  1  1

In [95]: %timeit df[(df.sum(axis=1) != 0)]
1000 loops, best of 3: 495 µs per loop

In [96]: %timeit df[df.values.sum(axis=1) != 0]
1000 loops, best of 3: 217 µs per loop

On a larger dataset:

In [119]: bdf = pd.DataFrame(np.random.randint(0,2,size=(10000,4)))

In [120]: %timeit bdf[(bdf.T != 0).any()]
1000 loops, best of 3: 1.63 ms per loop

In [121]: %timeit bdf[(bdf.sum(axis=1) != 0)]
1000 loops, best of 3: 1.09 ms per loop

In [122]: %timeit bdf[bdf.values.sum(axis=1) != 0]
1000 loops, best of 3: 517 µs per loop

Changing the background color of a drop down list transparent in html

You can actualy fake the transparency of option DOMElements with the following CSS:

CSS

option { 
    /* Whatever color  you want */
    background-color: #82caff;
}

See Demo

The option tag does not support rgba colors yet.

How to copy a selection to the OS X clipboard

I used:

map <C-x> :!pbcopy<CR>
vmap <C-c> :w !pbcopy<CR><CR>

It worked really well.

Remove specific characters from a string in Javascript

Honestly I think this probably the most concise and least confusing, but maybe that is just me:

str = "F0123456";
str.replace("f0", "");

Dont even go the regular expression route and simply do a straight replace.

Converting float to char*

typedef union{
    float a;
    char b[4];
} my_union_t;

You can access to float data value byte by byte and send it through 8-bit output buffer (e.g. USART) without casting.

How Do I Take a Screen Shot of a UIView?

Apple does not allow:

CGImageRef UIGetScreenImage();

Applications should take a screenshot using the drawRect method as specified in: http://developer.apple.com/library/ios/#qa/qa2010/qa1703.html

How to create helper file full of functions in react native?

To achieve what you want and have a better organisation through your files, you can create a index.js to export your helper files.

Let's say you have a folder called /helpers. Inside this folder you can create your functions divided by content, actions, or anything you like.

Example:

/* Utils.js */
/* This file contains functions you can use anywhere in your application */

function formatName(label) {
   // your logic
}

function formatDate(date) {
   // your logic
}

// Now you have to export each function you want
export {
   formatName,
   formatDate,
};

Let's create another file which has functions to help you with tables:

/* Table.js */
/* Table file contains functions to help you when working with tables */

function getColumnsFromData(data) {
   // your logic
}

function formatCell(data) {
   // your logic
}

// Export each function
export {
   getColumnsFromData,
   formatCell,
};

Now the trick is to have a index.js inside the helpers folder:

/* Index.js */
/* Inside this file you will import your other helper files */

// Import each file using the * notation
// This will import automatically every function exported by these files
import * as Utils from './Utils.js';
import * as Table from './Table.js';

// Export again
export {
   Utils,
   Table,
};

Now you can import then separately to use each function:

import { Table, Utils } from 'helpers';

const columns = Table.getColumnsFromData(data);
Table.formatCell(cell);

const myName = Utils.formatName(someNameVariable);

Hope it can help to organise your files in a better way.

VueJS conditionally add an attribute for an element

<input :required="condition">

You don't need <input :required="test ? true : false"> because if test is truthy you'll already get the required attribute, and if test is falsy you won't get the attribute. The true : false part is redundant, much like this...

if (condition) {
    return true;
} else {
    return false;
}
// or this...
return condition ? true : false;
// can *always* be replaced by...
return (condition); // parentheses generally not needed

The simplest way of doing this binding, then, is <input :required="condition">

Only if the test (or condition) can be misinterpreted would you need to do something else; in that case Syed's use of !! does the trick.
  <input :required="!!condition">

Handling click events on a drawable within an EditText

@Override
    public boolean onTouch(View v, MotionEvent event) {

        Drawable drawableObj = getResources().getDrawable(R.drawable.search_btn);
        int drawableWidth = drawableObj.getIntrinsicWidth();

        int x = (int) event.getX();
        int y = (int) event.getY();

        if (event != null && event.getAction() == MotionEvent.ACTION_UP) {
            if (x >= (searchPanel_search.getWidth() - drawableWidth - searchPanel_search.getPaddingRight())
                    && x <= (searchPanel_search.getWidth() - searchPanel_search.getPaddingRight())

                    && y >= searchPanel_search.getPaddingTop() && y <= (searchPanel_search.getHeight() - searchPanel_search.getPaddingBottom())) {

                getSearchData();
            }

            else {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(searchPanel_search, InputMethodManager.SHOW_FORCED);
            }
        }
        return super.onTouchEvent(event);

    }

jquery - How to determine if a div changes its height or any css attribute?

First, There is no such css-changes event out of the box, but you can create one by your own, as onchange is for :input elements only. not for css changes.

There are two ways to track css changes.

  1. Examine the DOM element for css changes every x time(500 milliseconds in the example).
  2. Trigger an event when you change the element css.
  3. Use the DOMAttrModified mutation event. But it's deprecated, so I'll skip on it.

First way:

var $element = $("#elementId");
var lastHeight = $("#elementId").css('height');
function checkForChanges()
{
    if ($element.css('height') != lastHeight)
    {
        alert('xxx');
        lastHeight = $element.css('height'); 
    }

    setTimeout(checkForChanges, 500);
}

Second way:

$('#mainContent').bind('heightChange', function(){
        alert('xxx');
    });


$("#btnSample1").click(function() {
    $("#mainContent").css('height', '400px');
    $("#mainContent").trigger('heightChange'); //<====
    ...
});    

If you control the css changes, the second option is a lot more elegant and efficient way of doing it.

Documentations:

  • bind: Description: Attach a handler to an event for the elements.
  • trigger: Description: Execute all handlers and behaviors attached to the matched elements for the given event type.

Installing SetupTools on 64-bit Windows

Here is a link to another post/thread. I was able run this script to automate registration of Python 2.7. (Make sure to run it from the Python 2.x .exe you want to register!)

To register Python 3.x I had to modify the print syntax and import winreg (instead of _winreg), then run the Python 3 .exe.

https://stackoverflow.com/a/29633714/3568893

How to store token in Local or Session Storage in Angular 2?

Save to local storage

localStorage.setItem('currentUser', JSON.stringify({ token: token, name: name }));

Load from local storage

var currentUser = JSON.parse(localStorage.getItem('currentUser'));
var token = currentUser.token; // your token

For more I suggest you go through this tutorial: Angular 2 JWT Authentication Example & Tutorial

Best way to read a large file into a byte array in C#?

I would recommend trying the Response.TransferFile() method then a Response.Flush() and Response.End() for serving your large files.

How do I go about adding an image into a java project with eclipse?

Place the image in a source folder, not a regular folder. That is: right-click on project -> New -> Source Folder. Place the image in that source folder. Then:

InputStream input = classLoader.getResourceAsStream("image.jpg");

Note that the path is omitted. That's because the image is directly in the root of the path. You can add folders under your source folder to break it down further if you like. Or you can put the image under your existing source folder (usually called src).

Convert pandas DataFrame into list of lists

you can do it like this:

map(list, df.values)

How do I add button on each row in datatable?

Take a Look.

$(document).ready(function () {     
        $('#datatable').DataTable({
            columns: [
                { 'data': 'ID' },
                { 'data': 'AuthorName' },
                { 'data': 'TotalBook' },
                { 'data': 'DateofBirth' },
                { 'data': 'OccupationEN' },   
                { 'data': null, title: 'Action', wrap: true, "render": function (item) { return '<div class="btn-group"> <button type="button" onclick="set_value(' + item.ID + ')" value="0" class="btn btn-warning" data-toggle="modal" data-target="#myModal">View</button></div>' } },
            ],            
            bServerSide: true,
            sAjaxSource: 'EmployeeDataHandler.ashx'           
        });       
    });

How can I disable ARC for a single file in a project?

Just use the -fno-objc-arc flag in Build Phases>Compile Sources

What is the difference between __str__ and __repr__?

Excellent answers already cover the difference between __str__ and __repr__, which for me boils down to the former being readable even by an end user, and the latter being as useful as possible to developers. Given that, I find that the default implementation of __repr__ often fails to achieve this goal because it omits information useful to developers.

For this reason, if I have a simple enough __str__, I generally just try to get the best of both worlds with something like:

def __repr__(self):
    return '{0} ({1})'.format(object.__repr__(self), str(self))

How do I remove newlines from a text file?

use

head -n 1 filename | od -c 

to figure WHAT is the offending character. then use

tr -d '\n' <filename

for LF

tr -d '\r\n' <filename

for CRLF

Cannot find or open the PDB file in Visual Studio C++ 2010

Working with VS 2013.
Try the following Tools -> Options -> Debugging -> Output Window -> Module Load Messages -> Off

It will disable the display of modules loaded.

.jar error - could not find or load main class

I Faced the same issue while installing a setup using a jar file. Solution thta worked for me is

  1. open command prompt as administrator
  2. Go to jdk bin directory (Ex.C:\Program Files\Java\jdk1.8.0_73\bin)
  3. now execute java -jar <<jar fully qualified path>>

It worked for me :)

Tomcat 7 "SEVERE: A child container failed during start"

I have seen this exception while tomcat started and it almost took many hours to figure out the reason. Finally I found out that there were some Spring JARs of a lower version in the lib folder in addition to the Spring jars in the Maven dependencies. The JARs in the lib were automatically added by Eclipse when I added a new Spring Rest controller. I removed those from the lib folder and then let Maven handle the JARs/dependancies and it was fine. Bottom line is if the JARS managed by maven and jars in the WEB-INF/lib causes a classpath issues, you may encounter this error.

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

Python script to do something at the same time every day

APScheduler might be what you are after.

from datetime import date
from apscheduler.scheduler import Scheduler

# Start the scheduler
sched = Scheduler()
sched.start()

# Define the function that is to be executed
def my_job(text):
    print text

# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)

# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])

# The job will be executed on November 6th, 2009 at 16:30:05
job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])

https://apscheduler.readthedocs.io/en/latest/

You can just get it to schedule another run by building that into the function you are scheduling.

How to Change Font Size in drawString Java

code example below:

g.setFont(new Font("TimesRoman", Font.PLAIN, 30));
g.drawString("Welcome to the Java Applet", 20 , 20);

Implode an array with JavaScript?

array.join was not recognizing ";" how a separator, but replacing it with comma. Using jQuery, you can use $.each to implode an array (Note that output_saved_json is the array and tmp is the string that will store the imploded array):

var tmp = "";
$.each(output_saved_json, function(index,value) {
    tmp = tmp + output_saved_json[index] + ";";
});

output_saved_json = tmp.substring(0,tmp.length - 1); // remove last ";" added

I have used substring to remove last ";" added at the final without necessity. But if you prefer, you can use instead substring something like:

var tmp = "";
$.each(output_saved_json, function(index,value) {
    tmp = tmp + output_saved_json[index];

    if((index + 1) != output_saved_json.length) {
         tmp = tmp + ";";
    }
});

output_saved_json = tmp;

I think this last solution is more slower than the 1st one because it needs to check if index is different than the lenght of array every time while $.each do not end.

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

Great answers! One thing that I would like to clarify deeper is nonatomic/atomic. The user should understand that this property - "atomicity" spreads only on the attribute's reference and not on it's contents. I.e. atomic will guarantee the user atomicity for reading/setting the pointer and only the pointer to the attribute. For example:

@interface MyClass: NSObject
@property (atomic, strong) NSDictionary *dict;
...

In this case it is guaranteed that the pointer to the dict will be read/set in the atomic manner by different threads. BUT the dict itself (the dictionary dict pointing to) is still thread unsafe, i.e. all read/add operations to the dictionary are still thread unsafe.

If you need thread safe collection you either have bad architecture (more often) OR real requirement (more rare). If it is "real requirement" - you should either find good&tested thread safe collection component OR be prepared for trials and tribulations writing your own one. It latter case look at "lock-free", "wait-free" paradigms. Looks like rocket-science at a first glance, but could help you achieving fantastic performance in comparison to "usual locking".

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

I used the Visual Studio 2008 Uninstall tool and it worked fine for me.

You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).

Found here, on the MSDN Forum: MSDN forum topic.

I found this answer here

Be sure you run the tool with admin-rights.

SQL - using alias in Group By

I'm not answering why it is so, but only wanted to show a way around that limitation in SQL Server by using CROSS APPLY to create the alias. You then use it in the GROUP BY clause, like so:

SELECT 
 itemName as ItemName,
 FirstLetter,
 Count(itemName)
FROM table1
CROSS APPLY (SELECT substring(itemName, 1,1) as FirstLetter) Alias
GROUP BY itemName, FirstLetter

What is the method for converting radians to degrees?

pi Radians = 180 degrees

So 1 degree = pi/180 radians

or 1 radian = 180/pi degrees

Removing duplicate values from a PowerShell array

In case you want to be fully bomb prove, this is what I would advice:

@('Apples', 'Apples ', 'APPLES', 'Banana') | 
    Sort-Object -Property @{Expression={$_.Trim()}} -Unique

Output:

Apples
Banana

This uses the Property parameter to first Trim() the strings, so extra spaces are removed and then selects only the -Unique values.

More info on Sort-Object:

Get-Help Sort-Object -ShowWindow

'Use of Unresolved Identifier' in Swift

I got this error for Mantle Framework in my Objective-Swift Project. What i tried is ,

  1. Check if import is there in Bridging-Header.h file
  2. Change the Target Membership for Framework in Mantle.h file as shown in below screenshot.

Toggle between Private Membership first build the project , end up with errors. Then build the project with Public Membership for all the frameworks appeared for Mantle.h file, you must get success.

It is just a bug of building with multiple framework in Objective-C Swift project.

enter image description here

Optimum way to compare strings in JavaScript?

You can use the comparison operators to compare strings. A strcmp function could be defined like this:

function strcmp(a, b) {
    if (a.toString() < b.toString()) return -1;
    if (a.toString() > b.toString()) return 1;
    return 0;
}

Edit    Here’s a string comparison function that takes at most min { length(a), length(b) } comparisons to tell how two strings relate to each other:

function strcmp(a, b) {
    a = a.toString(), b = b.toString();
    for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
    if (i === n) return 0;
    return a.charAt(i) > b.charAt(i) ? -1 : 1;
}

ASP.NET MVC Razor pass model to layout

this is pretty basic stuff, all you need to do is to create a base view model and make sure ALL! and i mean ALL! of your views that will ever use that layout will receive views that use that base model!

public class SomeViewModel : ViewModelBase
{
    public bool ImNotEmpty = true;
}

public class EmptyViewModel : ViewModelBase
{
}

public abstract class ViewModelBase
{
}

in the _Layout.cshtml:

@model Models.ViewModelBase
<!DOCTYPE html>
  <html>
  and so on...

in the the Index (for example) method in the home controller:

    public ActionResult Index()
    {
        var model = new SomeViewModel()
        {
        };
        return View(model);
    }

the Index.cshtml:

@model Models.SomeViewModel

@{
  ViewBag.Title = "Title";
  Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="row">

i disagree that passing a model to the _layout is an error, some user info can be passed and the data can be populate in the controllers inheritance chain so only one implementation is needed.

obviously for more advanced purpose you should consider creating custom static contaxt using injection and include that model namespace in the _Layout.cshtml.

but for basic users this will do the trick

try/catch with InputMismatchException creates infinite loop

As the bError = false statement is never reached in the try block, and the statement is struck to the input taken, it keeps printing the error in infinite loop.

Try using it this way by using hasNextInt()

catch (Exception e) {
            System.out.println("Error!");
           input.hasNextInt();         
        }

Or try using nextLine() coupled with Integer.parseInt() for taking input....

Scanner scan = new Scanner(System.in);

int num1 = Integer.parseInt(scan.nextLine());
int num2 = Integer.parseInt(scan.nextLine());

Why em instead of px?

The general consensus is to use percentages for font sizing, because it's more consistent across browsers/platforms.

It's funny though, I always used to use pt for font sizing and I assumed all sites used that. You don't normally use px sizes in other apps (eg Word). I guess it's because they're for printing - but the size is the same in a web browser as in Word...

Find a pair of elements from an array whose sum equals a given number

Implementation in Java : Using codaddict's algorithm:

import java.util.Hashtable;
public class Range {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Hashtable mapping = new Hashtable();
    int a[]= {80,79,82,81,84,83,85};
    int k = 160;

    for (int i=0; i < a.length; i++){
        mapping.put(a[i], i);
    }

    for (int i=0; i < a.length; i++){
        if (mapping.containsKey(k - a[i]) && (Integer)mapping.get(k-a[i]) != i){
            System.out.println(k-a[i]+", "+ a[i]);
        }
    }      

}

}

Output:

81, 79
79, 81

If you want duplicate pairs (eg: 80,80) also then just remove && (Integer)mapping.get(k-a[i]) != i from the if condition and you are good to go.

Is arr.__len__() the preferred way to get the length of an array in Python?

you can use len(arr) as suggested in previous answers to get the length of the array. In case you want the dimensions of a 2D array you could use arr.shape returns height and width

Why am I getting a FileNotFoundError?

Difficult to give code examples in the comments.

To read the words in the file, you can read the contents of the file, which gets you a string - this is what you were doing before, with the read() method - and then use split() to get the individual words. Split breaks up a String on the delimiter provided, or on whitespace by default. For example,

"the quick brown fox".split()

produces

['the', 'quick', 'brown', 'fox']

Similarly,

fileScan.read().split()

will give you an array of Strings. Hope that helps!

How to use Typescript with native ES6 Promises

If you use node.js 0.12 or above / typescript 1.4 or above, just add compiler options like:

tsc a.ts --target es6 --module commonjs

More info: https://github.com/Microsoft/TypeScript/wiki/Compiler-Options

If you use tsconfig.json, then like this:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6"
    }
}

More info: https://github.com/Microsoft/TypeScript/wiki/tsconfig.json

regular expression for finding 'href' value of a <a> link

 HTMLDocument DOC = this.MySuperBrowser.Document as HTMLDocument;
 public IHTMLAnchorElement imageElementHref;
 imageElementHref = DOC.getElementById("idfirsticonhref") as IHTMLAnchorElement;

Simply try this code

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

In some cases _hostingEnvironment.ContentRootPath and System.IO.Directory.GetCurrentDirectory() targets to source directory. Here is bug about it.

The solution proposed there helped me

Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

Index all *except* one item in python

Use np.delete ! It does not actually delete anything inplace

Example:

import numpy as np
a = np.array([[1,4],[5,7],[3,1]])                                       

# a: array([[1, 4],
#           [5, 7],
#           [3, 1]])

ind = np.array([0,1])                                                   

# ind: array([0, 1])

# a[ind]: array([[1, 4],
#                [5, 7]])

all_except_index = np.delete(a, ind, axis=0)                                              
# all_except_index: array([[3, 1]])

# a: (still the same): array([[1, 4],
#                             [5, 7],
#                             [3, 1]])

What is a "method" in Python?

In Python, a method is a function that is available for a given object because of the object's type.

For example, if you create my_list = [1, 2, 3], the append method can be applied to my_list because it's a Python list: my_list.append(4). All lists have an append method simply because they are lists.

As another example, if you create my_string = 'some lowercase text', the upper method can be applied to my_string simply because it's a Python string: my_string.upper().

Lists don't have an upper method, and strings don't have an append method. Why? Because methods only exist for a particular object if they have been explicitly defined for that type of object, and Python's developers have (so far) decided that those particular methods are not needed for those particular objects.

To call a method, the format is object_name.method_name(), and any arguments to the method are listed within the parentheses. The method implicitly acts on the object being named, and thus some methods don't have any stated arguments since the object itself is the only necessary argument. For example, my_string.upper() doesn't have any listed arguments because the only required argument is the object itself, my_string.

One common point of confusion regards the following:

import math
math.sqrt(81)

Is sqrt a method of the math object? No. This is how you call the sqrt function from the math module. The format being used is module_name.function_name(), instead of object_name.method_name(). In general, the only way to distinguish between the two formats (visually) is to look in the rest of the code and see if the part before the period (math, my_list, my_string) is defined as an object or a module.

How to show disable HTML select option in by default?

I know you ask how to disable the option, but I figure the end users visual outcome is the same with this solution, although it is probably marginally less resource demanding.

Use the optgroup tag, like so :

<select name="tagging">
    <optgroup label="Choose Tagging">
        <option value="Option A">Option A</option>
        <option value="Option B">Option B</option>
        <option value="Option C">Option C</option>
    </optgroup>
</select>

How to change indentation mode in Atom?

Changing language-specific configuration

I changed the default tab settings, and it still did not impact when I was editing my files, which were Python files. It also did not change when I modified the "*" setting in ~/.atom/config.cson . I don't have a good explanation for either of those.

However, when I added the following to my config.cson, I was able to change the tab in my Python files to 2 spaces:

'.source.python':
  editor:
    tabLength: 2

Thanks to this resource for the solution: Tab key not respecting tab length

How can I prevent the backspace key from navigating back?

Using Dojo toolkit 1.7, this works in IE 8:

require(["dojo/on", "dojo/keys", "dojo/domReady!"],
function(on, keys) {
    on(document.body,"keydown",function(evt){if(evt.keyCode == keys.BACKSPACE)evt.preventDefault()});
});

Concatenating strings in Razor

Use the parentesis syntax of Razor:

@(Model.address + " " + Model.city)

or

@(String.Format("{0} {1}", Model.address, Model.city))

Update: With C# 6 you can also use the $-Notation (officially interpolated strings):

@($"{Model.address} {Model.city}")

Better/Faster to Loop through set or list?

While a set may be what you want structure-wise, the question is what is faster. A list is faster. Your example code doesn't accurately compare set vs list because you're converting from a list to a set in set_loop, and then you're creating the list you'll be looping through in list_loop. The set and list you iterate through should be constructed and in memory ahead of time, and simply looped through to see which data structure is faster at iterating:

ids_list = range(1000000)
ids_set = set(ids)
def f(x):
    for i in x:
         pass

%timeit f(ids_set)
#1 loops, best of 3: 214 ms per loop
%timeit f(ids_list)
#1 loops, best of 3: 176 ms per loop

how to set width for PdfPCell in ItextSharp

aca definis los anchos

 float[] anchoDeColumnas= new float[] {10f, 20f, 30f, 10f};

aca se los insertas a la tabla que tiene las columnas

table.setWidths(anchoDeColumnas);

How to access parameters in a Parameterized Build?

You can also try using parameters directive for making your build parameterized and accessing parameters:

Doc: Pipeline syntax: Parameters

Example:

pipeline{

agent { node { label 'test' } }
options { skipDefaultCheckout() }

parameters {
    string(name: 'suiteFile', defaultValue: '', description: 'Suite File')
}
stages{

    stage('Initialize'){

        steps{

          echo "${params.suiteFile}"

        }
    }
 }

How to join multiple collections with $lookup in mongodb

You can actually chain multiple $lookup stages. Based on the names of the collections shared by profesor79, you can do this :

db.sivaUserInfo.aggregate([
    {
        $lookup: {
           from: "sivaUserRole",
           localField: "userId",
           foreignField: "userId",
           as: "userRole"
        }
    },
    {
        $unwind: "$userRole"
    },
    {
        $lookup: {
            from: "sivaUserInfo",
            localField: "userId",
            foreignField: "userId",
            as: "userInfo"
        }
    },
    {
        $unwind: "$userInfo"
    }
])

This will return the following structure :

{
    "_id" : ObjectId("56d82612b63f1c31cf906003"),
    "userId" : "AD",
    "phone" : "0000000000",
    "userRole" : {
        "_id" : ObjectId("56d82612b63f1c31cf906003"),
        "userId" : "AD",
        "role" : "admin"
    },
    "userInfo" : {
        "_id" : ObjectId("56d82612b63f1c31cf906003"),
        "userId" : "AD",
        "phone" : "0000000000"
    }
}

Maybe this could be considered an anti-pattern because MongoDB wasn't meant to be relational but it is useful.

jQuery send string as POST parameters

For a similar application I had to wrap my data object with JSON.stringify() like this:

data: JSON.stringify({ 
  'foo': 'bar', 
  'ca$libri': 'no$libri'
}),

The API was working with a REST client but couldn't get it to function with jquery ajax in the browser. stringify was the solution.

How can I use a batch file to write to a text file?

@echo off

echo Type your text here.

:top

set /p boompanes=

pause

echo %boompanes%> practice.txt

hope this helps. you should change the string names(IDK what its called) and the file name

ES6 exporting/importing in index file

Simply:

// Default export (recommended)
export {default} from './MyClass' 

// Default export with alias
export {default as d1} from './MyClass' 

// In >ES7, it could be
export * from './MyClass'

// In >ES7, with alias
export * as d1 from './MyClass'

Or by functions names :

// export by function names
export { funcName1, funcName2, …} from './MyClass'

// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './MyClass'

More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

How to Serialize a list in java?

List is just an interface. The question is: is your actual List implementation serializable? Speaking about the standard List implementations (ArrayList, LinkedList) from the Java run-time, most of them actually are already.

How can we dynamically allocate and grow an array

You allocate a new Array (double the capacity, for instance), and move all elements to it.

Basically you need to check if the wordCount is about to hit the wordList.size(), when it does, create a new array with twice the length of the previous one, and copy all elements to it (create an auxiliary method to do this), and assign wordList to your new array.

To copy the contents over, you could use System.arraycopy, but I'm not sure that's allowed with your restrictions, so you can simply copy the elements one by one:

public String[] createNewArray(String[] oldArray){
    String[] newArray = new String[oldArray.length * 2];
    for(int i = 0; i < oldArray.length; i++) {
        newArray[i] = oldArray[i];
    }

    return newArray;
}

Proceed.

Express.js Response Timeout

Before you set your routes, add the code:

app.all('*', function(req, res, next) {
    setTimeout(function() {
        next();
    }, 120000); // 120 seconds
});

Java: Convert a String (representing an IP) to InetAddress

Simply call InetAddress.getByName(String host) passing in your textual IP address.

From the javadoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.

InetAddress javadoc

adding 1 day to a DATETIME format value

There is a more concise and intuitive way to add days to php date. Don't get me wrong, those php expressions are great, but you always have to google how to treat them. I miss auto-completion facility for that.

Here is how I like to handle those cases:

(new Future(
    new DateTimeFromISO8601String('2014-11-21T06:04:31.321987+00:00'),
    new OneDay()
))
    ->value();

For me, it's way more intuitive and autocompletion works out of the box. No need to google for the solution each time.

As a nice bonus, you don't have to worry about formatting the resulting value, it's already is ISO8601 format.

This is meringue library, there are more examples here.

Java: how do I check if a Date is within a certain range?

you can use like this

Interval interval = new Interval(date1.getTime(),date2.getTime());
Interval interval2 = new Interval(date3.getTime(), date4.getTime());
Interval overlap = interval.overlap(interval2);
boolean isOverlap = overlap == null ? false : true

ImportError: No module named 'encodings'

For Python-3 try removing virtual environment files. And resetting it up.

rm -rf venv
virtualenv -p /usr/bin/python3 venv/
source venv/bin/activate
pip install -r requirements.txt

https://wiki.ubuntu.com/XenialXerus/ReleaseNotes#Python_3 edit fo