Programs & Examples On #Amd

The Asynchronous Module Definition (AMD) API specifies a mechanism for defining modules such that the module and its dependencies can be asynchronously loaded. The AMD pattern is well suited for the browser environment where synchronous loading can be problematic.

Is it possible to run CUDA on AMD GPUs?

Nope, you can't use CUDA for that. CUDA is limited to NVIDIA hardware. OpenCL would be the best alternative.

Khronos itself has a list of resources. As does the StreamComputing.eu website. For your AMD specific resources, you might want to have a look at AMD's APP SDK page.

Note that at this time there are several initiatives to translate/cross-compile CUDA to different languages and APIs. One such an example is HIP. Note however that this still does not mean that CUDA runs on AMD GPUs.

Managing jQuery plugin dependency in webpack

This works in webpack 3:

in the webpack.config.babel.js file:

resolve: {
    alias: {
         jquery: "jquery/src/jquery"
    },
 ....
}

And use ProvidePlugin

new webpack.ProvidePlugin({
        '$': 'jquery',
        'jQuery': 'jquery',
    })

Relation between CommonJS, AMD and RequireJS?

AMD

  • introduced in JavaScript to scale JavaScript project into multiple files
  • mostly used in browser based application and libraries
  • popular implementation is RequireJS, Dojo Toolkit

CommonJS:

  • it is specification to handle large number of functions, files and modules of big project
  • initial name ServerJS introduced in January, 2009 by Mozilla
  • renamed in August, 2009 to CommonJS to show the broader applicability of the APIs
  • initially implementation were server, nodejs, desktop based libraries

Example

upper.js file

exports.uppercase = str => str.toUpperCase()

main.js file

const uppercaseModule = require('uppercase.js')
uppercaseModule.uppercase('test')

Summary

  • AMD – one of the most ancient module systems, initially implemented by the library require.js.
  • CommonJS – the module system created for Node.js server.
  • UMD – one more module system, suggested as a universal one, compatible with AMD and CommonJS.

Resources:

Create a unique number with javascript time

This performs faster than creating a Date instance, uses less code and will always produce a unique number (locally):

function uniqueNumber() {
    var date = Date.now();

    // If created at same millisecond as previous
    if (date <= uniqueNumber.previous) {
        date = ++uniqueNumber.previous;
    } else {
        uniqueNumber.previous = date;
    }

    return date;
}

uniqueNumber.previous = 0;

jsfiddle: http://jsfiddle.net/j8aLocan/

I've released this on Bower and npm: https://github.com/stevenvachon/unique-number

You could also use something more elaborate such as cuid, puid or shortid to generate a non-number.

GCC: array type has incomplete element type

It's the array that's causing trouble in:

void print_graph(g_node graph_node[], double weight[][], int nodes);

The second and subsequent dimensions must be given:

void print_graph(g_node graph_node[], double weight[][32], int nodes);

Or you can just give a pointer to pointer:

void print_graph(g_node graph_node[], double **weight, int nodes);

However, although they look similar, those are very different internally.

If you're using C99, you can use variably-qualified arrays. Quoting an example from the C99 standard (section §6.7.5.2 Array Declarators):

void fvla(int m, int C[m][m]); // valid: VLA with prototype scope

void fvla(int m, int C[m][m])  // valid: adjusted to auto pointer to VLA
{
    typedef int VLA[m][m];     // valid: block scope typedef VLA
    struct tag {
        int (*y)[n];           // invalid: y not ordinary identifier
        int z[n];              // invalid: z not ordinary identifier
    };
    int D[m];                  // valid: auto VLA
    static int E[m];           // invalid: static block scope VLA
    extern int F[m];           // invalid: F has linkage and is VLA
    int (*s)[m];               // valid: auto pointer to VLA
    extern int (*r)[m];        // invalid: r has linkage and points to VLA
    static int (*q)[m] = &B;   // valid: q is a static block pointer to VLA
}

Question in comments

[...] In my main(), the variable I am trying to pass into the function is a double array[][], so how would I pass that into the function? Passing array[0][0] into it gives me incompatible argument type, as does &array and &array[0][0].

In your main(), the variable should be:

double array[10][20];

or something faintly similar; maybe

double array[][20] = { { 1.0, 0.0, ... }, ... };

You should be able to pass that with code like this:

typedef struct graph_node
{
    int X;
    int Y;
    int active;
} g_node;

void print_graph(g_node graph_node[], double weight[][20], int nodes);

int main(void)
{
    g_node g[10];
    double array[10][20];
    int n = 10;

    print_graph(g, array, n);
    return 0;
}

That compiles (to object code) cleanly with GCC 4.2 (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)) and also with GCC 4.7.0 on Mac OS X 10.7.3 using the command line:

/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -c zzz.c

jQuery convert line breaks to br (nl2br equivalent)

Another way to insert text from a textarea in the DOM keeping the line breaks is to use the Node.innerText property that represents the rendered text content of a node and its descendants.

As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied to the clipboard.

The property became standard in 2016 and is well supported by modern browsers. Can I Use: 97% global coverage when I posted this answer.

How to use OAuth2RestTemplate?

My simple solution. IMHO it's the cleanest.

First create a application.yml

spring.main.allow-bean-definition-overriding: true

security:
  oauth2:
    client:
      clientId: XXX
      clientSecret: XXX
      accessTokenUri: XXX
      tokenName: access_token
      grant-type: client_credentials

Create the main class: Main

@SpringBootApplication
@EnableOAuth2Client
public class Main extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll();
    }

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

    @Bean
    public OAuth2RestTemplate oauth2RestTemplate(ClientCredentialsResourceDetails details) {
        return new OAuth2RestTemplate(details);
    }

}

Then Create the controller class: Controller

@RestController
class OfferController {

    @Autowired
    private OAuth2RestOperations restOperations;

    @RequestMapping(value = "/<your url>"
            , method = RequestMethod.GET
            , produces = "application/json")
    public String foo() {
        ResponseEntity<String> responseEntity = restOperations.getForEntity(<the url you want to call on the server>, String.class);
        return responseEntity.getBody();
    }
}

Maven dependencies

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.1.5.RELEASE</version>
    </dependency>
</dependencies>

The simplest way to resize an UIImage?

Use this extension, in case you need to resize width/height only with aspect ratio.

extension UIImage {
    func resize(to size: CGSize) -> UIImage {
        return UIGraphicsImageRenderer(size: size).image { _ in
            draw(in: CGRect(origin: .zero, size: size))
        }
    }
    func resize(width: CGFloat) -> UIImage {
        return resize(to: CGSize(width: width, height: width / (size.width / size.height)))
    }
    func resize(height: CGFloat) -> UIImage {
        return resize(to: CGSize(width: height * (size.width / size.height), height: height))
    }
}

"cannot be used as a function error"

This line is the problem:

int estimatedPopulation (int currentPopulation,
                         float growthRate (birthRate, deathRate))

Make it:

int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)

instead and invoke the function with three arguments like

estimatePopulation( currentPopulation, birthRate, deathRate );

OR declare it with two arguments like:

int estimatedPopulation (int currentPopulation, float growthrt ) { ... }

and call it as

estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));

Edit:

Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate variable in the main() hides the function with the same name. So within main() you can only access grouthRate as float. On the other hand, outside of the main() you can only access that name as a function, since that automatic variable is only visible within the scope of main().

Just hope I didn't confuse you further :)

javax.naming.NameNotFoundException

The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.

As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:

/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml

The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.

BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is

@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
   public void bussinesMethod(){

   }
}

No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.

Now in your client code you need to lookup "MyComponentName".

Altering column size in SQL Server

You can use ALTER command to modify the table schema.

The syntax for modifying the column size is

ALTER table table_name modify COLUMN column_name varchar (size);

API Gateway CORS: no 'Access-Control-Allow-Origin' header

1) I needed to do the same as @riseres and some other changes.This are my response headers:

headers: {
            'Access-Control-Allow-Origin' : '*',
            'Access-Control-Allow-Headers':'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
            'Access-Control-Allow-Credentials' : true,
            'Content-Type': 'application/json'
        }

2) And

According to this documentation:

http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

When you use proxy for lambda functions on API Gateway config, the post or get methods have no added headers, only the options does. You must do it manually in the response(server or lambda response).

3) And

Beside that, I needed to disable the 'API Key Required' option in my API gateway post method.

Is there any JSON Web Token (JWT) example in C#?

It would be better to use standard and famous libraries instead of writing the code from scratch.

  1. JWT for encoding and decoding JWT tokens
  2. Bouncy Castle supports encryption and decryption, especially RS256 get it here

Using these libraries you can generate a JWT token and sign it using RS256 as below.

    public string GenerateJWTToken(string rsaPrivateKey)
    {
        var rsaParams = GetRsaParameters(rsaPrivateKey);
        var encoder = GetRS256JWTEncoder(rsaParams);

        // create the payload according to the Google's doc
        var payload = new Dictionary<string, object>
        {
            { "iss", ""},
            { "sub", "" },
            // and other key-values according to the doc
        };

        // add headers. 'alg' and 'typ' key-values are added automatically.
        var header = new Dictionary<string, object>
        {
            { "kid", "{your_private_key_id}" },
        };

        var token = encoder.Encode(header,payload, new byte[0]);

        return token;
    }

    private static IJwtEncoder GetRS256JWTEncoder(RSAParameters rsaParams)
    {
        var csp = new RSACryptoServiceProvider();
        csp.ImportParameters(rsaParams);

        var algorithm = new RS256Algorithm(csp, csp);
        var serializer = new JsonNetSerializer();
        var urlEncoder = new JwtBase64UrlEncoder();
        var encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

        return encoder;
    }

    private static RSAParameters GetRsaParameters(string rsaPrivateKey)
    {
        var byteArray = Encoding.ASCII.GetBytes(rsaPrivateKey);
        using (var ms = new MemoryStream(byteArray))
        {
            using (var sr = new StreamReader(ms))
            {
                // use Bouncy Castle to convert the private key to RSA parameters
                var pemReader = new PemReader(sr);
                var keyPair = pemReader.ReadObject() as AsymmetricCipherKeyPair;
                return DotNetUtilities.ToRSAParameters(keyPair.Private as RsaPrivateCrtKeyParameters);
            }
        }
    }

ps: the RSA private key should have the following format:

-----BEGIN RSA PRIVATE KEY----- {base64 formatted value} -----END RSA PRIVATE KEY-----

How to maintain page scroll position after a jquery event is carried out?

What you want to do is prevent the default action of the click event. To do this, you will need to modify your script like this:

$(document).ready(function() {
  $('.galleryicon').live("click", function(e) {

    $('#mainImage').hide();
    $('#cakebox').css('background-image', "url('ajax-loader.gif')");
    var i = $('<img />').attr('src',this.href).load(function() {
        $('#mainImage').attr('src', i.attr('src'));
        $('#cakebox').css('background-image', 'none');
        $('#mainImage').fadeIn();
    });
    return false; 
    e.preventDefault();
   });
 });

So, you're adding an "e" that represents the event in the line $('.galleryicon').live("click", function(e) { and you're adding the line e.preventDefault();

Error handling with PHPMailer

Even if you use exceptions, it still output errors.
You have to set $MailerDebug to False wich should look like this

$mail = new PHPMailer();
$mail->MailerDebug = false;

Why does instanceof return false for some literals?

The primitive wrapper types are reference types that are automatically created behind the scenes whenever strings, num­bers, or Booleans are read.For example :

var name = "foo";
var firstChar = name.charAt(0);
console.log(firstChar);

This is what happens behind the scenes:

// what the JavaScript engine does
var name = "foo";
var temp = new String(name);
var firstChar = temp.charAt(0);
temp = null;
console.log(firstChar);

Because the second line uses a string (a primitive) like an object, the JavaScript engine creates an instance of String so that charAt(0) will work.The String object exists only for one statement before it’s destroyed check this

The instanceof operator returns false because a temporary object is created only when a value is read. Because instanceof doesn’t actually read anything, no temporary objects are created, and it tells us the ­values aren’t instances of primitive wrapper types. You can create primitive wrapper types manually

How to call another controller Action From a controller in Mvc

I know it's old, but you can:

  • Create a service layer
  • Move method there
  • Call method in both controllers

Laravel is there a way to add values to a request array

You can access directly the request array with $request['key'] = 'value';

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

Android failed to load JS bundle

### Here is my solution

None of the above solutions can solve my problem but only follow the below steps working for me. Add in network-security-config.xml file

    <domain-config cleartextTrafficPermitted="true">
          <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
    ...

Then update AndroidManifest.xml file with

<application
+   android:networkSecurityConfig="@xml/network_security_config"
    ...

How to add minutes to current time in swift

In case you want unix timestamp

        let now : Date = Date()
        let currentCalendar : NSCalendar = Calendar.current as NSCalendar

        let nowPlusAddTime : Date = currentCalendar.date(byAdding: .second, value: accessTime, to: now, options: .matchNextTime)!

        let unixTime = nowPlusAddTime.timeIntervalSince1970

How do you create a yes/no boolean field in SQL server?

The BIT datatype is generally used to store boolean values (0 for false, 1 for true).

How to specify credentials when connecting to boto3 S3?

I'd like expand on @JustAGuy's answer. The method I prefer is to use AWS CLI to create a config file. The reason is, with the config file, the CLI or the SDK will automatically look for credentials in the ~/.aws folder. And the good thing is that AWS CLI is written in python.

You can get cli from pypi if you don't have it already. Here are the steps to get cli set up from terminal

$> pip install awscli  #can add user flag 
$> aws configure
AWS Access Key ID [****************ABCD]:[enter your key here]
AWS Secret Access Key [****************xyz]:[enter your secret key here]
Default region name [us-west-2]:[enter your region here]
Default output format [None]:

After this you can access boto and any of the api without having to specify keys (unless you want to use a different credentials).

How to draw border on just one side of a linear layout?

As an alternative (if you don't want to use background), you can easily do it by making a view as follows:

<View
    android:layout_width="2dp"
    android:layout_height="match_parent"
    android:background="#000000" />

For having a right border only, place this after the layout (where you want to have the border):

<View
    android:layout_width="2dp"
    android:layout_height="match_parent"
    android:background="#000000" />

For having a left border only, place this before the layout (where you want to have the border):

Worked for me...Hope its of some help....

How to set JAVA_HOME in Linux for all users

Probably a good idea to source whatever profile you edit to save having to use a fresh login.

either: source /etc/ or . /etc/

Where is whatever profile you edited.

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

You can fix this issue without opening the storyboard as a source. This warning is triggered by UILabels if numberOfLines !=1 and deployment target is < 8.0

HOW TO FIND IT?

  1. Go to Issue Navigator (CMD+8) and Select latest built with the warning enter image description here
  2. Locate the warning(s) (search for "Automatic Preferred Max Layout") and press expand button on the right
    enter image description here
  3. Find the Object ID of the UILabel enter image description here
  4. Open the Storyboard and SEARCH (CMD+f) for the object. It will SELECT AND HIGHLIGHT the UILabel
  5. Set Preferred Width = 0 "Explicit" as others suggested

How do I preserve line breaks when getting text from a textarea?

The easiest solution is to simply style the element you're inserting the text into with the following CSS property:

white-space: pre-wrap;

This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a <textarea>. That is, consecutive whitespace is not collapsed, and lines are broken at explicit newlines (but are also wrapped automatically if they exceed the width of the element).

Given that several of the answers posted here so far have been vulnerable to HTML injection (e.g. because they assign unescaped user input to innerHTML) or otherwise buggy, let me give an example of how to do this safely and correctly, based on your original code:

_x000D_
_x000D_
document.getElementById('post-button').addEventListener('click', function () {_x000D_
  var post = document.createElement('p');_x000D_
  var postText = document.getElementById('post-text').value;_x000D_
  post.append(postText);_x000D_
  var card = document.createElement('div');_x000D_
  card.append(post);_x000D_
  var cardStack = document.getElementById('card-stack');_x000D_
  cardStack.prepend(card);_x000D_
});
_x000D_
#card-stack p {_x000D_
  background: #ddd;_x000D_
  white-space: pre-wrap;  /* <-- THIS PRESERVES THE LINE BREAKS */_x000D_
}_x000D_
textarea {_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
_x000D_
_x000D_


Note that, like your original code, the snippet above uses append() and prepend(). As of this writing, those functions are still considered experimental and not fully supported by all browsers. If you want to be safe and remain compatible with older browsers, you can substitute them pretty easily as follows:

  • element.append(otherElement) can be replaced with element.appendChild(otherElement);
  • element.prepend(otherElement) can be replaced with element.insertBefore(otherElement, element.firstChild);
  • element.append(stringOfText) can be replaced with element.appendChild(document.createTextNode(stringOfText));
  • element.prepend(stringOfText) can be replaced with element.insertBefore(document.createTextNode(stringOfText), element.firstChild);
  • as a special case, if element is empty, both element.append(stringOfText) and element.prepend(stringOfText) can simply be replaced with element.textContent = stringOfText.

Here's the same snippet as above, but without using append() or prepend():

_x000D_
_x000D_
document.getElementById('post-button').addEventListener('click', function () {_x000D_
  var post = document.createElement('p');_x000D_
  var postText = document.getElementById('post-text').value;_x000D_
  post.textContent = postText;_x000D_
  var card = document.createElement('div');_x000D_
  card.appendChild(post);_x000D_
  var cardStack = document.getElementById('card-stack');_x000D_
  cardStack.insertBefore(card, cardStack.firstChild);_x000D_
});
_x000D_
#card-stack p {_x000D_
  background: #ddd;_x000D_
  white-space: pre-wrap;  /* <-- THIS PRESERVES THE LINE BREAKS */_x000D_
}_x000D_
textarea {_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
_x000D_
_x000D_


Ps. If you really want to do this without using the CSS white-space property, an alternative solution would be to explicitly replace any newline characters in the text with <br> HTML tags. The tricky part is that, to avoid introducing subtle bugs and potential security holes, you have to first escape any HTML metacharacters (at a minimum, & and <) in the text before you do this replacement.

Probably the simplest and safest way to do that is to let the browser handle the HTML-escaping for you, like this:

var post = document.createElement('p');
post.textContent = postText;
post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');

_x000D_
_x000D_
document.getElementById('post-button').addEventListener('click', function () {_x000D_
  var post = document.createElement('p');_x000D_
  var postText = document.getElementById('post-text').value;_x000D_
  post.textContent = postText;_x000D_
  post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');  // <-- THIS FIXES THE LINE BREAKS_x000D_
  var card = document.createElement('div');_x000D_
  card.appendChild(post);_x000D_
  var cardStack = document.getElementById('card-stack');_x000D_
  cardStack.insertBefore(card, cardStack.firstChild);_x000D_
});
_x000D_
#card-stack p {_x000D_
  background: #ddd;_x000D_
}_x000D_
textarea {_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
_x000D_
_x000D_

Note that, while this will fix the line breaks, it won't prevent consecutive whitespace from being collapsed by the HTML renderer. It's possible to (sort of) emulate that by replacing some of the whitespace in the text with non-breaking spaces, but honestly, that's getting rather complicated for something that can be trivially solved with a single line of CSS.

ValueError: unconverted data remains: 02:05

Well it was very simple. I was missing the format of the date in the json file, so I should write :

st = datetime.strptime(st, '%A %d %B %H %M')

because in the json file the date was like :

"start": "Friday 06 December 02:05",

React: "this" is undefined inside a component function

in my case this was the solution = () => {}

methodName = (params) => {
//your code here with this.something
}

Passing dynamic javascript values using Url.action()

In my case it worked great just by doing the following:

The Controller:

[HttpPost]
public ActionResult DoSomething(int custNum)
{
    // Some magic code here...
}

Create the form with no action:

<form id="frmSomething" method="post">
    <div>
        <!-- Some magic html here... -->
    </div>
    <button id="btnSubmit" type="submit">Submit</button>
</form>

Set button click event to trigger submit after adding the action to the form:

var frmSomething= $("#frmSomething");
var btnSubmit= $("#btnSubmit");
var custNum = 100;

btnSubmit.click(function()
    {
        frmSomething.attr("action", "/Home/DoSomething?custNum=" + custNum);

        btnSubmit.submit();
    });

Hope this helps vatos!

Is there a "not equal" operator in Python?

Use != or <>. Both stands for not equal.

The comparison operators <> and != are alternate spellings of the same operator. != is the preferred spelling; <> is obsolescent. [Reference: Python language reference]

Optimal number of threads per core

I thought I'd add another perspective here. The answer depends on whether the question is assuming weak scaling or strong scaling.

From Wikipedia:

Weak scaling: how the solution time varies with the number of processors for a fixed problem size per processor.

Strong scaling: how the solution time varies with the number of processors for a fixed total problem size.

If the question is assuming weak scaling then @Gonzalo's answer suffices. However if the question is assuming strong scaling, there's something more to add. In strong scaling you're assuming a fixed workload size so if you increase the number of threads, the size of the data that each thread needs to work on decreases. On modern CPUs memory accesses are expensive and would be preferable to maintain locality by keeping the data in caches. Therefore, the likely optimal number of threads can be found when the dataset of each thread fits in each core's cache (I'm not going into the details of discussing whether it's L1/L2/L3 cache(s) of the system).

This holds true even when the number of threads exceeds the number of cores. For example assume there's 8 arbitrary unit (or AU) of work in the program which will be executed on a 4 core machine.

Case 1: run with four threads where each thread needs to complete 2AU. Each thread takes 10s to complete (with a lot of cache misses). With four cores the total amount of time will be 10s (10s * 4 threads / 4 cores).

Case 2: run with eight threads where each thread needs to complete 1AU. Each thread takes only 2s (instead of 5s because of the reduced amount of cache misses). With four cores the total amount of time will be 4s (2s * 8 threads / 4 cores).

I've simplified the problem and ignored overheads mentioned in other answers (e.g., context switches) but hope you get the point that it might be beneficial to have more number of threads than the available number of cores, depending on the data size you're dealing with.

PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused

For me was php version from mac instead of MAMP, PATH variable on .bash_profile was wrong. I just prepend the MAMP PHP bin folder to the $PATH env variable. For me was:

/Applications/mampstack-7.1.21-0/php/bin
  1. In terminal run vim ~/.bash_profile to open ~/.bash_profile

  2. Type i to be able to edit the file, add the bin directory as PATH variable on the top to the file:

    export PATH="/Applications/mampstack-7.1.21-0/php/bin/:$PATH"

  3. Hit ESC, Type :wq, and hit Enter

  4. In Terminal run source ~/.bash_profile
  5. In Terminal type which php, output should be the path to MAMP PHP install.

Alter column in SQL Server

I think you want this syntax:

ALTER TABLE tb_TableName  
add constraint cnt_Record_Status Default '' for Record_Status

Based on some of your comments, I am going to guess that you might already have null values in your table which is causing the alter of the column to not null to fail. If that is the case, then you should run an UPDATE first. Your script will be:

update tb_TableName
set Record_Status  = ''
where Record_Status is null

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL

ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status

See SQL Fiddle with demo

How to write connection string in web.config file and read from it?

Try this After open web.config file in application and add sample db connection in connectionStrings section like this

<connectionStrings>
<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient"/>
</connectionStrings >

Convert DataTable to IEnumerable<T>

Nothing wrong with that implementation. You might give the yield keyword a shot, see how you like it:

private IEnumerable<TankReading> ConvertToTankReadings(DataTable dataTable)
    {
        foreach (DataRow row in dataTable.Rows)
        {
            yield return new TankReading
                                  {
                                      TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),
                                      TankID = Convert.ToInt32(row["TankID"]),
                                      ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),
                                      ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),
                                      ReadingInches = Convert.ToInt32(row["ReadingInches"]),
                                      MaterialNumber = row["MaterialNumber"].ToString(),
                                      EnteredBy = row["EnteredBy"].ToString(),
                                      ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),
                                      MaterialID = Convert.ToInt32(row["MaterialID"]),
                                      Submitted = Convert.ToBoolean(row["Submitted"]),
                                  };
        }

    }

Also the AsEnumerable isn't necessary, as List<T> is already an IEnumerable<T>

Change Circle color of radio button

I made it short way like this (Working on API pre 21 as well as post 21)

Your radio button in xml should look like this

  <RadioButton android:id="@+id/radioid"                    
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"                 
                android:button="@drawable/radiodraw" />

in radiodraw.xml

  <?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">    
      <item android:state_checked="false" >
          <shape  android:shape="oval" >
              <stroke android:width="1dp" android:color="#000"/>
              <size android:width="30dp" android:height="30dp"/>
              <solid android:color="@android:color/transparent"/>
          </shape>
      </item>
      <item android:state_checked="true">
          <layer-list>
              <item>
                  <shape android:shape="oval">
                      <stroke android:width="1dp" android:color="#000"/>
                      <size android:width="30dp" android:height="30dp"/>
                      <solid android:color="@android:color/transparent"/>
                  </shape>
              </item>
              <item android:top="5dp" android:bottom="5dp" android:left="5dp" android:right="5dp">
                  <shape android:shape="oval">
                      <solid android:width="1dp" android:color="#000"/>
                      <size android:width="10dp" android:height="10dp"/>
                  </shape>
              </item>
          </layer-list>
      </item>
  </selector>

have to add color transparent for drawing the unchecked status ;else it draw solid black oval.

Benefits of inline functions in C++?

Our computer science professor urged us to never use inline in a c++ program. When asked why, he kindly explained to us that modern compilers should detect when to use inline automatically.

So yes, the inline can be an optimization technique to be used wherever possible, but apparently this is something that is already done for you whenever it's possible to inline a function anyways.

JavaScript - get the first day of the week from current date

First Day of The Week

To get the date of the first day of the week from today, you can use something like so:

_x000D_
_x000D_
function getUpcomingSunday() {_x000D_
  const date = new Date();_x000D_
  const today = date.getDate();_x000D_
  const dayOfTheWeek = date.getDay();_x000D_
  const newDate = date.setDate(today - dayOfTheWeek + 7);_x000D_
  return new Date(newDate);_x000D_
}_x000D_
_x000D_
console.log(getUpcomingSunday());
_x000D_
_x000D_
_x000D_

Or to get the last day of the week from today:

_x000D_
_x000D_
function getLastSunday() {_x000D_
  const date = new Date();_x000D_
  const today = date.getDate();_x000D_
  const dayOfTheWeek = date.getDay();_x000D_
  const newDate = date.setDate(today - (dayOfTheWeek || 7));_x000D_
  return new Date(newDate);_x000D_
}_x000D_
_x000D_
console.log(getLastSunday());
_x000D_
_x000D_
_x000D_

* Depending on your time zone, the beginning of the week doesn't has to start on Sunday, it can start on Friday, Saturday, Monday or any other day your machine is set to. Those methods will account for that.

* You can also format it using toISOString method like so: getLastSunday().toISOString()

XML shape drawable not rendering desired color

In drawable I use this xml code to define the border and background:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="4dp" android:color="#D8FDFB" /> 
  <padding android:left="7dp" android:top="7dp" 
    android:right="7dp" android:bottom="7dp" /> 
  <corners android:radius="4dp" /> 
  <solid android:color="#f0600000"/> 
</shape> 

How to decompile to java files intellij idea

Try

https://github.com/fesh0r/fernflower

Download jar from

http://files.minecraftforge.net/maven/net/minecraftforge/fernflower/

Command :

java -jar fernflower.jar -hes=0 -hdc=0 C:\binary  C:\source

Place your jar file in folder C:\binary and source will be extracted and packed in a jar inside C:\source.

Enjoy!

Change the Right Margin of a View Programmatically?

EDIT: A more generic way of doing this that doesn't rely on the layout type (other than that it is a layout type which supports margins):

public static void setMargins (View v, int l, int t, int r, int b) {
    if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
        p.setMargins(l, t, r, b);
        v.requestLayout();
    }
}

You should check the docs for TextView. Basically, you'll want to get the TextView's LayoutParams object, and modify the margins, then set it back to the TextView. Assuming it's in a LinearLayout, try something like this:

TextView tv = (TextView)findViewById(R.id.my_text_view);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
tv.setLayoutParams(params);

I can't test it right now, so my casting may be off by a bit, but the LayoutParams are what need to be modified to change the margin.

NOTE

Don't forget that if your TextView is inside, for example, a RelativeLayout, one should use RelativeLayout.LayoutParams instead of LinearLayout.LayoutParams

Most efficient way to see if an ArrayList contains an object in Java

I would say the simplest solution would be to wrap the object and delegate the contains call to a collection of the wrapped class. This is similar to the comparator but doesn't force you to sort the resulting collection, you can simply use ArrayList.contains().

public class Widget {
        private String name;
        private String desc;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }
    }



    public abstract class EqualsHashcodeEnforcer<T> {

        protected T wrapped;

        public T getWrappedObject() {
            return wrapped;
        }

        @Override
        public boolean equals(Object obj) {
            return equalsDelegate(obj);
        }

        @Override
        public int hashCode() {
            return hashCodeDelegate();
        }

        protected abstract boolean equalsDelegate(Object obj);

        protected abstract int hashCodeDelegate();
    }


    public class WrappedWidget extends EqualsHashcodeEnforcer<Widget> {

        @Override
        protected boolean equalsDelegate(Object obj) {
            if (obj == null) {
                return false;
            }
            if (obj == getWrappedObject()) {
                return true;
            }
            if (obj.getClass() != getWrappedObject().getClass()) {
                return false;
            }
            Widget rhs = (Widget) obj;

            return new EqualsBuilder().append(getWrappedObject().getName(),
                    rhs.getName()).append(getWrappedObject().getDesc(),
                    rhs.getDesc()).isEquals();
        }

        @Override
        protected int hashCodeDelegate() {

            return new HashCodeBuilder(121, 991).append(
                    getWrappedObject().getName()).append(
                    getWrappedObject().getDesc()).toHashCode();
        }

    }

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

add condition only firefox in your custom css file.

/* only Firefox */
@-moz-document url-prefix() {
   .img-responsive, .thumbnail>img, .thumbnail a>img, .carousel-inner>.item>img, .carousel-inner>.item>a>img {
      width: 100%;
   }
}

How do I implement Toastr JS?

Add CDN Files of toastr.css and toastr.js

<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>

function toasterOptions() {
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "newestOnTop": false,
        "progressBar": true,
        "positionClass": "toast-top-center",
        "preventDuplicates": true,
        "onclick": null,
        "showDuration": "100",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "show",
        "hideMethod": "hide"
    };
};


toasterOptions();
toastr.error("Error Message from toastr");

What is the difference between persist() and merge() in JPA and Hibernate?

The most important difference is this:

  • In case of persist method, if the entity that is to be managed in the persistence context, already exists in persistence context, the new one is ignored. (NOTHING happened)

  • But in case of merge method, the entity that is already managed in persistence context will be replaced by the new entity (updated) and a copy of this updated entity will return back. (from now on any changes should be made on this returned entity if you want to reflect your changes in persistence context)

Open a selected file (image, pdf, ...) programmatically from my Android Application?

Try this one add this code to your manifest file

 <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

provide your path type path.xml

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

and add this code to your functionality

File file = new File(tempPathNameFileString);
Intent viewPdf = new Intent(Intent.ACTION_VIEW);
viewPdf.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
Uri URI = FileProvider.getUriForFile(ReportsActivity.this, ReportsActivity.this.getApplicationContext().getPackageName() + ".provider", file);
viewPdf.setDataAndType(URI, "application/pdf");
viewPdf.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
ReportsActivity.this.startActivity(viewPdf);

How to undo "git commit --amend" done instead of "git commit"

None of these answers with the use of HEAD@{1} worked out for me, so here's my solution:

git reflog

d0c9f22 HEAD@{0}: commit (amend): [Feature] - ABC Commit Description 
c296452 HEAD@{1}: commit: [Feature] - ABC Commit Description 

git reset --soft c296452

Your staging environment will now contain all of the changes that you accidentally merged with the c296452 commit.

How to simulate a mouse click using JavaScript?

(Modified version to make it work without prototype.js)

function simulate(element, eventName)
{
    var options = extend(defaultOptions, arguments[2] || {});
    var oEvent, eventType = null;

    for (var name in eventMatchers)
    {
        if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }

    if (!eventType)
        throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (document.createEvent)
    {
        oEvent = document.createEvent(eventType);
        if (eventType == 'HTMLEvents')
        {
            oEvent.initEvent(eventName, options.bubbles, options.cancelable);
        }
        else
        {
            oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
            options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
            options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
        }
        element.dispatchEvent(oEvent);
    }
    else
    {
        options.clientX = options.pointerX;
        options.clientY = options.pointerY;
        var evt = document.createEventObject();
        oEvent = extend(evt, options);
        element.fireEvent('on' + eventName, oEvent);
    }
    return element;
}

function extend(destination, source) {
    for (var property in source)
      destination[property] = source[property];
    return destination;
}

var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
}
var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
}

You can use it like this:

simulate(document.getElementById("btn"), "click");

Note that as a third parameter you can pass in 'options'. The options you don't specify are taken from the defaultOptions (see bottom of the script). So if you for example want to specify mouse coordinates you can do something like:

simulate(document.getElementById("btn"), "click", { pointerX: 123, pointerY: 321 })

You can use a similar approach to override other default options.

Credits should go to kangax. Here's the original source (prototype.js specific).

Difference between JSON.stringify and JSON.parse

JavaScript Object <-> JSON String


JSON.stringify() <-> JSON.parse()

JSON.stringify(obj) - Takes any serializable object and returns the JSON representation as a string.

JSON.stringify() -> Object To String.

JSON.parse(string) - Takes a well formed JSON string and returns the corresponding JavaScript object.

JSON.parse() -> String To Object.

Explanation: JSON.stringify(obj [, replacer [, space]]);

Replacer/Space - optional or takes integer value or you can call interger type return function.

function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}
  • Replacer Just Use for replace non finite no with null.
  • Space use for indenting Json String by space

SQLite error 'attempt to write a readonly database' during insert?

This can happen when the owner of the SQLite file itself is not the same as the user running the script. Similar errors can occur if the entire directory path (meaning each directory along the way) can't be written to.

Who owns the SQLite file? You?

Who is the script running as? Apache or Nobody?

How to use document.getElementByName and getElementByTag?

  • document.getElementById('frmMain').elements
    assumes the form has an ID and that the ID is unique as IDs should be. Although it also accesses a name attribute in IE, please add ID to the element if you want to use getElementById



A great alternative is


In all of the above, the .elements can be replaced by for example .querySelectorAll("[type=text]") to get all text elements

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

For SQL Server, CROSS JOIN and FULL OUTER JOIN are different. CROSS JOIN is simply Cartesian Product of two tables, irrespective of any filter criteria or any condition.

FULL OUTER JOIN gives unique result set of LEFT OUTER JOIN and RIGHT OUTER JOIN of two tables. It also needs ON clause to map two columns of tables.

Table 1 contains 10 rows and Table 2 contains 20 rows with 5 rows matching on specific columns.

Then CROSS JOIN will return 10*20=200 rows in result set.

FULL OUTER JOIN will return 25 rows in result set.

FULL OUTER JOIN (or any other JOIN) always returns result set with less than or equal to Cartesian Product number.

Number of rows returned by FULL OUTER JOIN equal to (No. of Rows by LEFT OUTER JOIN) + (No. of Rows by RIGHT OUTER JOIN) - (No. of Rows by INNER JOIN).

DisplayName attribute from Resources?

I got Gunders answer working with my App_GlobalResources by choosing the resources properties and switch "Custom Tool" to "PublicResXFileCodeGenerator" and build action to "Embedded Resource". Please observe Gunders comment below.

enter image description here

Works like a charm :)

jQuery OR Selector?

Finally I've found hack how to do it:

div:not(:not(.classA,.classB)) > span

(selects div with class classA OR classB with direct child span)

How to Use UTF-8 Collation in SQL Server database?

Looks like this will be finally supported in the SQL Server 2019! SQL Server 2019 - whats new?

From BOL:

UTF-8 support

Full support for the widely used UTF-8 character encoding as an import or export encoding, or as database-level or column-level collation for text data. UTF-8 is allowed in the CHAR and VARCHAR datatypes, and is enabled when creating or changing an object’s collation to a collation with the UTF8 suffix.

For example,LATIN1_GENERAL_100_CI_AS_SC to LATIN1_GENERAL_100_CI_AS_SC_UTF8. UTF-8 is only available to Windows collations that support supplementary characters, as introduced in SQL Server 2012. NCHAR and NVARCHAR allow UTF-16 encoding only, and remain unchanged.

This feature may provide significant storage savings, depending on the character set in use. For example, changing an existing column data type with ASCII strings from NCHAR(10) to CHAR(10) using an UTF-8 enabled collation, translates into nearly 50% reduction in storage requirements. This reduction is because NCHAR(10) requires 22 bytes for storage, whereas CHAR(10) requires 12 bytes for the same Unicode string.

2019-05-14 update:

Documentation seems to be updated now and explains our options staring in MSSQL 2019 in section "Collation and Unicode Support".

2019-07-24 update:

Article by Pedro Lopes - Senior Program Manager @ Microsoft about introducing UTF-8 support for Azure SQL Database

Cordova : Requirements check failed for JDK 1.8 or greater

if you have many version of JDK you can run

export JAVA_HOME="/usr/local/env/java/jdk1.8.0_131.jdk/Contents/Home/"

before cordova build, to use a specific version of jdk :)

Convert dictionary to list collection in C#

foreach (var item in dicNumber)
{
    listnumber.Add(item.Key);
}

Check if element found in array c++

Using Newton C++

bool exists_linear( INPUT_ITERATOR first, INPUT_ITERATOR last, const T& value )

bool exists_binary( INPUT_ITERATOR first, INPUT_ITERATOR last, const T& value )

the code will be something like this:

if ( newton::exists_linear(arr.begin(), arr.end(), value) )
   std::cout << "found" << std::endl;
else
   std::cout << "not found" << std::endl;

both exists_linear and exists_binary use std implementations. binary use std::binary_search, and linear use std::find, but return directly a bool, not an iterator.

Modify property value of the objects in list using Java 8 streams

If you wanna create new list, use Stream.map method:

List<Fruit> newList = fruits.stream()
    .map(f -> new Fruit(f.getId(), f.getName() + "s", f.getCountry()))
    .collect(Collectors.toList())

If you wanna modify current list, use Collection.forEach:

fruits.forEach(f -> f.setName(f.getName() + "s"))

How can I tell Moq to return a Task?

Now you can also use Talentsoft.Moq.SetupAsync package https://github.com/TalentSoft/Moq.SetupAsync

Which on the base on the answers found here and ideas proposed to Moq but still not yet implemented here: https://github.com/moq/moq4/issues/384, greatly simplify setup of async methods

Few examples found in previous responses done with SetupAsync extension:

mock.SetupAsync(arg=>arg.DoSomethingAsync());
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Callback(() => { <my code here> });
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Throws(new InvalidOperationException());

Passing capturing lambda as function pointer

As it was mentioned by the others you can substitute Lambda function instead of function pointer. I am using this method in my C++ interface to F77 ODE solver RKSUITE.

//C interface to Fortran subroutine UT
extern "C"  void UT(void(*)(double*,double*,double*),double*,double*,double*,
double*,double*,double*,int*);

// C++ wrapper which calls extern "C" void UT routine
static  void   rk_ut(void(*)(double*,double*,double*),double*,double*,double*,
double*,double*,double*,int*);

//  Call of rk_ut with lambda passed instead of function pointer to derivative
//  routine
mathlib::RungeKuttaSolver::rk_ut([](double* T,double* Y,double* YP)->void{YP[0]=Y[1]; YP[1]= -Y[0];}, TWANT,T,Y,YP,YMAX,WORK,UFLAG);

Select SQL results grouped by weeks

I think this should do it..

Select 
ProductName,
WeekNumber,
sum(sale)
from
(
    SELECT 
    ProductName,
    DATEDIFF(week, '2011-05-30', date) AS WeekNumber,
    sale
    FROM table
)
GROUP BY
ProductName,
WeekNumber

Editing the date formatting of x-axis tick labels in matplotlib

While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.

So for everyone in need here is a full working example:

from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)

myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)

## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()

C# - Making a Process.Start wait until the process has start-up

public static class WinApi
{

    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    public static class Windows
    {
        public const int NORMAL = 1;
        public const int HIDE = 0;
        public const int RESTORE = 9;
        public const int SHOW = 5;
        public const int MAXIMIXED = 3;
    }

}

App

String process_name = "notepad"
Process process;
process = Process.Start( process_name );

while (!WinApi.ShowWindow(process.MainWindowHandle, WinApi.Windows.NORMAL))
{
    Thread.Sleep(100);
    process.Refresh();
}

// Done!
// Continue your code here ...

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

As suggested here you can also inject the HttpServletRequest as a method param, e.g.:

public MyResponseObject myApiMethod(HttpServletRequest request, ...) {
    ...
}

How to dynamically add and remove form fields in Angular 2

addAccordian(type, data) { console.log(type, data);

let form = this.form;

if (!form.controls[type]) {
  let ownerAccordian = new FormArray([]);
  const group = new FormGroup({});
  ownerAccordian.push(
    this.applicationService.createControlWithGroup(data, group)
  );
  form.controls[type] = ownerAccordian;
} else {
  const group = new FormGroup({});
  (<FormArray>form.get(type)).push(
    this.applicationService.createControlWithGroup(data, group)
  );
}
console.log(this.form);

}

Gradle: Could not determine java version from '11.0.2'

Updating gradle/wrapper/gradle-wrapper.properties with the following version fixed it for me:

distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip

Using print statements only to debug

First off, I will second the nomination of python's logging framework. Be a little careful about how you use it, however. Specifically: let the logging framework expand your variables, don't do it yourself. For instance, instead of:

logging.debug("datastructure: %r" % complex_dict_structure)

make sure you do:

logging.debug("datastructure: %r", complex_dict_structure)

because while they look similar, the first version incurs the repr() cost even if it's disabled. The second version avoid this. Similarly, if you roll your own, I'd suggest something like:

def debug_stdout(sfunc):
    print(sfunc())

debug = debug_stdout

called via:

debug(lambda: "datastructure: %r" % complex_dict_structure)

which will, again, avoid the overhead if you disable it by doing:

def debug_noop(*args, **kwargs):
    pass

debug = debug_noop

The overhead of computing those strings probably doesn't matter unless they're either 1) expensive to compute or 2) the debug statement is in the middle of, say, an n^3 loop or something. Not that I would know anything about that.

Unique Key constraints for multiple columns in Entity Framework

With Entity Framework 6.1, you can now do this:

[Index("IX_FirstAndSecond", 1, IsUnique = true)]
public int FirstColumn { get; set; }

[Index("IX_FirstAndSecond", 2, IsUnique = true)]
public int SecondColumn { get; set; }

The second parameter in the attribute is where you can specify the order of the columns in the index.
More information: MSDN

How to pass parameters to maven build using pom.xml?

We can Supply parameter in different way after some search I found some useful

<plugin>
  <artifactId>${release.artifactId}</artifactId>
  <version>${release.version}-${release.svm.version}</version>...

...

Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .

While Running build we need supply value for those parameter as follows.

RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74

Here I am supplying

release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74

It worked for me. Thanks

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

I would think that your first question is simply a matter of scope. The ServletContext is a much more broad scoped object (the whole servlet context) than a ServletRequest, which is simply a single request. You might look to the Servlet specification itself for more detailed information.

As to how, I am sorry but I will have to leave that for others to answer at this time.

How do you run JavaScript script through the Terminal?

You would need a JavaScript engine (such as Mozilla's Rhino) in order to evaluate the script - exactly as you do for Python, though the latter ships with the standard distribution.

If you have Rhino (or alternative) installed and on your path, then running JS can indeed be as simple as

> rhino filename.js

It's worth noting though that while JavaScript is simply a language in its own right, a lot of particular scripts assume that they'll be executing in a browser-like environment - and so try to access global variables such as location.href, and create output by appending DOM objects rather than calling print.

If you've got hold of a script which was written for a web page, you may need to wrap or modify it somewhat to allow it to accept arguments from stdin and write to stdout. (I believe Rhino has a mode to emulate standard browser global vars which helps a lot, though I can't find the docs for this now.)

len() of a numpy array in python

What is the len of the equivalent nested list?

len([[2,3,1,0], [2,3,1,0], [3,2,1,1]])

With the more general concept of shape, numpy developers choose to implement __len__ as the first dimension. Python maps len(obj) onto obj.__len__.

X.shape returns a tuple, which does have a len - which is the number of dimensions, X.ndim. X.shape[i] selects the ith dimension (a straight forward application of tuple indexing).

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

You better install Ruby 2.2.5 for compatibility. The Ruby version in your local machine is different from the one declared in Gemfile.

If you're using rvm:

rvm install 2.2.5
rvm use 2.2.5

else if you're using rbenv:

rbenv install 2.2.5
rbenv local 2.2.5

else if you can not change ruby version by rbenv, read here

How to sum up an array of integers in C#

In one of my apps I used :

public class ClassBlock
{
    public int[] p;
    public int Sum
    {
        get { int s = 0;  Array.ForEach(p, delegate (int i) { s += i; }); return s; }
    }
}

HTML text-overflow ellipsis detection

The e.offsetWidth < e.scrollWidth solution is not always working.

And if you want to use pure JavaScript, I recommend to use this:

(typescript)

public isEllipsisActive(element: HTMLElement): boolean {
    element.style.overflow = 'initial';
    const noEllipsisWidth = element.offsetWidth;
    element.style.overflow = 'hidden';
    const ellipsisWidth = element.offsetWidth;

    if (ellipsisWidth < noEllipsisWidth) {
      return true;
    } else {
      return false;
    }
}

how to loop through rows columns in excel VBA Macro

Here is my sugestion:

Dim i As integer, j as integer

With Worksheets("TimeOut")
    i = 26
    Do Until .Cells(8, i).Value = ""
        For j = 9 to 100 ' I do not know how many rows you will need it.'
            .Cells(j, i).Formula = "YourVolFormulaHere"
            .Cells(j, i + 1).Formula = "YourCapFormulaHere"
        Next j

        i = i + 2
    Loop
 End With

What is the iPhone 4 user-agent?

You can use:

http://whatsmyuseragent.com/

To find your user agent (Google: "What is my user agent" gives this answer)

How can I rename a project folder from within Visual Studio?

Man, have I struggled with this. Unfortunately there isn't a one click solution in Visual Studio, but if you're running Visual Studio 2012 and your project is under source control with Team Foundation Server, here is how I got it to work, while keeping the source history:

(Make sure you read @mjv's comment below, as he notes that you can skip step 5-10)

  1. Make sure you have checked in all changes, so you have no pending changes.
  2. Remove the project from the solution, by right clicking and selecting Remove.
  3. Now, in Windows Explorer, rename the project folder.
  4. Go back to Visual Studio, and in Solution Explorer, right click the solution and choose Add -> Existing project. Select the project file for the project you removed in step 2, which should be located in the renamed folder.
  5. Now the project is back in the solution, but the project doesn't seem to be added to source control. To fix that, open Source Control Explorer.
  6. Find the project folder in Source Control Explorer, that corresponds with the project folder on your disk, that you renamed in step 3.
  7. Rename the folder in Source Control Explorer, so it has the same name as the project folder on disk.
  8. Now take a look at your pending changes. You should have changes to the solution file and a rename operation on the project folder.
  9. Do a rebuild and make sure everything compiles correctly. If you had inter-project references to the project you renamed, you need to add them again to the individual projects that referenced it.
  10. You should be all set now. Go and check everything in.

The above guide worked for me. If it doesn't work for you, try and delete your local solution completely, and remove the folder mapping in your workspace. Restart Visual Studio just in case. Make sure you actually deleted the whole solution from your computer. Now readd the solution mapping to your workspace and get the latest version. Now try the above steps. The same applies if something goes wrong while following the above steps. Just delete your solution locally and get the latest source, and you'll have a clean slate to work with.

If you're still having problems, make sure that you haven't changed anything manually in the solution file, or trying other 'tricks' before trying the above steps. If you have changed something and checked it in, you might want to consider doing a rollback to the point just before you started messing with the renaming of the project.

Of course, you'd also want to rename the project itself, in Solution Explorer. You can do this before the steps above, but in that case, make sure you check in that change before applying the steps above. You can also do it afterwards, but make sure you follow all the steps above first, and check in your changes before trying to rename the project name in Solution Explorer. I don't recommend trying to mix the above steps with a rename of the project name in Solution Explorer. It might work though, but I would recommand doing it in 2 separate changesets.

How to track untracked content?

This worked out just fine for me:

git update-index --skip-worktree

If it doesn't work with the pathname, try the filename. Let me know if this worked for you too.

Bye!

Difference between "process.stdout.write" and "console.log" in node.js?

The Simple Difference is: console.log() methods automatically append new line character. It means if we are looping through and printing the result, each result get printed in new line.

process.stdout.write() methods don't append new line character. useful for printing patterns.

Run a php app using tomcat?

tomcat is designed as JSP servlet container. Apache is designed PHP web server. Use apache as web server, responding for PHP request, and direct JSP servlet request to tomcat container. should be better implementation.

What port is used by Java RMI connection?

You typically set the port at the server using the rmiregistry command. You can set the port on the command line, or it will default to 1099

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

This: "Disconnected: No supported authentication methods available (server sent: publickey)" happened to me after I turned on Microsoft One Drive backup and sync for my files including the directory where I saved my ssh key. In my case the solution is simple: just go to Putty => SSH => Auth and just (re)browse again to where my same key is located and saved, then it worked. It looks backup and sync software such as Microsoft One Drive (and may be the same with Google Drive), affect the way Putty sees and identifies directories if the key directory is specified and then later some time installing or turning on backup and sync including that directory.

Python - OpenCV - imread - Displaying Image

In openCV whenever you try to display an oversized image or image bigger than your display resolution you get the cropped display. It's a default behaviour.
In order to view the image in the window of your choice openCV encourages to use named window. Please refer to namedWindow documentation

The function namedWindow creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names.

cv.namedWindow(name, flags=CV_WINDOW_AUTOSIZE) where each window is related to image container by the name arg, make sure to use same name

eg:

import cv2
frame = cv2.imread('1.jpg')
cv2.namedWindow("Display 1")
cv2.resizeWindow("Display 1", 300, 300)
cv2.imshow("Display 1", frame)

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

On Android >=6.0, We have to request permission runtime.

Step1: add in AndroidManifest.xml file

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

Step2: Request permission.

int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);

if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
} else {
    //TODO
}

Step3: Handle callback when you request permission.

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_READ_PHONE_STATE:
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                //TODO
            }
            break;

        default:
            break;
    }
}

Edit: Read official guide here Requesting Permissions at Run Time

HashMap - getting First Key value

Java 8 way of doing,

String firstKey = map.keySet().stream().findFirst().get();

How to copy a file to multiple directories using the gnu cp command

To use copying with xargs to directories using wildcards on Mac OS, the only solution that worked for me with spaces in the directory name is:

find ./fs*/* -type d -print0 | xargs -0 -n 1 cp test 

Where test is the file to copy
And ./fs*/* the directories to copy to

The problem is that xargs sees spaces as a new argument, the solutions to change the delimiter character using -d or -E is unfortunately not properly working on Mac OS.

Convert double to Int, rounded down

If you explicitly cast double to int, the decimal part will be truncated. For example:

int x = (int) 4.97542;   //gives 4 only
int x = (int) 4.23544;   //gives 4 only

Moreover, you may also use Math.floor() method to round values in case you want double value in return.

Java Array, Finding Duplicates

public static ArrayList<Integer> duplicate(final int[] zipcodelist) {

    HashSet<Integer> hs = new HashSet<>();
    ArrayList<Integer> al = new ArrayList<>();
    for(int element: zipcodelist) {
        if(hs.add(element)==false) {
            al.add(element);
        }   
    }
    return al;
}

Search all of Git history for a string?

git rev-list --all | (
    while read revision; do
        git grep -F 'password' $revision
    done
)

Percentage width in a RelativeLayout

Just put your two textviews host and port in an independant linearlayout horizontal and use android:layout_weight to make the percentage

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

A NoClassDefFoundError (NCDFE) happens when your code runs "new Y()" and it can't find the Y class.

It may simply be that Y is missing from your class loader like the other comments suggest, but it could be that the Y class isn't signed or has an invalid signature, or that Y is loaded by a different classloader not visible to your code, or even that Y depends on Z which couldn't be loaded for any of the above reasons.

If this happens, then the JVM will remember the result of loading X (NCDFE) and it will simply throw a new NCDFE every time you ask for Y without telling you why:

class a {
  static class b {}
  public static void main(String args[]) {
    System.out.println("First attempt new b():");
    try {new b(); } catch(Throwable t) {t.printStackTrace();}
    System.out.println("\nSecond attempt new b():");
    try {new b(); } catch(Throwable t) {t.printStackTrace();}
  }
}

save this as a.java somewhere

The code simply tries to instantiate a new "b" class twice, other than that, it doesn't have any bugs, and it doesn't do anything.

Compile the code with javac a.java, Then run a by invoking java -cp . a -- it should just print out two lines of text, and it should run fine without errors.

Then delete the "a$b.class" file (or fill it with garbage, or copy a.class over it) to simulate the missing or corrupted class. Here's what happens:

First attempt new b():
java.lang.NoClassDefFoundError: a$b
    at a.main(a.java:5)
Caused by: java.lang.ClassNotFoundException: a$b
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
    ... 1 more

Second attempt new b():
java.lang.NoClassDefFoundError: a$b
    at a.main(a.java:7)

The first invocation results in a ClassNotFoundException (thrown by the class loader when it can't find the class), which must be wrapped in an unchecked NoClassDefFoundError, since the code in question (new b()) should just work.

The second attempt will of course fail too, but as you can see the wrapped exception is no more, because the ClassLoader seems to remember failed class loaders. You see only the NCDFE with absolutely no clue as to what really happened.

So if you ever see a NCDFE with no root cause, you need to see if you can track back to the very first time the class was loaded to find the cause of the error.

Fatal error: Call to undefined function sqlsrv_connect()

First check that the extension is properly loaded in phpinfo(); (something like sqlsrv should appear). If not, the extension isn't properly loaded. You also need to restart apache after installing an extension.

How to hide a button programmatically?

public void OnClick(View.v)
Button b1 = (Button) findViewById(R.id.playButton);
b1.setVisiblity(View.INVISIBLE);

FileNotFoundException while getting the InputStream object from HttpURLConnection

To anyone with this problem in the future, the reason is because the status code was a 404 (or in my case was a 500). It appears the InpuStream function will throw an error when the status code is not 200.

In my case I control my own server and was returning a 500 status code to indicate an error occurred. Despite me also sending a body with a string message detailing the error, the inputstream threw an error regardless of the body being completely readable.

If you control your server I suppose this can be handled by sending yourself a 200 status code and then handling whatever the string error response was.

How to write UPDATE SQL with Table alias in SQL Server 2008?

The syntax for using an alias in an update statement on SQL Server is as follows:

UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;

The alias should not be necessary here though.

What's the best UI for entering date of birth?

I'm troubled by the preponderance of solutioning instead of designing. The OP said, "I want to know what is the most usable and problem free solution, so user wont be confused at all." So whether it's jQuery or JavaScript or C# or FORTRAN, the design is important--and it's the UX design, not the UI design that matters here. (Another plea to avoid the incorrect and illogical construct "UX/UI").

Use text input. Use three separate boxes labeled Day, Month, and Year (or Month, Day, and Year). Let users type the dates. Mixing text and lists in the same interaction is a Bad Thing (don't use text input for year but date picker or lists for month and day, for example).

Use a single text field that uses in-field format hints, for example, [ day / month / year ] Don't require formats too rigidly. If a user type JUN in the place where you expect a month, then use June on the back end. If a user types 6 in the place where you expect a month, then use June on the back end. If a user types 06 in the place where you expect a month, then use June on the back end.

Use Occam's Razor as a guide (in effect, most of the time the data will be accurate enough). Reduce cognitive friction (don't make users think).

How to hide the border for specified rows of a table?

You can simply add these lines of codes here to hide a row,

Either you can write border:0 or border-style:hidden; border: none or it will happen the same thing

_x000D_
_x000D_
<style type="text/css">_x000D_
              table, th, td {_x000D_
               border: 1px solid;_x000D_
              }_x000D_
              _x000D_
              tr.hide_all > td, td.hide_all{_x000D_
                 border: 0;_x000D_
                _x000D_
              }_x000D_
          }_x000D_
        </style>_x000D_
    <table>_x000D_
      <tr>_x000D_
        <th>Firstname</th>_x000D_
        <th>Lastname</th>_x000D_
        <th>Savings</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Peter</td>_x000D_
        <td>Griffin</td>_x000D_
        <td>$100</td>_x000D_
      </tr>_x000D_
      <tr class= hide_all>_x000D_
        <td>Lois</td>_x000D_
        <td>Griffin</td>_x000D_
        <td>$150</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Joe</td>_x000D_
        <td>Swanson</td>_x000D_
        <td>$300</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Cleveland</td>_x000D_
        <td>Brown</td>_x000D_
        <td>$250</td>_x000D_
      </tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

running these lines of codes can solve the problem easily

Remove Item from ArrayList

In this specific case, you should remove the elements in descending order. First index 5, then 3, then 1. This will remove the elements from the list without undesirable side effects.

for (int j = i.length-1; j >= 0; j--) {
    list.remove(i[j]);
}

NodeJS/express: Cache and 304 status code

As you said, Safari sends Cache-Control: max-age=0 on reload. Express (or more specifically, Express's dependency, node-fresh) considers the cache stale when Cache-Control: no-cache headers are received, but it doesn't do the same for Cache-Control: max-age=0. From what I can tell, it probably should. But I'm not an expert on caching.

The fix is to change (what is currently) line 37 of node-fresh/index.js from

if (cc && cc.indexOf('no-cache') !== -1) return false;  

to

if (cc && (cc.indexOf('no-cache') !== -1 ||
  cc.indexOf('max-age=0') !== -1)) return false;

I forked node-fresh and express to include this fix in my project's package.json via npm, you could do the same. Here are my forks, for example:

https://github.com/stratusdata/node-fresh https://github.com/stratusdata/express#safari-reload-fix

The safari-reload-fix branch is based on the 3.4.7 tag.

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

Use X-Requested-With: XMLHttpRequest with your request header. So the response header will not contain WWW-Authenticate:Basic.

beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', ("Basic "
                        .concat(btoa(key))));
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                },

Selenium WebDriver findElement(By.xpath()) not working for me

You haven't specified what kind of html element you are trying to do an absolute xpath search on. In your case, it's the input element.

Try this:

element = findElement(By.xpath("//input[@class='t-TextBox' and @type='email' and @test-    
id='test-username']");

How to use Google fonts in React.js?

If you are using Create React App environment simply add @import rule to index.css as such:

@import url('https://fonts.googleapis.com/css?family=Anton');

Import index.css in your main React app:

import './index.css'

React gives you a choice of Inline styling, CSS Modules or Styled Components in order to apply CSS:

font-family: 'Anton', sans-serif;

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

How to force reloading a page when using browser back button?

Just use jquery :

jQuery( document ).ready(function( $ ) {

   //Use this inside your document ready jQuery 
   $(window).on('popstate', function() {
      location.reload(true);
   });

});

The above will work 100% when back or forward button has been clicked using ajax as well.

if it doesn't, there must be a misconfiguration in a different part of the script.

For example it might not reload if something like one of the example in the previous post is used window.history.pushState('', null, './');

so when you do use history.pushState(); make sure you use it properly.

Suggestion in most cases you will just need:

history.pushState(url, '', url); 

No window.history... and make sure url is defined.

Hope that helps..

How to create JSON string in C#

I've found that you don't need the serializer at all. If you return the object as a List. Let me use an example.

In our asmx we get the data using the variable we passed along

// return data
[WebMethod(CacheDuration = 180)]
public List<latlon> GetData(int id) 
{
    var data = from p in db.property 
               where p.id == id 
               select new latlon
               {
                   lat = p.lat,
                   lon = p.lon

               };
    return data.ToList();
}

public class latlon
{
    public string lat { get; set; }
    public string lon { get; set; }
}

Then using jquery we access the service, passing along that variable.

// get latlon
function getlatlon(propertyid) {
var mydata;

$.ajax({
    url: "getData.asmx/GetLatLon",
    type: "POST",
    data: "{'id': '" + propertyid + "'}",
    async: false,
    contentType: "application/json;",
    dataType: "json",
    success: function (data, textStatus, jqXHR) { //
        mydata = data;
    },
    error: function (xmlHttpRequest, textStatus, errorThrown) {
        console.log(xmlHttpRequest.responseText);
        console.log(textStatus);
        console.log(errorThrown);
    }
});
return mydata;
}

// call the function with your data
latlondata = getlatlon(id);

And we get our response.

{"d":[{"__type":"MapData+latlon","lat":"40.7031420","lon":"-80.6047970}]}

Editor does not contain a main type in Eclipse

Right click your project > Run As > Run Configuration... > Java Application (in left side panel) - double click on it. That will create new configuration. click on search button under Main Class section and select your main class from it.

Javascript Regexp dynamic generation from variables?

You have to forgo the regex literal and use the object constructor, where you can pass the regex as a string.

var regex = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regex);

String vs. StringBuilder

StringBuilder is better for building up a string from many non-constant values.

If you're building up a string from a lot of constant values, such as multiple lines of values in an HTML or XML document or other chunks of text, you can get away with just appending to the same string, because almost all compilers do "constant folding", a process of reducing the parse tree when you have a bunch of constant manipulation (it's also used when you write something like int minutesPerYear = 24 * 365 * 60). And for simple cases with non-constant values appended to each other, the .NET compiler will reduce your code to something similar to what StringBuilder does.

But when your append can't be reduced to something simpler by the compiler, you'll want a StringBuilder. As fizch points out, that's more likely to happen inside of a loop.

Sorting Directory.GetFiles()

If you're interested in properties of the files such as CreationTime, then it would make more sense to use System.IO.DirectoryInfo.GetFileSystemInfos(). You can then sort these using one of the extension methods in System.Linq, e.g.:

DirectoryInfo di = new DirectoryInfo("C:\\");
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.OrderBy(f => f.CreationTime);

Edit - sorry, I didn't notice the .NET2.0 tag so ignore the LINQ sorting. The suggestion to use System.IO.DirectoryInfo.GetFileSystemInfos() still holds though.

How to "crop" a rectangular image into a square with CSS?

object-fit: cover will do exactly what you need.

But it might not work on IE/Edge. Follow as shown below to fix it with just CSS to work on all browsers.

The approach I took was to position the image inside the container with absolute and then place it right at the centre using the combination:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Once it is in the centre, I give to the image,

// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;

// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;

This makes the image get the effect of Object-fit:cover.


Here is a demonstration of the above logic.

https://jsfiddle.net/furqan_694/s3xLe1gp/

This logic works in all browsers.


Original Image
Original Image

Vertically Cropped
Vertically Cropped Image

Horizontally Cropped
Horizontally Cropped Image


How can I shrink the drawable on a button?

You can call setBounds on the "compound" drawables to modify the size of the image.

Try this code to autosize the drawable of your button:

DroidUtils.scaleButtonDrawables((Button) findViewById(R.id.ButtonTest), 1.0);

defined by this function:

public final class DroidUtils {

    /** scale the Drawables of a button to "fit"
     *  For left and right drawables: height is scaled 
     *  eg. with fitFactor 1 the image has max. the height of the button.
     *  For top and bottom drawables: width is scaled: 
     *  With fitFactor 0.9 the image has max. 90% of the width of the button 
     *  */
    public static void scaleButtonDrawables(Button btn, double fitFactor) {
        Drawable[] drawables = btn.getCompoundDrawables();

        for (int i = 0; i < drawables.length; i++) {
            if (drawables[i] != null) {
                int imgWidth = drawables[i].getIntrinsicWidth();
                int imgHeight = drawables[i].getIntrinsicHeight();
                if ((imgHeight > 0) && (imgWidth > 0)) {    //might be -1
                    float scale;
                    if ((i == 0) || (i == 2)) { //left or right -> scale height
                        scale = (float) (btn.getHeight() * fitFactor) / imgHeight;
                    } else { //top or bottom -> scale width
                        scale = (float) (btn.getWidth() * fitFactor) / imgWidth;                    
                    }
                    if (scale < 1.0) {
                        Rect rect = drawables[i].getBounds();
                        int newWidth = (int)(imgWidth * scale);
                        int newHeight = (int)(imgHeight * scale);
                        rect.left = rect.left + (int)(0.5 * (imgWidth - newWidth)); 
                        rect.top = rect.top + (int)(0.5 * (imgHeight - newHeight));
                        rect.right = rect.left + newWidth;
                        rect.bottom = rect.top + newHeight;
                        drawables[i].setBounds(rect);
                    }
                }
            }
        }
    }
}

Be aware, that this may not be called in onCreate() of an activity, because button height and width are not (yet) available there. Call this in on onWindowFocusChanged() or use this solution to call the function.

Edited:

The first incarnation of this function did not work correctly. It used userSeven7s code to scale the image, but returning ScaleDrawable.getDrawable() does not seem to work (neither does returning ScaleDrawable) for me.

The modified code uses setBounds to provide the bounds for the image. Android fits the image into these bounds.

How do I test if a string is empty in Objective-C?

Just use one of the if else conditions as shown below:

Method 1:

if ([yourString isEqualToString:@""]) {
        // yourString is empty.
    } else {
        // yourString has some text on it.
    }

Method 2:

if ([yourString length] == 0) {
    // Empty yourString
} else {
    // yourString is not empty
}

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Some version working

<div class="hidden-xs">Only Mobile hidden</div>
<div class="visible-xs">Only Mobile visible</div>

jquery find class and get the value

var myVar = $("#start").find('myClass').val();

needs to be

var myVar = $("#start").find('.myClass').val();

Remember the CSS selector rules require "." if selecting by class name. The absence of "." is interpreted to mean searching for <myclass></myclass>.

Open file by its full path in C++

Normally one uses the backslash character as the path separator in Windows. So:

ifstream file;
file.open("C:\\Demo.txt", ios::in);

Keep in mind that when written in C++ source code, you must use the double backslash because the backslash character itself means something special inside double quoted strings. So the above refers to the file C:\Demo.txt.

Member '<method>' cannot be accessed with an instance reference

In C#, unlike VB.NET and Java, you can't access static members with instance syntax. You should do:

MyClass.MyItem.Property1

to refer to that property or remove the static modifier from Property1 (which is what you probably want to do). For a conceptual idea about what static is, see my other answer.

omp parallel vs. omp parallel for

There are obviously plenty of answers, but this one answers it very nicely (with source)

#pragma omp for only delegates portions of the loop for different threads in the current team. A team is the group of threads executing the program. At program start, the team consists only of a single member: the master thread that runs the program.

To create a new team of threads, you need to specify the parallel keyword. It can be specified in the surrounding context:

#pragma omp parallel
{
   #pragma omp for
   for(int n = 0; n < 10; ++n)
   printf(" %d", n);
}

and:

What are: parallel, for and a team

The difference between parallel, parallel for and for is as follows:

A team is the group of threads that execute currently. At the program beginning, the team consists of a single thread. A parallel construct splits the current thread into a new team of threads for the duration of the next block/statement, after which the team merges back into one. for divides the work of the for-loop among the threads of the current team.

It does not create threads, it only divides the work amongst the threads of the currently executing team. parallel for is a shorthand for two commands at once: parallel and for. Parallel creates a new team, and for splits that team to handle different portions of the loop. If your program never contains a parallel construct, there is never more than one thread; the master thread that starts the program and runs it, as in non-threading programs.

https://bisqwit.iki.fi/story/howto/openmp/

Python convert object to float

  • You can use pandas.Series.astype
  • You can do something like this :

    weather["Temp"] = weather.Temp.astype(float)
    
  • You can also use pd.to_numeric that will convert the column from object to float

  • For details on how to use it checkout this link :http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.to_numeric.html
  • Example :

    s = pd.Series(['apple', '1.0', '2', -3])
    print(pd.to_numeric(s, errors='ignore'))
    print("=========================")
    print(pd.to_numeric(s, errors='coerce'))
    
  • Output:

    0    apple
    1      1.0
    2        2
    3       -3
    =========================
    dtype: object
    0    NaN
    1    1.0
    2    2.0
    3   -3.0
    dtype: float64
    
  • In your case you can do something like this:

    weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
    
  • Other option is to use convert_objects
  • Example is as follows

    >> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
    
    0     1
    1     2
    2     3
    3     4
    4   NaN
    dtype: float64
    
  • You can use this as follows:

    weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
    
  • I have showed you examples because if any of your column won't have a number then it will be converted to NaN... so be careful while using it.

Swift double to string

I would prefer NSNumber and NumberFormatter approach (where need), also u can use extension to avoid bloating code

extension Double {

   var toString: String {
      return NSNumber(value: self).stringValue
   }

}

U can also need reverse approach

extension String {

    var toDouble: Double {
        return Double(self) ?? .nan
    }

}

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

Actually python will reclaim the memory which is not in use anymore.This is called garbage collection which is automatic process in python. But still if you want to do it then you can delete it by del variable_name. You can also do it by assigning the variable to None

a = 10
print a 

del a       
print a      ## throws an error here because it's been deleted already.

The only way to truly reclaim memory from unreferenced Python objects is via the garbage collector. The del keyword simply unbinds a name from an object, but the object still needs to be garbage collected. You can force garbage collector to run using the gc module, but this is almost certainly a premature optimization but it has its own risks. Using del has no real effect, since those names would have been deleted as they went out of scope anyway.

ImportError: Cannot import name X

While you should definitely avoid circular dependencies, you can defer imports in python.

for example:

import SomeModule

def someFunction(arg):
    from some.dependency import DependentClass

this ( at least in some instances ) will circumvent the error.

How to declare empty list and then add string in scala?

Maybe you can use ListBuffers in scala to create empty list and add strings later because ListBuffers are mutable. Also all the List functions are available for the ListBuffers in scala.

import scala.collection.mutable.ListBuffer 

val dm = ListBuffer[String]()
dm: scala.collection.mutable.ListBuffer[String] = ListBuffer()
dm += "text1"
dm += "text2"
dm = ListBuffer(text1, text2)

if you want you can convert this to a list by using .toList

How do I check if a Key is pressed on C++

There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.

Solution for linux and other posix compliant systems:

Here, for Morgan Mattews's code provide kbhit() functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.

Solution for windows:

For windows, Microsoft offers _kbhit()

Reversing a string in C

You can put your (len/2) test in the for loop:

for(i = 0,k=len-1 ; i < (len/2); i++,k--)
{
        temp = str[k];
        str[k] = str[i];
        str[i] = temp;

}

Converting ArrayList to Array in java

package com.v4common.shared.beans.audittrail;

import java.util.ArrayList;
import java.util.List;

public class test1 {
    public static void main(String arg[]){
        List<String> list = new ArrayList<String>();
        list.add("abcd#xyz");
        list.add("mnop#qrs");

        Object[] s = list.toArray();
        String[] s1= new String[list.size()];
        String[] s2= new String[list.size()];

        for(int i=0;i<s.length;i++){
            if(s[i] instanceof String){
                String temp = (String)s[i];
                if(temp.contains("#")){
                    String[] tempString = temp.split("#");
                    for(int j=0;j<tempString.length;j++) {
                        s1[i] = tempString[0];
                        s2[i] = tempString[1];
                    }

                }
            }   
        }
        System.out.println(s1.length);
        System.out.println(s2.length);
        System.out.println(s1[0]);
        System.out.println(s1[1]);
    }
}

How do you debug React Native?

if you want to debug using android device on Windows just open a command prompt then type ( make sure your adb working properly)

adb shell input keyevent 82

it will prompt a screen like the image enter image description here

then select

debug JS Remotely

it will automatically open a new window.then open inspect element or press F12 for console.

httpd-xampp.conf: How to allow access to an external IP besides localhost?

<Directory "E:/xampp/phpMyAdmin/">
AllowOverride AuthConfig Limit
Order allow,deny
Allow from all
Require all granted

Writing Python lists to columns in csv

import csv
dic = {firstcol,secondcol} #dictionary
csv = open('result.csv', "w") 
for key in dic.keys():
    row ="\n"+ str(key) + "," + str(dic[key]) 
    csv.write(row)

How do I create an .exe for a Java program?

If you really want an exe Excelsior JET is a professional level product that compiles to native code:

http://www.excelsior-usa.com/jet.html

You can also look at JSMooth:

http://jsmooth.sourceforge.net/

And if your application is compatible with its compatible with AWT/Apache classpath then GCJ compiles to native exe.

Difference between "module.exports" and "exports" in the CommonJs Module System

module is a plain JavaScript object with an exports property. exports is a plain JavaScript variable that happens to be set to module.exports. At the end of your file, node.js will basically 'return' module.exports to the require function. A simplified way to view a JS file in Node could be this:

var module = { exports: {} };
var exports = module.exports;

// your code

return module.exports;

If you set a property on exports, like exports.a = 9;, that will set module.exports.a as well because objects are passed around as references in JavaScript, which means that if you set multiple variables to the same object, they are all the same object; so then exports and module.exports are the same object.
But if you set exports to something new, it will no longer be set to module.exports, so exports and module.exports are no longer the same object.

CSS fixed width in a span

In an ideal world you'd achieve this simply using the following css

<style type="text/css">

span {
  display: inline-block;
  width: 50px;
}

</style>

This works on all browsers apart from FF2 and below.

Firefox 2 and lower don't support this value. You can use -moz-inline-box, but be aware that it's not the same as inline-block, and it may not work as you expect in some situations.

Quote taken from quirksmode

Converting Epoch time into the datetime

If you have epoch in milliseconds a possible solution is convert to seconds:

import time
time.ctime(milliseconds/1000)

For more time functions: https://docs.python.org/3/library/time.html#functions

SQL Server after update trigger

Here is my example after a test

CREATE TRIGGER [dbo].UpdateTasadoresName 
ON [dbo].Tasadores  
FOR  UPDATE
AS 
      UPDATE Tasadores 
      SET NombreCompleto = RTRIM( Tasadores.Nombre + ' ' + isnull(Tasadores.ApellidoPaterno,'') + ' ' + isnull(Tasadores.ApellidoMaterno,'')    )  
      FROM Tasadores 
    INNER JOIN INSERTED i ON Tasadores.id = i.id

The inserted special table will have the information from the updated record.

Redirect stderr to stdout in C shell

As paxdiablo said you can use >& to redirect both stdout and stderr. However if you want them separated you can use the following:

(command > stdoutfile) >& stderrfile

...as indicated the above will redirect stdout to stdoutfile and stderr to stderrfile.

mysqli_select_db() expects parameter 1 to be mysqli, string given

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    die("Database selection failed: " . mysqli_error($connection));
}

You got the order of the arguments to mysqli_select_db() backwards. And mysqli_error() requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.

Note also that with mysqli you can specify the DB in mysqli_connect():

$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
  die("Database connection failed: " . mysqli_connect_error();
}

You must use mysqli_connect_error(), not mysqli_error(), to get the error from mysqli_connect(), since the latter requires you to supply a valid connection.

How do I use a custom deleter with a std::unique_ptr member?

It's possible to do this cleanly using a lambda in C++11 (tested in G++ 4.8.2).

Given this reusable typedef:

template<typename T>
using deleted_unique_ptr = std::unique_ptr<T,std::function<void(T*)>>;

You can write:

deleted_unique_ptr<Foo> foo(new Foo(), [](Foo* f) { customdeleter(f); });

For example, with a FILE*:

deleted_unique_ptr<FILE> file(
    fopen("file.txt", "r"),
    [](FILE* f) { fclose(f); });

With this you get the benefits of exception-safe cleanup using RAII, without needing try/catch noise.

This Activity already has an action bar supplied by the window decor

I got this error due to a custome attribute inside, removing it fixed the issue.

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
..
        <item name="searchBarBgColor">#383838</item>  --> remove this line
    </style>

HTML button to NOT submit form

Dave Markle is correct. From W3School's website:

Always specify the type attribute for the button. The default type for Internet Explorer is "button", while in other browsers (and in the W3C specification) it is "submit".

In other words, the browser you're using is following W3C's specification.

Make multiple-select to adjust its height to fit options without scroll bar

You can count option tag first, and then set the count for size attribute. For example, in PHP you can count the array and then use a foreach loop for the array.

<?php $count = count($array); ?>
<select size="<?php echo $count; ?>" style="height:100%;">
<?php foreach ($array as $item){ ?>
    <option value="valueItem">Name Item</option>
<?php } ?>
</select>

What's the PowerShell syntax for multiple values in a switch statement?

switch($someString.ToLower())
{
    "yes"   { $_ = "y" }
    "y"     { "You entered Yes." }
    default { "You entered No." }
}

You can arbitrarily branch, cascade, and merge cases in this fashion, as long as the target case is located below/after the case or cases where the $_ variable is respectively reassigned.


n.b. As cute as this behavior is, it seems to reveal that the PowerShell interpreter is not implementing switch/case as efficiently as one might hope or assume. For one, stepping with the ISE debugger suggests that instead of optimized lookup, hashing, or binary branching, each case is tested in turn, like so many if-else statements. (If so, consider putting your most common cases first.) Also, as shown in this answer, PowerShell continues testing cases after having satisfied one. And cruelly enough, there even happens to be a special optimized 'switch' opcode available in .NET CIL which, because of this behavior, PowerShell can't take advantage of.

Efficient iteration with index in Scala

How about this?

val a = Array("One", "Two", "Three")
a.foldLeft(0) ((i, x) => {println(i + ": " + x); i + 1;} )

Output:

0: One
1: Two
2: Three

UITableView example for Swift

For completeness sake, and for those that do not wish to use the Interface Builder, here's a way of creating the same table as in Suragch's answer entirely programatically - albeit with a different size and position.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {

    var tableView: UITableView = UITableView()
    let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    let cellReuseIdentifier = "cell"

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.frame = CGRectMake(0, 50, 320, 200)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

        self.view.addSubview(tableView)
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return animals.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!

        cell.textLabel?.text = animals[indexPath.row]

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }

}

Make sure you have remembered to import UIKit.

How to read a .properties file which contains keys that have a period character using Shell script

Since variable names in the BASH shell cannot contain a dot or space it is better to use an associative array in BASH like this:

#!/bin/bash

# declare an associative array
declare -A arr

# read file line by line and populate the array. Field separator is "="
while IFS='=' read -r k v; do
   arr["$k"]="$v"
done < app.properties

Testing:

Use declare -p to show the result:

  > declare -p arr  

        declare -A arr='([db.uat.passwd]="secret" [db.uat.user]="saple user" )'

python NameError: name 'file' is not defined

file is not defined in Python3, which you are using apparently. The package you're instaling is not suitable for Python 3, instead, you should install Python 2.7 and try again.

See: http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins

Double array initialization in Java

You can initialize an array by writing actual values it holds in curly braces on the right hand side like:

String[] strArr = { "one", "two", "three"};
int[] numArr = { 1, 2, 3};

In the same manner two-dimensional array or array-of-arrays holds an array as a value, so:

String strArrayOfArrays = { {"a", "b", "c"}, {"one", "two", "three"} };

Your example shows exactly that

double m[][] = {
    {0*0,1*0,2*0,3*0},
    {0*1,1*1,2*1,3*1},
    {0*2,1*2,2*2,3*2},
    {0*3,1*3,2*3,3*3}
};

But also the multiplication of number will also be performed and its the same as:

double m[][] = { {0, 0, 0, 0}, {0, 1, 2, 3}, {0, 2, 4, 6}, {0, 3, 6, 9} };

How to detect the end of loading of UITableView

I always use this very simple solution:

-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] == lastRow){
        //end of loading
        //for example [activityIndicator stopAnimating];
    }
}

How do I sleep for a millisecond in Perl?

Time::HiRes:

  use Time::HiRes;
  Time::HiRes::sleep(0.1); #.1 seconds
  Time::HiRes::usleep(1); # 1 microsecond.

http://perldoc.perl.org/Time/HiRes.html

How to execute cmd commands via Java

I found this in forums.oracle.com

Allows the reuse of a process to execute multiple commands in Windows: http://kr.forums.oracle.com/forums/thread.jspa?messageID=9250051

You need something like

   String[] command =
    {
        "cmd",
    };
    Process p = Runtime.getRuntime().exec(command);
    new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
    new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
    PrintWriter stdin = new PrintWriter(p.getOutputStream());
    stdin.println("dir c:\\ /A /Q");
    // write any other commands you want here
    stdin.close();
    int returnCode = p.waitFor();
    System.out.println("Return code = " + returnCode);

SyncPipe Class:

class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
      istrm_ = istrm;
      ostrm_ = ostrm;
  }
  public void run() {
      try
      {
          final byte[] buffer = new byte[1024];
          for (int length = 0; (length = istrm_.read(buffer)) != -1; )
          {
              ostrm_.write(buffer, 0, length);
          }
      }
      catch (Exception e)
      {
          e.printStackTrace();
      }
  }
  private final OutputStream ostrm_;
  private final InputStream istrm_;
}

what is the use of xsi:schemaLocation?

The Java XML parser that spring uses will read the schemaLocation values and try to load them from the internet, in order to validate the XML file. Spring, in turn, intercepts those load requests and serves up versions from inside its own JAR files.

If you omit the schemaLocation, then the XML parser won't know where to get the schema in order to validate the config.

How do I remove a CLOSE_WAIT socket connection

As described by Crist Clark.

CLOSE_WAIT means that the local end of the connection has received a FIN from the other end, but the OS is waiting for the program at the local end to actually close its connection.

The problem is your program running on the local machine is not closing the socket. It is not a TCP tuning issue. A connection can (and quite correctly) stay in CLOSE_WAIT forever while the program holds the connection open.

Once the local program closes the socket, the OS can send the FIN to the remote end which transitions you to LAST_ACK while you wait for the ACK of the FIN. Once that is received, the connection is finished and drops from the connection table (if your end is in CLOSE_WAIT you do not end up in the TIME_WAIT state).

What does "xmlns" in XML mean?

I think the biggest confusion is that xml namespace is pointing to some kind of URL that doesn't have any information. But the truth is that the person who invented below namespace:

xmlns:android="http://schemas.android.com/apk/res/android"

could also call it like that:

xmlns:android="asjkl;fhgaslifujhaslkfjhliuqwhrqwjlrknqwljk.rho;il"

This is just a unique identifier. However it is established that you should put there URL that is unique and can potentially point to the specification of used tags/attributes in that namespace. It's not required tho.

Why it should be unique? Because namespaces purpose is to have them unique so the attribute for example called background from your namespace can be distinguished from the background from another namespace.

Because of that uniqueness you do not need to worry that if you create your custom attribute you gonna have name collision.

How does `scp` differ from `rsync`?

One major feature of rsync over scp (beside the delta algorithm and encryption if used w/ ssh) is that it automatically verifies if the transferred file has been transferred correctly. Scp will not do that, which occasionally might result in corruption when transferring larger files. So in general rsync is a copy with guarantee.

Centos manpages mention this the end of the --checksum option description:

Note that rsync always verifies that each transferred file was correctly reconstructed on the receiving side by checking a whole-file checksum that is generated as the file is transferred, but that automatic after-the-transfer verification has nothing to do with this option’s before-the-transfer “Does this file need to be updated?” check.

Why are there two ways to unstage a file in Git?

This thread is a bit old, but I still want to add a little demonstration since it is still not an intuitive problem:

me$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   new file:   to-be-added
#   modified:   to-be-modified
#   deleted:    to-be-removed
#

me$ git reset -q HEAD to-be-added

    # ok

me$ git reset -q HEAD to-be-modified

    # ok

me$ git reset -q HEAD to-be-removed

    # ok

# or alternatively:

me$ git reset -q HEAD to-be-added to-be-removed to-be-modified

    # ok

me$ git status
# On branch master
# Changes not staged for commit:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   to-be-modified
#   deleted:    to-be-removed
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   to-be-added
no changes added to commit (use "git add" and/or "git commit -a")

git reset HEAD (without -q) gives a warning about the modified file and its exit code is 1 which will be considered as an error in a script.

Edit: git checkout HEAD to-be-modified to-be-removed also works for unstaging, but removes the change completely from the workspace

Update git 2.23.0: From time to time, the commands change. Now, git status says:

  (use "git restore --staged <file>..." to unstage)

... which works for all three types of change

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

Right click can be achieved using Java script executor as well(in cases where action class is not supported):

JavascriptExecutor js = (JavascriptExecutor) driver;

String javaScript = "var evt = document.createEvent('MouseEvents');"
                + "var RIGHT_CLICK_BUTTON_CODE = 2;"
                + "evt.initMouseEvent('contextmenu', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, RIGHT_CLICK_BUTTON_CODE, null);"
                + "arguments[0].dispatchEvent(evt)";

js.executeScript(javaScript, element);

How do I get my Maven Integration tests to run

You should try using maven failsafe plugin. You can tell it to include a certain set of tests.

How to set the color of an icon in Angular Material?

Since for some reason white isn't available for selection, I have found that mat-palette($mat-grey, 50) was close enough to white, for my needs at least.

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

Try to go to App_Data folder property and add ASPNET user with read and write privileges

Ref:
How to assign correct permissions to App_Data folder of WebMail Pro ASP.NET
Permissions on APP_DATA Folder
ASP/ASP.NET Best way to handle write permissions?

If it does not solve your problem then check whether your XML files are not open by another thread using these configuration files.. and provide some more details if still persists.

Copying HTML code in Google Chrome's inspect element

  1. Select the <html> tag in Elements.
  2. Do CTRL-C.
  3. Check if there is only lefting <!DOCTYPE html> before the <html>.

How to override equals method in Java

//Written by K@stackoverflow
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<Person> people = new ArrayList<Person>();
        people.add(new Person("Subash Adhikari", 28));
        people.add(new Person("K", 28));
        people.add(new Person("StackOverflow", 4));
        people.add(new Person("Subash Adhikari", 28));

        for (int i = 0; i < people.size() - 1; i++) {
            for (int y = i + 1; y <= people.size() - 1; y++) {
                boolean check = people.get(i).equals(people.get(y));

                System.out.println("-- " + people.get(i).getName() + " - VS - " + people.get(y).getName());
                System.out.println(check);
            }
        }
    }
}

//written by K@stackoverflow
public class Person {
    private String name;
    private int age;

    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }

        if (obj.getClass() != this.getClass()) {
            return false;
        }

        final Person other = (Person) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }

        if (this.age != other.age) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 53 * hash + this.age;
        return hash;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Output:

run:

-- Subash Adhikari - VS - K false

-- Subash Adhikari - VS - StackOverflow false

-- Subash Adhikari - VS - Subash Adhikari true

-- K - VS - StackOverflow false

-- K - VS - Subash Adhikari false

-- StackOverflow - VS - Subash Adhikari false

-- BUILD SUCCESSFUL (total time: 0 seconds)

React.js inline style best practices

Depending on your configuration inline styling can offer you Hot reload. The webpage is immediately re-rendered every time the style changes. This helps me develop components quicker. Having said that, I am sure you can setup a Hot reload environment for CSS + SCSS.

How to hide html source & disable right click and text copy?

You potentially can not prevent user from viewing the HTML source content. The site that you have listed prevents user from right click. but fact is you can still do CTRL + U in Firefox to view source!

How to view an HTML file in the browser with Visual Studio Code

probably most will be able to find a solution from the above answers but seeing as how none worked for me (vscode v1.34) i thought i'd share my experience. if at least one person finds it helpful then, cool not a wasted post, amiirte?


anyway, my solution (windows) is built a-top of @noontz's. his configuration may have been sufficient for older versions of vscode but not with 1.34 (at least, i couldn't get it working ..).

our configs are nearly identical save a single property -- that property being, the group property. i'm not sure why but without this, my task would not even appear in the command palette.

so. a working tasks.json for windows users running vscode 1.34:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Chrome",
            "type": "process",
            "command": "chrome.exe",
            "windows": {
                "command": "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
            },
            "args": [
                "${file}"
            ],
            "group": "build",
            "problemMatcher": []
        }
    ]
}

note that the problemMatcher property is not required for this to work but without it an extra manual step is imposed on you. tried to read the docs on this property but i'm too thick to understand. hopefully someone will come about and school me but yeah, thanks in advance for that. all i know is -- include this property and ctrl+shift+b opens the current html file in a new chrome tab, hassle free.


easy.

How to present a modal atop the current view in Swift

This worked for me in Swift 5.0. Set the Storyboard Id in the identity inspector as "destinationVC".

@IBAction func buttonTapped(_ sender: Any) {
    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
    let destVC = storyboard.instantiateViewController(withIdentifier: "destinationVC") as! MyViewController

    destVC.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
    destVC.modalTransitionStyle = UIModalTransitionStyle.crossDissolve

    self.present(destVC, animated: true, completion: nil)
}

bash: Bad Substitution

I was adding a dollar sign twice in an expression with curly braces in bash:

cp -r $PROJECT_NAME ${$PROJECT_NAME}2

instead of

cp -r $PROJECT_NAME ${PROJECT_NAME}2

Regular expression for letters, numbers and - _

This is the pattern you are looking for

/^[\w-_.]*$/

What this means:

  • ^ Start of string
  • [...] Match characters inside
  • \w Any word character so 0-9 a-z A-Z
  • -_. Match - and _ and .
  • * Zero or more of pattern or unlimited
  • $ End of string

If you want to limit the amount of characters:

/^[\w-_.]{0,5}$/

{0,5} Means 0-5 characters

Maximum call stack size exceeded on npm install

I'm not a Windows user, so if you are, try to check Rene Knop comment.

For Unix/OSX users, I've removed the root .npmrc file ~/.npmrc.
Before you're going to try it, please, check if there is nothing necessary over there you can use this command to bring all content into your terminal: cat ~/.npmrc .

If you have got something like:

cat: /Users/$USER/.npmrc: No such file or directory

to save a copy:

cp ~/.npmrc ~/.npmrc_copy

Now, try to remove it (Works for bash users: Unix / Ubuntu / OSX ...):

rm -f ~/.npmrc

This worked for me.
Hope this will be helpful for others.

Manually Set Value for FormBuilder Control

You could try this:

deptSelected(selected: { id: string; text: string }) {
  console.log(selected) // Shows proper selection!

  // This is how I am trying to set the value
  this.form.controls['dept'].updateValue(selected.id);
}

For more details, you could have a look at the corresponding JS Doc regarding the second parameter of the updateValue method: https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/model.ts#L269.

Find the most frequent number in a NumPy array

Starting in Python 3.4, the standard library includes the statistics.mode function to return the single most common data point.

from statistics import mode

mode([1, 2, 3, 1, 2, 1, 1, 1, 3, 2, 2, 1])
# 1

If there are multiple modes with the same frequency, statistics.mode returns the first one encountered.


Starting in Python 3.8, the statistics.multimode function returns a list of the most frequently occurring values in the order they were first encountered:

from statistics import multimode

multimode([1, 2, 3, 1, 2])
# [1, 2]

Is there a MySQL option/feature to track history of changes to records?

Just my 2 cents. I would create a solution which records exactly what changed, very similar to transient's solution.

My ChangesTable would simple be:

DateTime | WhoChanged | TableName | Action | ID |FieldName | OldValue

1) When an entire row is changed in the main table, lots of entries will go into this table, BUT that is very unlikely, so not a big problem (people are usually only changing one thing) 2) OldVaue (and NewValue if you want) have to be some sort of epic "anytype" since it could be any data, there might be a way to do this with RAW types or just using JSON strings to convert in and out.

Minimum data usage, stores everything you need and can be used for all tables at once. I'm researching this myself right now, but this might end up being the way I go.

For Create and Delete, just the row ID, no fields needed. On delete a flag on the main table (active?) would be good.

Access images inside public folder in laravel

In my case it worked perfectly

<img style="border-radius: 50%;height: 50px;width: 80px;"  src="<?php echo asset("storage/TeacherImages/{$teacher->profilePic}")?>">

this is used to display image from folder i hope this will help someone looking for this type of code

Connect HTML page with SQL server using javascript

JavaScript is a client-side language and your MySQL database is going to be running on a server.

So you have to rename your file to index.php for example (.php is important) so you can use php code for that. It is not very difficult, but not directly possible with html.

(Somehow you can tell your server to let the html files behave like php files, but this is not the best solution.)

So after you renamed your file, go to the very top, before <html> or <!DOCTYPE html> and type:

<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        /*Creating variables*/
        $name = $_POST["name"];
        $address = $_POST["address"];
        $age = $_POST["age"];


        $dbhost = "localhost"; /*most of the time it's localhost*/
        $username = "yourusername";
        $password = "yourpassword";
        $dbname = "mydatabase";

        $mysql = mysqli_connect($dbhost, $username, $password, $dbname); //It connects
        $query = "INSERT INTO yourtable (name,address,age) VALUES $name, $address, $age";
        mysqli_query($mysql, $query);
    }
?>
<!DOCTYPE html>
<html>
<head>.......
....
    <form method="post">
        <input name="name" type="text"/>
        <input name="address" type="text"/>
        <input name="age" type="text"/>
    </form>
....

Bash: infinite sleep (infinite blocking)

sleep infinity looks most elegant, but sometimes it doesn't work for some reason. In that case, you can try other blocking commands such as cat, read, tail -f /dev/null, grep a etc.

How to express a NOT IN query with ActiveRecord/Rails?

Using Arel:

topics=Topic.arel_table
Topic.where(topics[:forum_id].not_in(@forum_ids))

or, if preferred:

topics=Topic.arel_table
Topic.where(topics[:forum_id].in(@forum_ids).not)

and since rails 4 on:

topics=Topic.arel_table
Topic.where.not(topics[:forum_id].in(@forum_ids))

Please notice that eventually you do not want the forum_ids to be the ids list, but rather a subquery, if so then you should do something like this before getting the topics:

@forum_ids = Forum.where(/*whatever conditions are desirable*/).select(:id)

in this way you get everything in a single query: something like:

select * from topic 
where forum_id in (select id 
                   from forum 
                   where /*whatever conditions are desirable*/)

Also notice that eventually you do not want to do this, but rather a join - what might be more efficient.

How to git commit a single file/directory

Try:

git commit -m 'my notes' path/to/my/file.ext 

How to properly add include directories with CMake

I had the same problem.

My project directory was like this:

    --project
    ---Classes
    ----Application
    -----.h and .c files
    ----OtherFolders
    --main.cpp

And what I used to include the files in all those folders:

    file(GLOB source_files
            "*.h"
            "*.cpp"
            "Classes/*/*.cpp"
            "Classes/*/*.h"
    )

    add_executable(Server ${source_files})

And it totally worked.

Use python requests to download CSV

Python3 Supported Code

    with closing(requests.get(PHISHTANK_URL, stream=True})) as r:
        reader = csv.reader(codecs.iterdecode(r.iter_lines(), 'utf-8'), delimiter=',', quotechar='"')
        for record in reader:
           print (record)

Transposing a 2D-array in JavaScript

here is my implementation in modern browser (without dependency):

transpose = m => m[0].map((x,i) => m.map(x => x[i]))

custom facebook share button

You can use facebook javascript sdk. First add FB Js SDK to your code (please refer to https://developers.facebook.com/docs/javascript)

window.fbAsyncInit = function(){
FB.init({
    appId: 'xxxxx', status: true, cookie: true, xfbml: true }); 
};
(function(d, debug){var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if(d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; 
    js.async = true;js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
    ref.parentNode.insertBefore(js, ref);}(document, /*debug*/ false));
function postToFeed(title, desc, url, image){
var obj = {method: 'feed',link: url, picture: 'http://www.url.com/images/'+image,name: title,description: desc};
function callback(response){}
FB.ui(obj, callback);
}

So when you want to share something

<a href="someurl.com/some-article" data-image="article-1.jpg" data-title="Article Title" data-desc="Some description for this article" class="btnShare">Share</a>

And finally JS to handle click:

$('.btnShare').click(function(){
elem = $(this);
postToFeed(elem.data('title'), elem.data('desc'), elem.prop('href'), elem.data('image'));

return false;
});

How can I add a Google search box to my website?

This is one of the way to add google site search to websites:

_x000D_
_x000D_
<form action="https://www.google.com/search" class="searchform" method="get" name="searchform" target="_blank">_x000D_
<input name="sitesearch" type="hidden" value="example.com">_x000D_
<input autocomplete="on" class="form-control search" name="q" placeholder="Search in example.com" required="required"  type="text">_x000D_
<button class="button" type="submit">Search</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Date formatting in WPF datagrid

This is a very old question, but I found a new solution, so I wrote about it.

First of all, is this way of solution possible while using AutoGenerateColumns?

Yes, that can be done with AttachedProperty as follows.

<DataGrid AutoGenerateColumns="True" 
   local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
   ItemsSource="{Binding}" />

AttachedProperty

There are two AttachedProperty defined that allow you to specify two formats. DateTimeFormatAutoGenerate for DateTime and TimeSpanFormatAutoGenerate for TimeSpan.

class DataGridOperation
{
    public static string GetDateTimeFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(DateTimeFormatAutoGenerateProperty);
    public static void SetDateTimeFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(DateTimeFormatAutoGenerateProperty, value);
    public static readonly DependencyProperty DateTimeFormatAutoGenerateProperty =
        DependencyProperty.RegisterAttached("DateTimeFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
            new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<DateTime>(d, e)));

    public static string GetTimeSpanFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(TimeSpanFormatAutoGenerateProperty);
    public static void SetTimeSpanFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(TimeSpanFormatAutoGenerateProperty, value);
    public static readonly DependencyProperty TimeSpanFormatAutoGenerateProperty =
        DependencyProperty.RegisterAttached("TimeSpanFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
            new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<TimeSpan>(d, e)));

    private static void AddEventHandlerOnGenerating<T>(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is DataGrid dGrid))
            return;

        if ((e.NewValue is string format))
            dGrid.AutoGeneratingColumn += (o, e) => AddFormat_OnGenerating<T>(e, format);
    }

    private static void AddFormat_OnGenerating<T>(DataGridAutoGeneratingColumnEventArgs e, string format)
    {
        if (e.PropertyType == typeof(T))
            (e.Column as DataGridTextColumn).Binding.StringFormat = format;
    }
}

How to use

View

<Window
   x:Class="DataGridAutogenerateCustom.MainWindow"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="clr-namespace:DataGridAutogenerateCustom"
   Width="400" Height="250">
   <Window.DataContext>
      <local:MainWindowViewModel />
   </Window.DataContext>
   <StackPanel>
      <TextBlock Text="DEFAULT FORMAT" />
      <DataGrid ItemsSource="{Binding Dates}" />

      <TextBlock Margin="0,30,0,0" Text="CUSTOM FORMAT" />
      <DataGrid
         local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
         local:DataGridOperation.TimeSpanFormatAutoGenerate="dd\-hh\-mm\-ss"
         ItemsSource="{Binding Dates}" />
   </StackPanel>
</Window>

ViewModel

public class MainWindowViewModel
{
    public DatePairs[] Dates { get; } = new DatePairs[]
    {
        new (){StartDate= new (2011,1,1), EndDate= new (2011,2,1) },
        new (){StartDate= new (2020,1,1), EndDate= new (2021,1,1) },
    };
}

public class DatePairs
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public TimeSpan Span => EndDate - StartDate;
}

demo_wpf_datagrid

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

Set the trigger option of the popover to hover instead of click, which is the default one.

This can be done using either data-* attributes in the markup:

<a id="popover" data-trigger="hover">Popover</a>

Or with an initialization option:

$("#popover").popover({ trigger: "hover" });

Here's a DEMO.

How do I find the difference between two values without knowing which is larger?

abs function is definitely not what you need as it is not calculating the distance. Try abs (-25+15) to see that it's not working. A distance between the numbers is 40 but the output will be 10. Because it's doing the math and then removing "minus" in front. I am using this custom function:


def distance(a, b):
    if (a < 0) and (b < 0) or (a > 0) and (b > 0):
        return abs( abs(a) - abs(b) )
    if (a < 0) and (b > 0) or (a > 0) and (b < 0):
        return abs( abs(a) + abs(b) )

print distance(-25, -15) print distance(25, -15) print distance(-25, 15) print distance(25, 15)

Logcat not displaying my log calls

I figured out I was automatically importing com.sileria.Log (from some library project) instead of android.util.Log, where the latter was the correct one. Check your imports as well.

How do I programmatically set device orientation in iOS 7?

If you want only portrait mode, in iOS 9 (Xcode 7) you can:

  • Going to Info.plist
  • Select "Supported interface orientations" item
  • Delete "Landscape(left home button)" and "Landscape(right home button)"

enter image description here

jquery select element by xpath

First create an xpath selector function.

function _x(STR_XPATH) {
    var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
    var xnodes = [];
    var xres;
    while (xres = xresult.iterateNext()) {
        xnodes.push(xres);
    }

    return xnodes;
}

To use the xpath selector with jquery, you can do like this:

$(_x('/html/.//div[@id="text"]')).attr('id', 'modified-text');

Hope this can help.

Create a pointer to two-dimensional array

In

int *ptr= l_matrix[0];

you can access like

*p
*(p+1)
*(p+2)

after all 2 dimensional arrays are also stored as 1-d.

Parse an HTML string with JS

with this simple code you can do that:

let el = $('<div></div>');
$(document.body).append(el);
el.html(`<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>`);
console.log(el.find('a[href="test0"]'));

Specifying maxlength for multiline textbox

Nearly all modern browsers now support the use of the maxlength attribute for textarea elements.(https://caniuse.com/#feat=maxlength)

To include the maxlength attribute on a multiline TextBox, you can simply modify the Attributes collection in the code behind like so:

txtTextBox.Attributes["maxlength"] = "100";

If you don't want to have to use the code behind to specify that, you can just create a custom control that derives from TextBox:

public class Textarea : TextBox
{
    public override TextBoxMode TextMode
    {
        get { return TextBoxMode.MultiLine; }
        set { }
    }

    protected override void OnPreRender(EventArgs e)
    {
        if (TextMode == TextBoxMode.MultiLine && MaxLength != 0)
        {
            Attributes["maxlength"] = MaxLength.ToString();
        }

        base.OnPreRender(e);
    }
}

JavaScript unit test tools for TDD

You might also be interested in the unit testing framework that is part of qooxdoo, an open source RIA framework similar to Dojo, ExtJS, etc. but with quite a comprehensive tool chain.

Try the online version of the testrunner. Hint: hit the gray arrow at the top left (should be made more obvious). It's a "play" button that runs the selected tests.

To find out more about the JS classes that let you define your unit tests, see the online API viewer.

For automated UI testing (based on Selenium RC), check out the Simulator project.

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>

VMware Workstation and Device/Credential Guard are not compatible

If you are someone who maintains an open customized "Run as administrator" command prompt or powershell command line window at all the times you can optionally setup the following aliases / macros to simplify executing the commands mentioned by @gue22 for simply disabling hyper-v hypervisor when needing to use vmware player or workstation and then enabling it again when done.

doskey hpvEnb = choice /c:yn /cs /d n /t 30 /m "Are you running from elevated command prompt" ^& if not errorlevel 2 ( bcdedit /set hypervisorlaunchtype auto ^& echo.^&echo now reboot to enable hyper-v hypervisor )
doskey hpvDis = choice /c:yn /cs /d n /t 30 /m "Are you running from elevated command prompt" ^& if not errorlevel 2 ( bcdedit /set hypervisorlaunchtype off ^& echo.^&echo now reboot to disable hyper-v hypervisor )
doskey bcdL = bcdedit /enum ^& echo.^&echo now see boot configuration data store {current} boot loader settings

With the above in place you just type "hpvenb" [ hypervisor enabled at boot ], "hpvdis" [ hypervisor disabled at boot ] and "bcdl" [ boot configuration devices list ] commands to execute the on, off, list commands.

PHP foreach change original array values

Use foreach($fields as &$field){ - so you will work with the original array.

Here is more about passing by reference.

sorting integers in order lowest to highest java

Well, if you want to do it using an algorithm. There are a plethora of sorting algorithms out there. If you aren't concerned too much about efficiency and more about readability and understandability. I recommend Insertion Sort. Here is the psudo code, it is trivial to translate this into java.

begin
    for i := 1 to length(A)-1 do
    begin
        value := A[i];
        j := i - 1;
        done := false;
        repeat
            { To sort in descending order simply reverse
              the operator i.e. A[j] < value }
            if A[j] > value then
            begin
                A[j + 1] := A[j];
                j := j - 1;
                if j < 0 then
                    done := true;
            end
            else
                done := true;
        until done;
        A[j + 1] := value;
    end;
end;

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

XCOPY switch to create specified directory if it doesn't exist?

I tried this on the command.it is working for me.

if "$(OutDir)"=="bin\Debug\"  goto Visual
:TFSBuild
goto exit
:Visual
xcopy /y "$(TargetPath)$(TargetName).dll" "$(ProjectDir)..\Demo"
xcopy /y "$(TargetDir)$(TargetName).pdb" "$(ProjectDir)..\Demo"
goto exit
:exit

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

I found a solution which works, although it is a bit ugly. It also won't work in every situation, but it works for me. Since I'm adapting the size of the user interface to the iPad's window size, the user is normally unable to scroll. In other words, if I set the window's scrollTop, it will remain at 0.

If, on the other hand, the keyboard is shown, scrolling suddenly works. So I can set scrollTop, immediately test its value, and then reset it. Here's how that might look in code, using jQuery:

$(document).ready(function(){
    $('input').bind('focus',function() {
        $(window).scrollTop(10);
        var keyboard_shown = $(window).scrollTop() > 0;
        $(window).scrollTop(0);

        $('#test').append(keyboard_shown?'keyboard ':'nokeyboard ');
    });
});

Normally, you would expect this to not be visible to the user. Unfortunately, at least when running in the Simulator, the iPad visibly (though quickly) scrolls up and down again. Still, it works, at least in some specific situations.

I've tested this on an iPad, and it seems to work fine.