Programs & Examples On #Xpi

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

By default nginx limits upload size to 1MB.

With client_max_body_size you can set your own limit, as in

location /uploads {
    ...
    client_max_body_size 100M;
} 

You can set this setting also on the http or server block instead (See here).

This fixed my issue with net::ERR_HTTP2_PROTOCOL_ERROR

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

Just to put it out there, i had the same problems. On my local homestead it would work as expected but after pushing it to the development server i got the session timeout message as well. Figuring its a environment issue i changed from apache to nginx and that miraculously made the problem go away.

jwt check if token expired

Sadly @Andrés Montoya answer has a flaw which is related to how he compares the obj. I found a solution here which should solve this:

const now = Date.now().valueOf() / 1000

if (typeof decoded.exp !== 'undefined' && decoded.exp < now) {
    throw new Error(`token expired: ${JSON.stringify(decoded)}`)
}
if (typeof decoded.nbf !== 'undefined' && decoded.nbf > now) {
    throw new Error(`token expired: ${JSON.stringify(decoded)}`)
}

Thanks to thejohnfreeman!

HTTP POST with Json on Body - Flutter/Dart

This would also work :

import 'package:http/http.dart' as http;

  sendRequest() async {

    Map data = {
       'apikey': '12345678901234567890'
    };

    var url = 'https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
    http.post(url, body: data)
        .then((response) {
      print("Response status: ${response.statusCode}");
      print("Response body: ${response.body}");
    });  
  }

Set cookies for cross origin requests

Pim's answer is very helpful. In my case, I have to use

Expires / Max-Age: "Session"

If it is a dateTime, even it is not expired, it still won't send the cookie to the backend:

Expires / Max-Age: "Thu, 21 May 2020 09:00:34 GMT"

Hope it is helpful for future people who may meet same issue.

laravel 5.5 The page has expired due to inactivity. Please refresh and try again

Excluding URIs From CSRF Protection:

Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes.

Typically, you should place these kinds of routes outside of the web middleware group that the RouteServiceProvider applies to all routes in the routes/web.php file. However, you may also exclude the routes by adding their URIs to the $except property of the VerifyCsrfToken middleware:

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

"The page has expired due to inactivity" - Laravel 5.5

Some information is stored in the cookie which is related to previous versions of laravel in development. So it's conflicting with csrf generated tokens which are generated by another's versions. Just Clear the cookie and give a try.

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

Then later on in your actions you can simply

store.commit('authenticate', {
    token,
    expiration,
});

Is Visual Studio Community a 30 day trial?

No, Community edition is free, so just sign-in and rid the warning. For more detail please check following link.
https://visualstudio.microsoft.com/vs/support/community-edition-expired-buy-license/

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

If you need to skip the password prompt for some reason, you can input the password in the command (Dangerous)

mysql -u root --password=secret

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

I know this is an old thread, but there is a particular case when this may happen:

If you are using AWS api gateway coupled with a VPC link, and if the Network Load Balancer has proxy protocol v2 enabled, a 400 Bad Request will happen as well.

Took me the whole afternoon to figure it out, so if it may help someone I'd be glad :)

nginx: [emerg] "server" directive is not allowed here

The path to the nginx.conf file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf.

You may access and edit this file by typing this at the terminal

cd /etc/nginx

/etc/nginx$ sudo nano nginx.conf

Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.

I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf file which is the primary Configuration file for Nginx.

Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d . Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-

http{
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

Further to this you may comment out from the PRIMARY Config file , the line

http{
    #include /etc/nginx/sites-available/some_file.conf; # Comment Out 
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

and need not keep any Config Files in /etc/nginx/sites-available/ and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/ , kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .

EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/ , this was the older practice and is DEPRECIATED now .

Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf; .

Quote from Nginx CookBook page - 5 .

"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."

ORA-28001: The password has expired

I have fixed the problem, just need to check:

open_mode from v$database

and then check:

check account_status to get mode information

and then use:

alter user myuser identified by mynewpassword account unlock;

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

Disable nginx cache for JavaScript files

What you are looking for is a simple directive like:

location ~* \.(?:manifest|appcache|html?|xml|json)$ {
    expires -1;
}

The above will not cache the extensions within the (). You can configure different directives for different file types.

How can I set a cookie in react?

You can use default javascript cookies set method. this working perfect.

createCookieInHour: (cookieName, cookieValue, hourToExpire) => {
    let date = new Date();
    date.setTime(date.getTime()+(hourToExpire*60*60*1000));
    document.cookie = cookieName + " = " + cookieValue + "; expires = " +date.toGMTString();
},

call java scripts funtion in react method as below,

createCookieInHour('cookieName', 'cookieValue', 5);

and you can use below way to view cookies.

let cookie = document.cookie.split(';');
console.log('cookie : ', cookie);

please refer below document for more information - URL

Disable Chrome strict MIME type checking

In case you are using node.js (with express)

If you want to serve static files in node.js, you need to use a function. Add the following code to your js file:

app.use(express.static("public"));

Where app is:

const express = require("express");
const app = express();

Then create a folder called public in you project folder. (You could call it something else, this is just good practice but remember to change it from the function as well.)

Then in this file create another folder named css (and/or images file under css if you want to serve static images as well.) then add your css files to this folder.

After you add them change the stylesheet accordingly. For example if it was:

href="cssFileName.css"

and

src="imgName.png"

Make them:

href="css/cssFileName.css"
src="css/images/imgName.png"

That should work

Letsencrypt add domain to existing certificate

I was able to setup a SSL certificated for a domain AND multiple subdomains by using using --cert-name combined with --expand options.

See official certbot-auto documentation at https://certbot.eff.org/docs/using.html

Example:

certbot-auto certonly --cert-name mydomain.com.br \
--renew-by-default -a webroot -n --expand \
--webroot-path=/usr/share/nginx/html \
-d mydomain.com.br \
-d www.mydomain.com.br \
-d aaa1.com.br \
-d aaa2.com.br \
-d aaa3.com.br

How to configure CORS in a Spring Boot + Spring Security application?

Cross origin protection is a feature of the browser. Curl does not care for CORS, as you presumed. That explains why your curls are successful, while the browser requests are not.

If you send the browser request with the wrong credentials, spring will try to forward the client to a login page. This response (off the login page) does not contain the header 'Access-Control-Allow-Origin' and the browser reacts as you describe.

You must make spring to include the haeder for this login response, and may be for other response, like error pages etc.

This can be done like this :

    @Configuration
    @EnableWebMvc
    public class WebConfig extends WebMvcConfigurerAdapter {

            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                    .allowedOrigins("http://domain2.com")
                    .allowedMethods("PUT", "DELETE")
                    .allowedHeaders("header1", "header2", "header3")
                    .exposedHeaders("header1", "header2")
                    .allowCredentials(false).maxAge(3600);
            }
     }

This is copied from cors-support-in-spring-framework

I would start by adding cors mapping for all resources with :

registry.addMapping("/**")

and also allowing all methods headers.. Once it works you may start to reduce that again to the needed minimum.

Please note, that the CORS configuration changes with Release 4.2.

If this does not solve your issues, post the response you get from the failed ajax request.

Certificate has either expired or has been revoked

In Xcode 8,

  1. Go to Preferences->Accounts
  2. Press on your account
  3. Click "View Details"
  4. Delete profile which you need
  5. Click "Download All" in the lower left hand corner.

download a file from Spring boot rest service

Option 1 using an InputStreamResource

Resource implementation for a given InputStream.

Should only be used if no other specific Resource implementation is > applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

Option2 as the documentation of the InputStreamResource suggests - using a ByteArrayResource:

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    Path path = Paths.get(file.getAbsolutePath());
    ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

MySQL Incorrect datetime value: '0000-00-00 00:00:00'

Make the sql mode non strict

if using laravel go to config->database, the go to mysql settings and make the strict mode false

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

You need a development provisioning profile on your build machine. Apps can run on the simulator without a profile, but they are required to run on an actual device.

If you open the project in Xcode, it may automatically set up provisioning for you. Otherwise you will have to create go to the iOS Dev Center and create a profile.

Mysql password expired. Can't connect

All of these answers are using Linux consoles to access MySQL.

If you are on Windows and are using WAMP, you can start by opening the MySQL console (click WAMP icon->MySQL->MySQL console).

Then it will request you to enter your current password, enter it.

And then type SET PASSWORD = PASSWORD('some_pass');

ES6 export default with multiple functions referring to each other

One alternative is to change up your module. Generally if you are exporting an object with a bunch of functions on it, it's easier to export a bunch of named functions, e.g.

export function foo() { console.log('foo') }, 
export function bar() { console.log('bar') },
export function baz() { foo(); bar() }

In this case you are export all of the functions with names, so you could do

import * as fns from './foo';

to get an object with properties for each function instead of the import you'd use for your first example:

import fns from './foo';

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

I experienced this exception, and it was also related to ServicePointManager.SecurityProtocol.

For me, this was because ServicePointManager.SecurityProtocol had been set to Tls | Tls11 (because of certain websites the application visits with broken TLS 1.2) and upon visiting a TLS 1.2-only website (tested with SSLLabs' SSL Report), it failed.

An option for .NET 4.5 and higher is to enable all TLS versions:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                     | SecurityProtocolType.Tls11
                                     | SecurityProtocolType.Tls12;

Convert String to Carbon

Try this

$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;

Visual Studio Community 2015 expiration date

I am running VSCommunity 2015 in Win8.1 virtual machine installed inside a Parallels 11 virtual machine installed on my Mac OSX El Capitan. To my surprise and delight it installed and ran fine. I used it for 2 weeks without signing into my Microsoft account. I tried to login 6 weeks later and got the 30 day trial screen shown above.

However for me I was able to simply click on the link above shown as "Check for an updated license" and was prompted in to log in to my Microsoft account. I did so and it granted me a license successfully and was seamless. Now under License Status it displays as "This product is licensed to: ".

I guess I got lucky as I'm guessing this is how it is supposed to work.

[sidebar]: Over the decades I've disliked most MS products but have been out of the VS IDE development tools game for awhile, and I have to say using VSComm15 has been flawless. Using it to learn C# and the IDE itself for a new contract job and it worked perfectly and has great features.

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

this was happening for me for a different reason altogether. net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 when i inspect the page and go to newtork tab, i see that the vendor.js page has failed to load. Upon checking it seems that the size of the js file is big ~ 6.5 mb.Thats when i realised that i needed to compress the js. I checked that I was using ng build command to build. Instead when i used ng build --prod --aot --vendor-chunk --common-chunk --delete-output-path --buildOptimizer it worked for me.see https://github.com/angular/angular-cli/issues/9016

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

With Postman, select Body tab and choose the raw option and type the following:

grant_type=password&username=yourusername&password=yourpassword

PageSpeed Insights 99/100 because of Google Analytics - How can I cache GA?

You can try to host the analytics.js locally and update it's contents with a caching script or manually.

The js file is updated only few times a year and if you don't need any new tracking features update it manually.

https://developers.google.com/analytics/devguides/collection/analyticsjs/changelog

Prevent Sequelize from outputting SQL to the console on execution of query?

I solved a lot of issues by using the following code. Issues were : -

  1. Not connecting with database
  2. Database connection Rejection issues
  3. Getting rid of logs in console (specific for this).
const sequelize = new Sequelize("test", "root", "root", {
  host: "127.0.0.1",
  dialect: "mysql",
  port: "8889",
  connectionLimit: 10,
  socketPath: "/Applications/MAMP/tmp/mysql/mysql.sock",
  // It will disable logging
  logging: false
});

Elasticsearch difference between MUST and SHOULD bool query

As said in the documentation:

Must: The clause (query) must appear in matching documents.

Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.

In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.

Since you want your results to satisfy all the queries, you should use must.


You can indeed use filters inside a boolean query.

Spring boot - Not a managed type

Below worked for me..

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.apache.catalina.security.SecurityConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.something.configuration.SomethingConfig;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SomethingConfig.class, SecurityConfig.class }) //All your configuration classes
@EnableAutoConfiguration
@WebAppConfiguration // for MVC configuration
@EnableJpaRepositories("com.something.persistence.dataaccess")  //JPA repositories
@EntityScan("com.something.domain.entity.*")  //JPA entities
@ComponentScan("com.something.persistence.fixture") //any component classes you have
public class SomethingApplicationTest {

    @Autowired
    private WebApplicationContext ctx;
    private MockMvc mockMvc;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
    }

    @Test
    public void loginTest() throws Exception {
        this.mockMvc.perform(get("/something/login"))
        .andDo(print()).andExpect(status().isOk());
    }

}

Hadoop cluster setup - java.net.ConnectException: Connection refused

From the netstat output you can see the process is listening on address 127.0.0.1

tcp        0      0 127.0.0.1:9000          0.0.0.0:*  ...

from the exception message you can see that it tries to connect to address 127.0.1.1

java.net.ConnectException: Call From marta-komputer/127.0.1.1 to localhost:9000 failed ...

further in the exception it's mentionend

For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused

on this page you find

Check that there isn't an entry for your hostname mapped to 127.0.0.1 or 127.0.1.1 in /etc/hosts (Ubuntu is notorious for this)

so the conclusion is to remove this line in your /etc/hosts

127.0.1.1       marta-komputer

JWT refresh token flow

Assuming that this is about OAuth 2.0 since it is about JWTs and refresh tokens...:

  1. just like an access token, in principle a refresh token can be anything including all of the options you describe; a JWT could be used when the Authorization Server wants to be stateless or wants to enforce some sort of "proof-of-possession" semantics on to the client presenting it; note that a refresh token differs from an access token in that it is not presented to a Resource Server but only to the Authorization Server that issued it in the first place, so the self-contained validation optimization for JWTs-as-access-tokens does not hold for refresh tokens

  2. that depends on the security/access of the database; if the database can be accessed by other parties/servers/applications/users, then yes (but your mileage may vary with where and how you store the encryption key...)

  3. an Authorization Server may issue both access tokens and refresh tokens at the same time, depending on the grant that is used by the client to obtain them; the spec contains the details and options on each of the standardized grants

Laravel, sync() - how to sync an array and also pass additional pivot fields?

Add following trait to your project and append it to your model class as a trait. This is helpful, because this adds functionality to use multiple pivots. Probably someone can clean this up a little and improve on it ;)

namespace App\Traits;

trait AppTraits
{
    /**
     * Create pivot array from given values
     *
     * @param array $entities
     * @param array $pivots
     * @return array combined $pivots
     */
    public function combinePivot($entities, $pivots = [])
    {
        // Set array
        $pivotArray = [];
        // Loop through all pivot attributes
        foreach ($pivots as $pivot => $value) {
            // Combine them to pivot array
            $pivotArray += [$pivot => $value];
        }
        // Get the total of arrays we need to fill
        $total = count($entities);
        // Make filler array
        $filler = array_fill(0, $total, $pivotArray);
        // Combine and return filler pivot array with data
        return array_combine($entities, $filler);
    }
}

Model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Example extends Model
{
    use Traits\AppTraits;
    // ...
}

Usage:

// Get id's
$entities = [1, 2, 3];
// Create pivots
$pivots = [
    'price' => 634,
    'name'  => 'Example name',
];
// Combine the ids and pivots
$combination = $model->combinePivot($entities, $pivots);
// Sync the combination with the related model / pivot
$model->relation()->sync($combination);

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

In your $CATALINA_BASE/conf/context.xml add block below before </Context>

<Resources cachingAllowed="true" cacheMaxSize="100000" />

For more information: http://tomcat.apache.org/tomcat-8.0-doc/config/resources.html

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

There are two possible scenario, in my case I used 2nd point.

  1. If you are facing this issue in production environment and you can easily deploy new code to the production then you can use of below solution.

    You can add below line of code before making api call,

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5

  2. If you cannot deploy new code and you want to resolve with the same code which is present in the production, then this issue can be done by changing some configuration setting file. You can add either of one in your config file.

<runtime>
    <AppContextSwitchOverrides value="Switch.System.Net.DontEnableSchUseStrongCrypto=false"/>
  </runtime>

or

<runtime>
  <AppContextSwitchOverrides value="Switch.System.Net.DontEnableSystemDefaultTlsVersions=false"
</runtime>

JWT (JSON Web Token) automatic prolongation of expiration

In the case where you handle the auth yourself (i.e don't use a provider like Auth0), the following may work:

  1. Issue JWT token with relatively short expiry, say 15min.
  2. Application checks token expiry date before any transaction requiring a token (token contains expiry date). If token has expired, then it first asks API to 'refresh' the token (this is done transparently to the UX).
  3. API gets token refresh request, but first checks user database to see if a 'reauth' flag has been set against that user profile (token can contain user id). If the flag is present, then the token refresh is denied, otherwise a new token is issued.
  4. Repeat.

The 'reauth' flag in the database backend would be set when, for example, the user has reset their password. The flag gets removed when the user logs in next time.

In addition, let's say you have a policy whereby a user must login at least once every 72hrs. In that case, your API token refresh logic would also check the user's last login date from the user database and deny/allow the token refresh on that basis.

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

i had the same issue. go to Sql Server Configuration management->SQL Server network config->protocols for 'servername' and check named pipes is enabled.

How to create permanent PowerShell Aliases

It's not a good idea to add this kind of thing directly to your $env:WINDIR powershell folders.
The recommended way is to add it to your personal profile:

cd $env:USERPROFILE\Documents
md WindowsPowerShell -ErrorAction SilentlyContinue
cd WindowsPowerShell
New-Item Microsoft.PowerShell_profile.ps1 -ItemType "file" -ErrorAction SilentlyContinue
powershell_ise.exe .\Microsoft.PowerShell_profile.ps1

Now add your alias to the Microsoft.PowerShell_profile.ps1 file that is now opened:

function Do-ActualThing {
    # do actual thing
}

Set-Alias MyAlias Do-ActualThing

Then save it, and refresh the current session with:

. $profile

Note: Just in case, if you get permission issue like

CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess

Try the below command and refresh the session again.

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

Why am I getting a "401 Unauthorized" error in Maven?

As stated in @John's answer, the fact that there is already a 0.1.2-SNAPSHOT, interfered with my new non-SNAPSHOT version 0.1.2. Since the 401 Unauthorized error is nebulous and unhelpful--and is normally associated to user/pass problems--it's no surprise that I was unable to figure this out on my own.

Changing the version to 0.1.3 brings me back to my original error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.4:install (default-install) on project xbnjava: Failed to install artifact com.github.aliteralmind:xbnjava:jar:0.1.3: R:\jeffy\programming\build\xbnjava-0.1.3\download\xbnjava-0.1.3-all.jar (The system cannot find the path specified) -> [Help 1].

A sonatype support person also recommended that I remove the <parent> block from my POM (it's only there because it's in the one from ez-vcard, which is what I started with) and replace my <distributionManagement> block with

<distributionManagement>
  <snapshotRepository>
    <id>ossrh</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
  </snapshotRepository>
  <repository>
    <id>ossrh</id>
    <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
  </repository>
</distributionManagement>
and then make sure that lines up with what's in your settings.xml:
<settings>
  <servers>
    <server>
      <id>ossrh</id>
      <username>your-jira-id</username>
      <password>your-jira-pwd</password>
    </server>
  </servers>
</settings>

After doing this, running mvn deploy actually uploaded one of my jars for the very first time!!!

Output:

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building XBN-Java 0.1.3
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava ---
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ xbnjava ---
[INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\pom.xml to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.3\xbnjava-0.1.3.pom
[INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.3\download\xbnjava-0.1.3.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.3\xbnjava-0.1.3.jar
[INFO]
[INFO] --- maven-deploy-plugin:2.7:deploy (default-deploy) @ xbnjava ---
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.pom
2/6 KB
4/6 KB
6/6 KB

Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.pom (6 KB at 4.6 KB/sec)
Downloading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml
310/310 B

Downloaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml (310 B at 1.6 KB/sec)
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml
310/310 B

Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml (310 B at 1.4 KB/sec)
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.jar
2/630 KB
4/630 KB
6/630 KB
8/630 KB
10/630 KB
12/630 KB
14/630 KB
...
618/630 KB
620/630 KB
622/630 KB
624/630 KB
626/630 KB
628/630 KB
630/630 KB

(Success portion:)

Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.jar (630 KB at 474.7 KB/sec)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.632 s
[INFO] Finished at: 2014-07-18T15:09:25-04:00
[INFO] Final Memory: 6M/19M
[INFO] ------------------------------------------------------------------------

Here's the full updated POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.github.aliteralmind</groupId>
  <artifactId>xbnjava</artifactId>
  <packaging>pom</packaging>
  <version>0.1.3</version>
  <name>XBN-Java</name>
  <url>https://github.com/aliteralmind/xbnjava</url>
  <inceptionYear>2014</inceptionYear>
  <organization>
     <name>Jeff Epstein</name>
  </organization>
  <description>XBN-Java is a collection of generically-useful backend (server side, non-GUI) programming utilities, featuring RegexReplacer and FilteredLineIterator. XBN-Java is the foundation of Codelet (http://codelet.aliteralmind.com).</description>

  <licenses>
     <license>
        <name>Lesser General Public License (LGPL) version 3.0</name>
        <url>https://www.gnu.org/licenses/lgpl-3.0.txt</url>
     </license>
     <license>
        <name>Apache Software License (ASL) version 2.0</name>
        <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
     </license>
  </licenses>

  <developers>
     <developer>
        <name>Jeff Epstein</name>
        <email>[email protected]</email>
        <roles>
           <role>Lead Developer</role>
        </roles>
     </developer>
  </developers>

  <issueManagement>
     <system>GitHub Issue Tracker</system>
     <url>https://github.com/aliteralmind/xbnjava/issues</url>
  </issueManagement>

  <distributionManagement>
    <snapshotRepository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    </snapshotRepository>
    <repository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
    </repository>
  </distributionManagement>

  <scm>
     <connection>scm:git:[email protected]:aliteralmind/xbnjava.git</connection>
     <url>scm:git:[email protected]:aliteralmind/xbnjava.git</url>
     <developerConnection>scm:git:[email protected]:aliteralmind/xbnjava.git</developerConnection>
  </scm>

  <properties>
     <java.version>1.7</java.version>
     <jarprefix>R:\jeffy\programming\build\/${project.artifactId}-${project.version}/download/${project.artifactId}-${project.version}</jarprefix>
  </properties>
  <build>
     <plugins>
        <plugin>
           <groupId>org.codehaus.mojo</groupId>
           <artifactId>build-helper-maven-plugin</artifactId>
           <version>1.8</version>
           <executions>
              <execution>
                 <id>attach-artifacts</id>
                 <phase>package</phase>
                 <goals>
                    <goal>attach-artifact</goal>
                 </goals>
                 <configuration>
                    <artifacts>
                       <artifact>
                          <file>${jarprefix}.jar</file>
                          <type>jar</type>
                       </artifact>
                    </artifacts>
                 </configuration>
              </execution>
           </executions>
        </plugin>
     </plugins>
  </build>

  <profiles>
     <!--
     This profile will sign the JAR file, sources file, and javadocs file using the GPG key on the local machine.
     See: https://docs.sonatype.org/display/Repository/How+To+Generate+PGP+Signatures+With+Maven
     -->
     <profile>
        <id>release-sign-artifacts</id>
        <activation>
           <property>
              <name>release</name>
              <value>true</value>
           </property>
        </activation>
     </profile>
  </profiles>
</project>

That's one big Maven problem out of the way. Only 627 more to go.

curl: (60) SSL certificate problem: unable to get local issuer certificate

It is failing as cURL is unable to verify the certificate provided by the server.

There are two options to get this to work:

  1. Use cURL with -k option which allows curl to make insecure connections, that is cURL does not verify the certificate.

  2. Add the root CA (the CA signing the server certificate) to /etc/ssl/certs/ca-certificates.crt

You should use option 2 as it's the option that ensures that you are connecting to secure FTP server.

Validate date in dd/mm/yyyy format using JQuery Validate

If you use the moment js library it can easily be done like this -

jQuery.validator.addMethod("validDate", function(value, element) {
        return this.optional(element) || moment(value,"DD/MM/YYYY").isValid();
    }, "Please enter a valid date in the format DD/MM/YYYY");

upstream sent too big header while reading response header from upstream

If you're using Symfony framework: Before messing with Nginx config, try to disable ChromePHP first.

1 - Open app/config/config_dev.yml

2 - Comment these lines:

#chromephp:
    #type:   chromephp
    #level:  info

ChromePHP pack the debug info json-encoded in the X-ChromePhp-Data header, which is too big for the default config of nginx with fastcgi.

Source: https://github.com/symfony/symfony/issues/8413#issuecomment-20412848

Start redis-server with config file

I think that you should make the reference to your config file

26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf

you can try to start your redis server like

./redis-server /path/to/redis-stable/redis.conf

Convert date to UTC using moment.js

As of : moment.js version 2.24.0

let's say you have a local date input, this is the proper way to convert your dateTime or Time input to UTC :

var utcStart = new moment("09:00", "HH:mm").utc();

or in case you specify a date

var utcStart = new moment("2019-06-24T09:00", "YYYY-MM-DDTHH:mm").utc();

As you can see the result output will be returned in UTC :

//You can call the format() that will return your UTC date in a string 
 utcStart.format(); 
//Result : 2019-06-24T13:00:00 

But if you do this as below, it will not convert to UTC :

var myTime = new moment.utc("09:00", "HH:mm"); 

You're only setting your input to utc time, it's as if your mentioning that myTime is in UTC, ....the output will be 9:00

Spring Boot JPA - configuring auto reconnect

As some people already pointed out, spring-boot 1.4+, has specific namespaces for the four connections pools. By default, hikaricp is used in spring-boot 2+. So you will have to specify the SQL here. The default is SELECT 1. Here's what you would need for DB2 for example: spring.datasource.hikari.connection-test-query=SELECT current date FROM sysibm.sysdummy1

Caveat: If your driver supports JDBC4 we strongly recommend not setting this property. This is for "legacy" drivers that do not support the JDBC4 Connection.isValid() API. This is the query that will be executed just before a connection is given to you from the pool to validate that the connection to the database is still alive. Again, try running the pool without this property, HikariCP will log an error if your driver is not JDBC4 compliant to let you know. Default: none

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

Invalidating JSON Web Tokens

This seems really difficult to solve without a DB lookup upon every token verification. The alternative I can think of is keeping a blacklist of invalidated tokens server-side; which should be updated on a database whenever a change happens to persist the changes across restarts, by making the server check the database upon restart to load the current blacklist.

But if you keep it in the server memory (a global variable of sorts) then it's not gonna be scalable across multiple servers if you are using more than one, so in that case you can keep it on a shared Redis cache, which should be set-up to persist the data somewhere (database? filesystem?) in case it has to be restarted, and every time a new server is spun up it has to subscribe to the Redis cache.

Alternative to a black-list, using the same solution, you can do it with a hash saved in redis per session as this other answer points out (not sure that would be more efficient with many users logging in though).

Does it sound awfully complicated? it does to me!

Disclaimer: I have not used Redis.

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

How to determine SSL cert expiration date from a PEM encoded certificate?

One line checking on true/false if cert of domain will be expired in some time later(ex. 15 days):

openssl x509 -checkend $(( 24*3600*15 )) -noout -in <(openssl s_client -showcerts -connect my.domain.com:443 </dev/null 2>/dev/null | openssl x509 -outform PEM)
if [ $? -eq 0 ]; then
  echo 'good'
else
  echo 'bad'
fi

Locking pattern for proper use of .NET MemoryCache

There is an open source library [disclaimer: that I wrote]: LazyCache that IMO covers your requirement with two lines of code:

IAppCache cache = new CachingService();
var cachedResults = cache.GetOrAdd("CacheKey", 
  () => SomeHeavyAndExpensiveCalculation());

It has built in locking by default so the cacheable method will only execute once per cache miss, and it uses a lambda so you can do "get or add" in one go. It defaults to 20 minutes sliding expiration.

There's even a NuGet package ;)

How to make a machine trust a self-signed Java application

I had the same problem, but i solved it from Java Control Panel-->Security-->SecurityLevel:MEDIUM. Just so, no Manage certificates, imports ,exports etc..

HTML5 video won't play in Chrome only

I had a similar issue, no videos would play in Chrome. Tried installing beta 64bit, going back to Chrome 32bit release.

The only thing that worked for me was updating my video drivers.

I have the NVIDIA GTS 240. Downloaded, installed the drivers and restarted and Chrome 38.0.2125.77 beta-m (64-bit) starting playing HTML5 videos again on youtube, vimeo and others. Hope this helps anyone else.

Python : Trying to POST form using requests

Send a POST request with content type = 'form-data':

import requests
files = {
    'username': (None, 'myusername'),
    'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

Try to change where Member class

public function users() {
    return $this->hasOne('User');
} 

return $this->belongsTo('User');

OWIN Security - How to Implement OAuth2 Refresh Tokens

Just implemented my OWIN Service with Bearer (called access_token in the following) and Refresh Tokens. My insight into this is that you can use different flows. So it depends on the flow you want to use how you set your access_token and refresh_token expiration times.

I will describe two flows A and B in the follwing (I suggest what you want to have is flow B):

A) expiration time of access_token and refresh_token are the same as it is per default 1200 seconds or 20 minutes. This flow needs your client first to send client_id and client_secret with login data to get an access_token, refresh_token and expiration_time. With the refresh_token it is now possible to get a new access_token for 20 minutes (or whatever you set the AccessTokenExpireTimeSpan in the OAuthAuthorizationServerOptions to). For the reason that the expiration time of access_token and refresh_token are the same, your client is responsible to get a new access_token before the expiration time! E.g. your client could send a refresh POST call to your token endpoint with the body (remark: you should use https in production)

grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xxxxx

to get a new token after e.g. 19 minutes to prevent the tokens from expiration.

B) in this flow you want to have a short term expiration for your access_token and a long term expiration for your refresh_token. Lets assume for test purpose you set the access_token to expire in 10 seconds (AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(10)) and the refresh_token to 5 Minutes. Now it comes to the interesting part setting the expiration time of refresh_token: You do this in your createAsync function in SimpleRefreshTokenProvider class like this:

var guid = Guid.NewGuid().ToString();


        //copy properties and set the desired lifetime of refresh token
        var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
        {
            IssuedUtc = context.Ticket.Properties.IssuedUtc,
            ExpiresUtc = DateTime.UtcNow.AddMinutes(5) //SET DATETIME to 5 Minutes
            //ExpiresUtc = DateTime.UtcNow.AddMonths(3) 
        };
        /*CREATE A NEW TICKET WITH EXPIRATION TIME OF 5 MINUTES 
         *INCLUDING THE VALUES OF THE CONTEXT TICKET: SO ALL WE 
         *DO HERE IS TO ADD THE PROPERTIES IssuedUtc and 
         *ExpiredUtc to the TICKET*/
        var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

        //saving the new refreshTokenTicket to a local var of Type ConcurrentDictionary<string,AuthenticationTicket>
        // consider storing only the hash of the handle
        RefreshTokens.TryAdd(guid, refreshTokenTicket);            
        context.SetToken(guid);

Now your client is able to send a POST call with a refresh_token to your token endpoint when the access_token is expired. The body part of the call may look like this: grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xx

One important thing is that you may want to use this code not only in your CreateAsync function but also in your Create function. So you should consider to use your own function (e.g. called CreateTokenInternal) for the above code. Here you can find implementations of different flows including refresh_token flow(but without setting the expiration time of the refresh_token)

Here is one sample implementation of IAuthenticationTokenProvider on github (with setting the expiration time of the refresh_token)

I am sorry that I can't help out with further materials than the OAuth Specs and the Microsoft API Documentation. I would post the links here but my reputation doesn't let me post more than 2 links....

I hope this may help some others to spare time when trying to implement OAuth2.0 with refresh_token expiration time different to access_token expiration time. I couldn't find an example implementation on the web (except the one of thinktecture linked above) and it took me some hours of investigation until it worked for me.

New info: In my case I have two different possibilities to receive tokens. One is to receive a valid access_token. There I have to send a POST call with a String body in format application/x-www-form-urlencoded with the following data

client_id=YOURCLIENTID&grant_type=password&username=YOURUSERNAME&password=YOURPASSWORD

Second is if access_token is not valid anymore we can try the refresh_token by sending a POST call with a String body in format application/x-www-form-urlencoded with the following data grant_type=refresh_token&client_id=YOURCLIENTID&refresh_token=YOURREFRESHTOKENGUID

"The system cannot find the file specified"

I got same error after publish my project to my physical server. My web application works perfectly on my computer when I compile on VS2013. When I checked connection string on sql server manager, everything works perfect on server too. I also checked firewall (I switched it off). But still didn't work. I remotely try to connect database by SQL Manager with exactly same user/pass and instance name etc with protocol pipe/tcp and I saw that everything working normally. But when I try to open website I'm getting this error. Is there anyone know 4th option for fix this problem?.

NOTE: My App: ASP.NET 4.5 (by VS2013), Server: Windows 2008 R2 64bit, SQL: MS-SQL WEB 2012 SP1 Also other web applications works great at web browsers with their database on same server.


After one day suffering I found the solution of my issue:

First I checked all the logs and other details but i could find nothing. Suddenly I recognize that; when I try to use connection string which is connecting directly to published DB and run application on my computer by VS2013, I saw that it's connecting another database file. I checked local directories and I found it. ASP.NET Identity not using my connection string as I wrote in web.config file. And because of this VS2013 is creating or connecting a new database with the name "DefaultConnection.mdf" in App_Data folder. Then I found the solution, it was in IdentityModel.cs.

I changed code as this:

public class ApplicationUser : IdentityUser
{
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    //public ApplicationDbContext() : base("DefaultConnection") ---> this was original
    public ApplicationDbContext() : base("<myConnectionStringNameInWebConfigFile>") //--> changed
    {
    }
}

So, after all, I re-builded and published my project and everything works fine now :)

Node.js request CERT_HAS_EXPIRED

The best way to fix this:

Renew the certificate. This can be done for free using Greenlock which issues certificates via Let's Encrypt™ v2

A less insecure way to fix this:

'use strict';

var request = require('request');
var agentOptions;
var agent;

agentOptions = {
  host: 'www.example.com'
, port: '443'
, path: '/'
, rejectUnauthorized: false
};

agent = new https.Agent(agentOptions);

request({
  url: "https://www.example.com/api/endpoint"
, method: 'GET'
, agent: agent
}, function (err, resp, body) {
  // ...
});

By using an agent with rejectUnauthorized you at least limit the security vulnerability to the requests that deal with that one site instead of making your entire node process completely, utterly insecure.

Other Options

If you were using a self-signed cert you would add this option:

agentOptions.ca = [ selfSignedRootCaPemCrtBuffer ];

For trusted-peer connections you would also add these 2 options:

agentOptions.key = clientPemKeyBuffer;
agentOptions.cert = clientPemCrtSignedBySelfSignedRootCaBuffer;

Bad Idea

It's unfortunate that process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; is even documented. It should only be used for debugging and should never make it into in sort of code that runs in the wild. Almost every library that runs atop https has a way of passing agent options through. Those that don't should be fixed.

How to download file from database/folder using php

butangDonload.php

$file = "Bang.png"; //Let say If I put the file name Bang.png
$_SESSION['name']=$file;    

Try this,

<?php

$name=$_SESSION['name'];
download($name);

function download($name){
$file = $nama_fail;
?>

Could not resolve placeholder in string value

With Spring Boot :

In the pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <addResources>true</addResources>
            </configuration>
        </plugin>
    </plugins>
</build>

Example in class Java

@Configuration
@Slf4j
public class MyAppConfig {
    @Value("${foo}")
    private String foo;
    @Value("${bar}")
    private String bar;
    @Bean("foo")
    public String foo() {
        log.info("foo={}", foo);
        return foo;
    }
    @Bean("bar")
    public String bar() {
        log.info("bar={}", bar);
        return bar;
    }
    [ ... ]

In the properties files :

src/main/resources/application.properties

foo=all-env-foo

src/main/resources/application-rec.properties

bar=rec-bar

src/main/resources/application-prod.properties

bar=prod-bar

In the VM arguments of Application.java

-Dspring.profiles.active=[rec|prod]

Don't forget to run mvn command after modifying the properties !

mvn clean package -Dmaven.test.skip=true

In the log file for -Dspring.profiles.active=rec :

The following profiles are active: rec
foo=all-env-foo
bar=rec-bar

In the log file for -Dspring.profiles.active=prod :

The following profiles are active: prod
foo=all-env-foo
bar=prod-bar

In the log file for -Dspring.profiles.active=local :

Could not resolve placeholder 'bar' in value "${bar}"

Oups, I forget to create application-local.properties.

How to set max_connections in MySQL Programmatically

How to change max_connections

You can change max_connections while MySQL is running via SET:

mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 5000  |
+-----------------+-------+
1 row in set (0.00 sec)

To OP

timeout related

I had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.

I suggest that you increase this value to 100k or disable connection pooling Pooling=false

UPDATED

he has two questions.

Q1 - what happens if I disable pooling Slow down making DB connection. connection pooling is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool

Q2 - Can the value of pooling be increased or the maximum is 100?

you can increase but I'm sure what is MAX value, maybe max_connections in my.cnf

My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.

If you have Stress Test tool like JMeter you can test youself.

How to build a 'release' APK in Android Studio?

Click \Build\Select Build Variant... in Android Studio. And choose release.

Difference between Role and GrantedAuthority in Spring Security

AFAIK GrantedAuthority and roles are same in spring security. GrantedAuthority's getAuthority() string is the role (as per default implementation SimpleGrantedAuthority).

For your case may be you can use Hierarchical Roles

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
    <constructor-arg ref="roleHierarchy" />
</bean>
<bean id="roleHierarchy"
        class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
    <property name="hierarchy">
        <value>
            ROLE_ADMIN > ROLE_createSubUsers
            ROLE_ADMIN > ROLE_deleteAccounts 
            ROLE_USER > ROLE_viewAccounts
        </value>
    </property>
</bean>

Not the exact sol you looking for, but hope it helps

Edit: Reply to your comment

Role is like a permission in spring-security. using intercept-url with hasRole provides a very fine grained control of what operation is allowed for which role/permission.

The way we handle in our application is, we define permission (i.e. role) for each operation (or rest url) for e.g. view_account, delete_account, add_account etc. Then we create logical profiles for each user like admin, guest_user, normal_user. The profiles are just logical grouping of permissions, independent of spring-security. When a new user is added, a profile is assigned to it (having all permissible permissions). Now when ever user try to perform some action, permission/role for that action is checked against user grantedAuthorities.

Also the defaultn RoleVoter uses prefix ROLE_, so any authority starting with ROLE_ is considered as role, you can change this default behavior by using a custom RolePrefix in role voter and using it in spring security.

Using Cookie in Asp.Net Mvc 4

userCookie.Expires.AddDays(365); 

This line of code doesn't do anything. It is the equivalent of:

DateTime temp = userCookie.Expires.AddDays(365); 
//do nothing with temp

You probably want

userCookie.Expires = DateTime.Now.AddDays(365); 

What is the right way to POST multipart/form-data using curl?

I had a hard time sending a multipart HTTP PUT request with curl to a Java backend. I simply tried

curl -X PUT URL \
   --header 'Content-Type: multipart/form-data; boundary=---------BOUNDARY' \
   --data-binary @file

and the content of the file was

-----------BOUNDARY
Content-Disposition: form-data; name="name1"
Content-Type: application/xml;version=1.0;charset=UTF-8

<xml>content</xml>
-----------BOUNDARY
Content-Disposition: form-data; name="name2"
Content-Type: text/plain

content
-----------BOUNDARY--

but I always got an error that the boundary was incorrect. After some Java backend debugging I found out that the Java implementation was adding a \r\n-- as a prefix to the boundary, so after changing my input file to

                          <-- here's the CRLF
-------------BOUNDARY       <-- added '--' at the beginning
...
-------------BOUNDARY       <-- added '--' at the beginning
...
-------------BOUNDARY--     <-- added '--' at the beginning

everything works fine!

tl;dr

Add a newline (CRLF \r\n) at the beginning of the multipart boundary content and -- at the beginning of the boundaries and try again.

Maybe you are sending a request to a Java backend that needs this changes in the boundary.

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

Just add this to your Application_OnBeginRequest method (this will enable CORS support globally for your application) and "handle" preflight requests :

var res = HttpContext.Current.Response;
var req = HttpContext.Current.Request;
res.AppendHeader("Access-Control-Allow-Origin", req.Headers["Origin"]);
res.AppendHeader("Access-Control-Allow-Credentials", "true");
res.AppendHeader("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name");
res.AppendHeader("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");

// ==== Respond to the OPTIONS verb =====
if (req.HttpMethod == "OPTIONS")
{
    res.StatusCode = 200;
    res.End();
}

* security: be aware that this will enable ajax requests from anywhere to your server (you can instead only allow a comma separated list of Origins/urls if you prefer).

I used current client origin instead of * because this will allow credentials => setting Access-Control-Allow-Credentials to true will enable cross browser session managment

also you need to enable delete and put, patch and options verbs in your webconfig section system.webServer, otherwise IIS will block them :

<handlers>
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

hope this helps

PowerShell Connect to FTP server and get files

Based on Why does FtpWebRequest download files from the root directory? Can this cause a 553 error?, I wrote a PowerShell script that enabled to download a file from a FTP-Server via explicit FTP over TLS:

# Config
$Username = "USERNAME"
$Password = "PASSWORD"
$LocalFile = "C:\PATH_TO_DIR\FILNAME.EXT"
#e.g. "C:\temp\somefile.txt"
$RemoteFile = "ftp://PATH_TO_REMOTE_FILE"
#e.g. "ftp://ftp.server.com/home/some/path/somefile.txt"

try{ 
    # Create a FTPWebRequest
    $FTPRequest = [System.Net.FtpWebRequest]::Create($RemoteFile)
    $FTPRequest.Credentials = New-Object System.Net.NetworkCredential($Username,$Password)
    $FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
    $FTPRequest.UseBinary = $true
    $FTPRequest.KeepAlive = $false
    $FTPRequest.EnableSsl  = $true
    # Send the ftp request
    $FTPResponse = $FTPRequest.GetResponse()
    # Get a download stream from the server response
    $ResponseStream = $FTPResponse.GetResponseStream()
    # Create the target file on the local system and the download buffer
    $LocalFileFile = New-Object IO.FileStream ($LocalFile,[IO.FileMode]::Create)
    [byte[]]$ReadBuffer = New-Object byte[] 1024
    # Loop through the download

    do {
        $ReadLength = $ResponseStream.Read($ReadBuffer,0,1024)
        $LocalFileFile.Write($ReadBuffer,0,$ReadLength)
    }
    while ($ReadLength -ne 0)
}catch [Exception]
{
    $Request = $_.Exception
    Write-host "Exception caught: $Request"
}

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 resolve DTS_E_OLEDBERROR. in ssis

Knowing the version of Windows and SQL Server might be helpful in some cases. From the Native Client 10.0 I infer either SQL Server 2008 or SQL Server 2008 R2.

There are a few possible things to check, but I would check to see if 'priority boost' was configured on the SQL Server. This is a deprecated setting and will eventually be removed. The problem is that it can rob the operating system of needed resources. See the notes at:

http://msdn.microsoft.com/en-in/library/ms180943(v=SQL.105).aspx

If 'priority boost' has been configured to 1, then get it configured back to 0.

exec sp_configure 'priority boost', 0;
RECONFIGURE;

Forms authentication timeout vs sessionState timeout

      <sessionState timeout="2" />
      <authentication mode="Forms">
          <forms name="userLogin" path="/" timeout="60" loginUrl="Login.aspx" slidingExpiration="true"/>
      </authentication>

This configuration sends me to the login page every two minutes, which seems to controvert the earlier answers

Importing the private-key/public-certificate pair in the Java KeyStore

With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.

# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12

# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert

To verify the contents of the JKS, you can use this command:

keytool -list -v -keystore mykeystore.jks

If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.

Refresh Page and Keep Scroll Position

document.location.reload() stores the position, see in the docs.

Add additional true parameter to force reload, but without restoring the position.

document.location.reload(true)

MDN docs:

The forcedReload flag changes how some browsers handle the user's scroll position. Usually reload() restores the scroll position afterward, but forced mode can scroll back to the top of the page, as if window.scrollY === 0.

Best way to disable button in Twitter's Bootstrap

For input and button:

$('button').prop('disabled', true);

For anchor:

$('a').attr('disabled', true);

Checked in firefox, chrome.

See http://jsfiddle.net/czL54/2/

Differences between hard real-time, soft real-time, and firm real-time?

real-time - Pertaining to a system or mode of operation in which computation is performed during the actual time that an external process occurs, in order that the computation results can be used to control, monitor, or respond to the external process in a timely manner. [IEEE Standard 610.12.1990]

I know this definition is old, very old. I can't, however, find a more recent definition by the IEEE (Institute of Electrical and Electronics Engineers).

Difference between Subquery and Correlated Subquery

Above example is not Co-related Sub-Query. It is Derived Table / Inline-View since i.e, a Sub-query within FROM Clause.

A Corelated Sub-query should refer its parent(main Query) Table in it. For example See find the Nth max salary by Co-related Sub-query:

SELECT Salary 
FROM Employee E1
WHERE N-1 = (SELECT COUNT(*)
             FROM Employee E2
             WHERE E1.salary <E2.Salary) 

Co-Related Vs Nested-SubQueries.

Technical difference between Normal Sub-query and Co-related sub-query are:

1. Looping: Co-related sub-query loop under main-query; whereas nested not; therefore co-related sub-query executes on each iteration of main query. Whereas in case of Nested-query; subquery executes first then outer query executes next. Hence, the maximum no. of executes are NXM for correlated subquery and N+M for subquery.

2. Dependency(Inner to Outer vs Outer to Inner): In the case of co-related subquery, inner query depends on outer query for processing whereas in normal sub-query, Outer query depends on inner query.

3.Performance: Using Co-related sub-query performance decreases, since, it performs NXM iterations instead of N+M iterations. ¨ Co-related Sub-query Execution.

For more information with examples :

http://dotnetauthorities.blogspot.in/2013/12/Microsoft-SQL-Server-Training-Online-Learning-Classes-Sql-Sub-Queries-Nested-Co-related.html

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Check that you have the correct rights set on CA certificates bundle. Usually, that means read access for everyone to CA files in the /etc/ssl/certs directory, for instance /etc/ssl/certs/ca-certificates.crt.

You can see what files have been configured for you curl version with the

curl-config --configure
command :

$ curl-config --configure
 '--prefix=/usr' 
 '--mandir=/usr/share/man' 
 '--disable-dependency-tracking' 
 '--disable-ldap' 
 '--disable-ldaps' 
 '--enable-ipv6' 
 '--enable-manual' 
 '--enable-versioned-symbols' 
 '--enable-threaded-resolver' 
 '--without-libidn' 
 '--with-random=/dev/urandom' 
 '--with-ca-bundle=/etc/ssl/certs/ca-certificates.crt' 
 'CFLAGS=-march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4' 'LDFLAGS=-Wl,-O1,--sort-common,--as-needed,-z,relro' 
 'CPPFLAGS=-D_FORTIFY_SOURCE=2'

Here you need read access to /etc/ssl/certs/ca-certificates.crt

$ curl-config --configure
 '--build' 'i486-linux-gnu' 
 '--prefix=/usr' 
 '--mandir=/usr/share/man' 
 '--disable-dependency-tracking' 
 '--enable-ipv6' 
 '--with-lber-lib=lber' 
 '--enable-manual' 
 '--enable-versioned-symbols' 
 '--with-gssapi=/usr' 
 '--with-ca-path=/etc/ssl/certs' 
 'build_alias=i486-linux-gnu' 
 'CFLAGS=-g -O2' 
 'LDFLAGS=' 
 'CPPFLAGS='

And the same here.

Parsing jQuery AJAX response

Imagine that this is your Json response

{"Visit":{"VisitId":8,"Description":"visit8"}}

This is how you parse the response and access the values

    Ext.Ajax.request({
    headers: {
        'Content-Type': 'application/json'
    },
    url: 'api/fullvisit/getfullvisit/' + visitId,
    method: 'GET',
    dataType: 'json',
    success: function (response, request) {
        obj = JSON.parse(response.responseText);
        alert(obj.Visit.VisitId);
    }
});

This will alert the VisitId field

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.

The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)

From: http://technet.microsoft.com/en-us/library/ee681792.aspx:

"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."

Edit: Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE returned.

If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll.

Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206

I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.

Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.

How to "EXPIRE" the "HSET" child key in redis?

You can use Sorted Set in redis to get a TTL container with timestamp as score. For example, whenever you insert a event string into the set you can set its score to the event time. Thus you can get data of any time window by calling zrangebyscore "your set name" min-time max-time

Moreover, we can do expire by using zremrangebyscore "your set name" min-time max-time to remove old events.

The only drawback here is you have to do housekeeping from an outsider process to maintain the size of the set.

Win32Exception (0x80004005): The wait operation timed out

EfCore version of @JonSchneider's answer

myDbContext.Database.SetCommandTimeout(999);

Where myDbContext is your DbContext instance, and 999 is the timeout value in seconds.

(Syntax current as of Entity Framework Core 3.1)

Go: panic: runtime error: invalid memory address or nil pointer dereference

for me one solution for this problem was to add in sql.Open ... sslmode=disable

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Jackson serialization: ignore empty values (or null)

For jackson 2.x

@JsonInclude(JsonInclude.Include.NON_NULL)

just before the field.

Xcode Product -> Archive disabled

In addition to the generic device (or "Any iOS Device" in newer versions of Xcode) mentioned in the other answers, it is possible that the "Archive" action is not selected for the current target in the scheme.

To view and edit at the current scheme, select Product > Schemes > Edit Scheme... (Cmd+<), then make sure that the "Archive" action is checked in the line corresponding to the desired target.

In the image below, Archive is not checked and the Archive action is greyed out in the Product menu. Checking the indicated checkbox fixed the issue for me.

scheme settings

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

You are not allowed to have a CNAME record for the domain, as the CNAME is an aliasing feature that covers all data types (regardless of whether the client looks for MX, NS or SOA records). CNAMEs also always refer to a new name, not an ip-address, so there are actually two errors in the single line

@                        IN CNAME   88.198.38.XXX

Changing that CNAME to an A record should make it work, provided the ip-address you use is the correct one for your Heroku app.

The only correct way in DNS to make a simple domain.com name work in the browser, is to point the domain to an IP-adress with an A record.

java Compare two dates

Read JavaDocs.

Use method:

 Date.compareTo()

How to Solve Max Connection Pool Error

Here's what u can also try....

run your application....while it is still running launch your command prompt

while your application is running type netstat -n on the command prompt. You should see a list of TCP/IP connections. Check if your list is not very long. Ideally you should have less than 5 connections in the list. Check the status of the connections.
If you have too many connections with a TIME_WAIT status it means the connection has been closed and is waiting for the OS to release the resources. If you are running on Windows, the default ephemeral port rang is between 1024 and 5000 and the default time it takes Windows to release the resource from TIME_WAIT status is 4 minutes. So if your application used more then 3976 connections in less then 4 minutes, you will get the exception you got.

Suggestions to fix it:

  1. Add a connection pool to your connection string.

If you continue to receive the same error message (which is highly unlikely) you can then try the following: (Please don't do it if you are not familiar with the Windows registry)

  1. Run regedit from your run command. In the registry editor look for this registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters:

Modify the settings so they read:

MaxUserPort = dword:00004e20 (10,000 decimal) TcpTimedWaitDelay = dword:0000001e (30 decimal)

This will increase the number of ports to 10,000 and reduce the time to release freed tcp/ip connections.

Only use suggestion 2 if 1 fails.

Thank you.

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

I had a similar issue. the error comes up when the i switched the fb user from setting. Facebook authorization fails on iOS6 when switching FB account on device This solved my problem

Using Python Requests: Sessions, Cookies, and POST

I don't know how stubhub's api works, but generally it should look like this:

s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)

Now your session contains cookies provided by login form. To access cookies of this session simply use

s.cookies

Any further actions like another requests will have this cookie

Export MySQL data to Excel in PHP

Posts by John Peter and Dileep kurahe helped me to develop what I consider as being a simpler and cleaner solution, just in case anyone else is still looking. (I am not showing any database code because I actually used a $_SESSION variable.)

The above solutions invariably caused an error upon loading in Excel, about the extension not matching the formatting type. And some of these solutions create a spreadsheet with the data across the page in columns where it would be more traditional to have column headings and list the data down the rows. So here is my simple solution:

$filename = "webreport.csv";
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename");  
header("Pragma: no-cache"); 
header("Expires: 0");
foreach($results as $x => $x_value){
    echo '"'.$x.'",' . '"'.$x_value.'"' . "\r\n";
}
  1. Change to .csv (which Excel instantly updates to .xls and there is no error upon loading.)
  2. Use the comma as delimiter.
  3. Double quote the Key and Value to escape any commas in the data.
  4. I also prepended column headers to $results so the spreadsheet looked even nicer.

Get JSON object from URL

$url = 'http://.../.../yoururl/...';
$obj = json_decode(file_get_contents($url), true);
echo $obj['access_token'];

Php also can use properties with dashes:

garex@ustimenko ~/src/ekapusta/deploy $ psysh
Psy Shell v0.4.4 (PHP 5.5.3-1ubuntu2.6 — cli) by Justin Hileman
>>> $q = new stdClass;
=> <stdClass #000000005f2b81c80000000076756fef> {}
>>> $q->{'qwert-y'} = 123
=> 123
>>> var_dump($q);
class stdClass#174 (1) {
  public $qwert-y =>
  int(123)
}
=> null

C# refresh DataGridView when updating or inserted on another form

For datagridview in C#, use this code

con.Open();
MySqlDataAdapter MyDA = new MySqlDataAdapter();
string sqlSelectAll = "SELECT * from dailyprice";
MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, con);

DataTable table = new DataTable();
MyDA.Fill(table);

BindingSource bSource = new BindingSource();
bSource.DataSource = table;


dataGridView1.DataSource = bSource;
con.Close();

It works for show new records in the datagridview.

An Authentication object was not found in the SecurityContext - Spring 3.2.2

As pointed already by @Arun P Johny the root cause of the problem is that at the moment when AuthenticationSuccessEvent is processed SecurityContextHolder is not populated by Authentication object. So any declarative authorization checks (that must get user rights from SecurityContextHolder) will not work. I give you another idea how to solve this problem. There are two ways how you can run your custom code immidiately after successful authentication:

  1. Listen to AuthenticationSuccessEvent
  2. Provide your custom AuthenticationSuccessHandler implementation.

AuthenticationSuccessHandler has one important advantage over first way: SecurityContextHolder will be already populated. So just move your stateService.rowCount() call into loginsuccesshandler.LoginSuccessHandler#onAuthenticationSuccess(...) method and the problem will go away.

Connection to SQL Server Works Sometimes

I had the same problem, trying to connect to a server in a local network (through VPN) from Visual Studio, while setting up an Entity Data Model.
Managed to solve only by setting TransparentNetworkIPResolution=false in the connection string. In VS Add Connection Wizard, you can find it in the Advanced tab.

How do I disable the security certificate check in Python requests

Use requests.packages.urllib3.disable_warnings() and verify=False on requests methods.

import requests
from urllib3.exceptions import InsecureRequestWarning

# Suppress only the single warning from urllib3 needed.
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

# Set `verify=False` on `requests.post`.
requests.post(url='https://example.com', data={'bar':'baz'}, verify=False)

PowerShell: Create Local User Account

As of 2014, here is a statement from a Microsoft representative (the Scripting Guy):

As much as we might hate to admit it, there are still no Windows PowerShell cmdlets from Microsoft that permit creating local user accounts or local user groups. We finally have a Desired State Configuration (DSC ) provider that can do this—but to date, no cmdlets.

Git log to get commits only for a specific branch

From what it sounds like you should be using cherry:

git cherry -v develop mybranch

This would show all of the commits which are contained within mybranch, but NOT in develop. If you leave off the last option (mybranch), it will compare the current branch instead.

As VonC pointed out, you are ALWAYS comparing your branch to another branch, so know your branches and then choose which one to compare to.

how to generate a unique token which expires after 24 hours?

There are two possible approaches; either you create a unique value and store somewhere along with the creation time, for example in a database, or you put the creation time inside the token so that you can decode it later and see when it was created.

To create a unique token:

string token = Convert.ToBase64String(Guid.NewGuid().ToByteArray());

Basic example of creating a unique token containing a time stamp:

byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] key = Guid.NewGuid().ToByteArray();
string token = Convert.ToBase64String(time.Concat(key).ToArray());

To decode the token to get the creation time:

byte[] data = Convert.FromBase64String(token);
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
if (when < DateTime.UtcNow.AddHours(-24)) {
  // too old
}

Note: If you need the token with the time stamp to be secure, you need to encrypt it. Otherwise a user could figure out what it contains and create a false token.

Can I limit the length of an array in JavaScript?

arr.length = Math.min(arr.length, 5)

"The semaphore timeout period has expired" error for USB connection

I had this problem as well on two different Windows computers when communicating with a Arduino Leonardo. The reliable solution was:

  • Find the COM port in device manager and open the device properties.
  • Open the "Port Settings" tab, and click the advanced button.
  • There, uncheck the box "Use FIFO buffers (required 16550 compatible UART), and press OK.

Unfortunately, I don't know what this feature does, or how it affects this issue. After several PC restarts and a dozen device connection cycles, this is the only thing that reliably fixed the issue.

Add Expires headers

In ASP.NET there is similar object, you can use Caching Portions in WebFormsUserControls in order to cache objects of a page for a period of time and save server resources. This is also known as fragment caching.
If you include this code to top of your user control, a version of the control stored in the output cache for 150 seconds. You can create your own control that would contain expire header for a specific resource you want.

<%@ OutputCache Duration="150" VaryByParam="None" %>

This article explain it completely: Caching Portions of an ASP.NET Page

How to redirect to logon page when session State time out is completed in asp.net mvc

I discover very simple way to redirect Login Page When session end in MVC. I have already tested it and this works without problems.

In short, I catch session end in _Layout 1 minute before and make redirection.

I try to explain everything step by step.

If we want to session end 30 minute after and redirect to loginPage see this steps:

  1. Change the web config like this (set 31 minute):

     <system.web>
        <sessionState timeout="31"></sessionState>
     </system.web>
    
  2. Add this JavaScript in _Layout (when session end 1 minute before this code makes redirect, it makes count time after user last action, not first visit on site)

    <script>
        //session end 
        var sessionTimeoutWarning = @Session.Timeout- 1;
    
        var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
        setTimeout('SessionEnd()', sTimeout);
    
        function SessionEnd() {
            window.location = "/Account/LogOff";
        }
    </script>
    
  3. Here is my LogOff Action, which makes only LogOff and redirect LoginIn Page

    public ActionResult LogOff()
    {
        Session["User"] = null; //it's my session variable
        Session.Clear();
        Session.Abandon();
        FormsAuthentication.SignOut(); //you write this when you use FormsAuthentication
        return RedirectToAction("Login", "Account");
    } 
    

I hope this is a very useful code for you.

OAuth2 and Google API: access token expiration time?

The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time

phpmyadmin logs out after 1440 secs

You can change the cookie time session feature at phpmyadmin web interface

Settings->Features->General->Login cookie validity

OR

If you want to change the 'login cookie validity' in configuration file, then open the phpmMyAdmin configuration file, config.inc.php in the root directory of PHPMyAdmin.(root directory is usually /etc/phpmyadmin/)

After locating the config.inc.php , search for the line below and set it to the value of seconds you want phpmyadmin to timeout:

$cfg['LoginCookieValidity'] 

or

Add the following:

$cfg[ ' Servers'] [$i] [ ' LoginCookieValidity' ] = <your_new_timeout>;

For example:

$cfg[ ' Servers'] [$i] [ ' LoginCookieValidity' ] = <3600 * 3 >;

The Timeout is set to 3 Hours from the Example above.

session.gc_maxlifetime might limit session validity and if the session is lost, the login cookie is also invalidated. So, we may need to set the session.gc_maxlifetime in php.ini configuration file(file location is /etc/php5 /apache2/php.ini in ubuntu).

session.gc_maxlifetime = 3600 * 3


phpMyAdmin Documentation on LoginCookieValidity

$cfg['LoginCookieValidity']

Type: integer [number of seconds]
Default value: 1440

Define how long a login cookie is valid. Please note that php configuration option session.gc_maxlifetime might limit session validity and if the session is lost, the login cookie is also invalidated. So it is a good idea to set session.gc_maxlifetime at least to the same value of $cfg['LoginCookieValidity'].

NOTE:

  1. If your server crashed and cannot load your phpmyadmin page, check your apache log at /var/log/apache2/error.log. If you got PHP Fatal error: Call to a member function get() on a non-object in /path/to/phpmyadmin/libraries/Header.class.php on line 135, then do a chmod 644 config.inc.php. that should take care of the error.
  2. You will then get another warning: Your PHP parameter session.gc_maxlifetime is lower that cookie validity configured in phpMyAdmin, because of this, your login will expire sooner than configured in phpMyAdmin.. then change the session.gc_maxlifetime as mentioned above.

401 Unauthorized: Access is denied due to invalid credentials

In my case,
My application is developed in MVC and my home controller class was decorated with [Authorize] which was causing this issue.
So I've removed it because my application don't require any authentication.

javascript set cookie with expire time

I use a function to store cookies with a custom expire time in days:

// use it like: writeCookie("mycookie", "1", 30)
// this will set a cookie for 30 days since now
function writeCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

PHP Array to CSV

In my case, my array was multidimensional, potentially with arrays as values. So I created this recursive function to blow apart the array completely:

function array2csv($array, &$title, &$data) {
    foreach($array as $key => $value) {      
        if(is_array($value)) {
            $title .= $key . ",";
            $data .= "" . ",";
            array2csv($value, $title, $data);
        } else {
            $title .= $key . ",";
            $data .= '"' . $value . '",';
        }
    }
}

Since the various levels of my array didn't lend themselves well to a the flat CSV format, I created a blank column with the sub-array's key to serve as a descriptive "intro" to the next level of data. Sample output:

agentid     fname           lname      empid    totals  sales   leads   dish    dishnet top200_plus top120  latino  base_packages
G-adriana   ADRIANA EUGENIA PALOMO PAIZ 886                0    19              0         0         0         0      0

You could easily remove that "intro" (descriptive) column, but in my case I had repeating column headers, i.e. inbound_leads, in each sub-array, so that gave me a break/title preceding the next section. Remove:

$title .= $key . ",";
$data .= "" . ",";

after the is_array() to compact the code further and remove the extra column.

Since I wanted both a title row and data row, I pass two variables into the function and upon completion of the call to the function, terminate both with PHP_EOL:

$title .= PHP_EOL;
$data .= PHP_EOL;

Yes, I know I leave an extra comma, but for the sake of brevity, I didn't handle it here.

Keeping session alive with Curl and PHP

You have correctly used "CURLOPT_COOKIEJAR" (writing) but you also need to set "CURLOPT_COOKIEFILE" (reading)

curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE); 
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE); 

Rewrite all requests to index.php with nginx

Here's the answer of your 2nd question :

   location / {
        rewrite ^/(.*)$ /$1.php last;
}

it's work for me (based my experience), means that all of your blabla.php will rewrite into blabla

like http://yourwebsite.com/index.php to http://yourwebsite.com/index

What is Cache-Control: private?

To answer your question about why caching is working, even though the web-server didn't include the headers:

  • Expires: [a date]
  • Cache-Control: max-age=[seconds]

The server kindly asked any intermediate proxies to not cache the contents (i.e. the item should only be cached in a private cache, i.e. only on your own local machine):

  • Cache-Control: private

But the server forgot to include any sort of caching hints:

  • they forgot to include Expires, so the browser knows to use the cached copy until that date
  • they forgot to include Max-Age, so the browser knows how long the cached item is good for
  • they forgot to include E-Tag, so the browser can do a conditional request

But they did include a Last-Modified date in the response:

Last-Modified: Tue, 16 Oct 2012 03:13:38 GMT

Because the browser knows the date the file was modified, it can perform a conditional request. It will ask the server for the file, but instruct the server to only send the file if it has been modified since 2012/10/16 3:13:38:

GET / HTTP/1.1
If-Modified-Since: Tue, 16 Oct 2012 03:13:38 GMT

The server receives the request, realizes that the client has the most recent version already. Rather than sending the client 200 OK, followed by the contents of the page, instead it tells you that your cached version is good:

304 Not Modified

Your browser did have to suffer the delay of sending a request to the server, and wait for a response, but it did save having to re-download the static content.

Why Max-Age? Why Expires?

Because Last-Modified sucks.

Not everything on the server has a date associated with it. If I'm building a page on the fly, there is no date associated with it - it's now. But I'm perfectly willing to let the user cache the homepage for 15 seconds:

200 OK
Cache-Control: max-age=15

If the user hammers F5, they'll keep getting the cached version for 15 seconds. If it's a corporate proxy, then all 67198 users hitting the same page in the same 15-second window will all get the same contents - all served from close cache. Performance win for everyone.

The virtue of adding Cache-Control: max-age is that the browser doesn't even have to perform a conditional request.

  • if you specified only Last-Modified, the browser has to perform a request If-Modified-Since, and watch for a 304 Not Modified response
  • if you specified max-age, the browser won't even have to suffer the network round-trip; the content will come right out of the caches

The difference between "Cache-Control: max-age" and "Expires"

Expires is a legacy equivalent of the modern (c. 1998) Cache-Control: max-age header:

  • Expires: you specify a date (yuck)
  • max-age: you specify seconds (goodness)
  • And if both are specified, then the browser uses max-age:

    200 OK
    Cache-Control: max-age=60
    Expires: 20180403T192837 
    

Any web-site written after 1998 should not use Expires anymore, and instead use max-age.

What is ETag?

ETag is similar to Last-Modified, except that it doesn't have to be a date - it just has to be a something.

If I'm pulling a list of products out of a database, the server can send the last rowversion as an ETag, rather than a date:

200 OK
ETag: "247986"

My ETag can be the SHA1 hash of a static resource (e.g. image, js, css, font), or of the cached rendered page (i.e. this is what the Mozilla MDN wiki does; they hash the final markup):

200 OK
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"

And exactly like in the case of a conditional request based on Last-Modified:

GET / HTTP/1.1
If-Modified-Since: Tue, 16 Oct 2012 03:13:38 GMT

304 Not Modified

I can perform a conditional request based on the ETag:

GET / HTTP/1.1
If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4"

304 Not Modified

An ETag is superior to Last-Modified because it works for things besides files, or things that have a notion of date. It just is

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

<configuration>
 <location path="Path/To/Public/Folder">
  <system.web>
     <authorization>
        <allow users="?"/>
     </authorization>
  </system.web>
 </location>
</configuration>

What is the functionality of setSoTimeout and how it works?

Does it mean that I'm blocking reading any input from the Server/Client for this socket for 2000 millisecond and after this time the socket is ready to read data?

No, it means that if no data arrives within 2000ms a SocketTimeoutException will be thrown.

What does it mean timeout expire?

It means the 2000ms (in your case) elapses without any data arriving.

What is the option which must be enabled prior to blocking operation?

There isn't one that 'must be' enabled. If you mean 'may be enabled', this is one of them.

Infinite Timeout menas that the socket does't read anymore?

What a strange suggestion. It means that if no data ever arrives you will block in the read forever.

Throw HttpResponseException or return Request.CreateErrorResponse?

As far as I can tell, whether you throw an exception, or you return Request.CreateErrorResponse, the result is the same. If you look at the source code for System.Web.Http.dll, you will see as much. Take a look at this general summary, and a very similar solution that I have made: Web Api, HttpError, and the behavior of exceptions

Create a zip file and download it

One of the error could be that the file is not read as 'archive' format. check out ZipArchive not opening file - Error Code: 19. Open the downloaded file in text editor, if you have any html tags or debug statements at the starting, clear the buffer before reading the file.

ob_clean();
flush();
readfile("$archive_file_name");

Converting a JToken (or string) to a given Type

System.Convert.ChangeType(jtoken.ToString(), targetType);

or

JsonConvert.DeserializeObject(jtoken.ToString(), targetType);

--EDIT--

Uzair, Here is a complete example just to show you they work

string json = @"{
        ""id"" : 77239923,
        ""username"" : ""UzEE"",
        ""email"" : ""[email protected]"",
        ""name"" : ""Uzair Sajid"",
        ""twitter_screen_name"" : ""UzEE"",
        ""join_date"" : ""2012-08-13T05:30:23Z05+00"",
        ""timezone"" : 5.5,
        ""access_token"" : {
            ""token"" : ""nkjanIUI8983nkSj)*#)(kjb@K"",
            ""scope"" : [ ""read"", ""write"", ""bake pies"" ],
            ""expires"" : 57723
        },
        ""friends"" : [{
            ""id"" : 2347484,
            ""name"" : ""Bruce Wayne""
        },
        {
            ""id"" : 996236,
            ""name"" : ""Clark Kent""
        }]
    }";

var obj = (JObject)JsonConvert.DeserializeObject(json);
Type type = typeof(int);
var i1 = System.Convert.ChangeType(obj["id"].ToString(), type);
var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);

Error message "Forbidden You don't have permission to access / on this server"

I solved my problem by adding my user to httpd.conf.

# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
#User daemon
User my_username
Group daemon

Not receiving Google OAuth refresh token

Using offline access and prompt:consent worked well to me:

   auth2 = gapi.auth2.init({
                    client_id: '{cliend_id}' 
   });

   auth2.grantOfflineAccess({prompt:'consent'}).then(signInCallback); 

Display PNG image as response to jQuery AJAX request

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

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

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

error: the details of the application error from being viewed remotely

Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.

Details: To enable the details of this specific error message to be viewable on remote machines, please create a tag within a "web.config" configuration file located in the root directory of the current web application. This tag should then have its "mode" attribute set to "Off".

Proper way to renew distribution certificate for iOS

When your certificate expires, it simply disappears from the ‘Certificates, Identifier & Profiles’ section of Member Center. There is no ‘Renew’ button that allows you to renew your certificate. You can revoke a certificate and generate a new one before it expires. Or you can wait for it to expire and disappear, then generate a new certificate. In Apple's App Distribution Guide:

Replacing Expired Certificates

When your development or distribution certificate expires, remove it and request a new certificate in Xcode.

When your certificate expires or is revoked, any provisioning profile that made use of the expired/revoked certificate will be reflected as ‘Invalid’. You cannot build and sign any app using these invalid provisioning profiles. As you can imagine, I'd rather revoke and regenerate a certificate before it expires.

Q: If I do that then will all my live apps be taken down?

Apps that are already on the App Store continue to function fine. Again, in Apple's App Distribution Guide:

Important: Re-creating your development or distribution certificates doesn’t affect apps that you’ve submitted to the store nor does it affect your ability to update them.

So…

Q: How to I properly renew it?

As mentioned above, there is no renewing of certificates. Follow the steps below to revoke and regenerate a new certificate, along with the affected provisioning profiles. The instructions have been updated for Xcode 8.3 and Xcode 9.

Step 1: Revoke the expiring certificate

Login to Member Center > Certificates, Identifiers & Profiles, select the expiring certificate. Take note of the expiry date of the certificate, and click the ‘Revoke’ button.

Select the expiring certificate and click the Revoke button

Step 2: (Optional) Remove the revoked certificate from your Keychain

Optionally, if you don't want to have the revoked certificate lying around in your system, you can delete them from your system. Unfortunately, the ‘Delete Certificate’ function in Xcode > Preferences > Accounts > [Apple ID] > Manage Certificates… seems to be always disabled, so we have to delete them manually using Keychain Access.app (/Applications/Utilities/Keychain Access.app).

Optionally remove the revoked certificate using Keychain Access.app

Filter by ‘login’ Keychains and ‘Certificates’ Category. Locate the certificate that you've just revoked in Step 1.

Depending on the certificate that you've just revoked, search for either ‘Mac’ or ‘iPhone’. Mac App Store distribution certificates begin with “3rd Party Mac Developer”, and iOS App Store distribution certificates begin with “iPhone Distribution”.

You can locate the revoked certificate based on the team name, the type of certificate (Mac or iOS) and the expiry date of the certificate you've noted down in Step 1.

Step 3: Request a new certificate using Xcode

Under Xcode > Preferences > Accounts > [Apple ID] > Manage Certificates…, click on the ‘+’ button on the lower left, and select the same type of certificate that you've just revoked to let Xcode request a new one for you.

Let Xcode request a new certificate for you in Xcode > Preferences > Accounts > Apple ID > Manage Certificates…

Step 4: Update your provisioning profiles to use the new certificate

After which, head back to Member Center > Certificates, Identifiers & Profiles > Provisioning Profiles > All. You'll notice that any provisioning profile that made use of the revoked certificate is now reflected as ‘Invalid’.

Notice that any provisioning profile that made use of the revoked certificate is now reflected as ‘Invalid’

Click on any profile that are now ‘Invalid’, click ‘Edit’, then choose the newly created certificate, then click on ‘Generate’. Repeat this until all provisioning profiles are regenerated with the new certificate.

Choose the newly created certificate, and click on Generate

Step 5: Use Xcode to download the new provisioning profiles

Tip: Before you download the new profiles using Xcode, you may want to clear any existing and possibly invalid provisioning profiles from your Mac. You can do so by removing all the profiles from ~/Library/MobileDevice/Provisioning Profiles

Back in Xcode > Preferences > Accounts > [Apple ID], click on the ‘Download All Profiles’ button to ask Xcode to download all the provisioning profiles from your developer account.

Click Download All Profiles for Xcode to download all the newly generated profiles

Chrome doesn't delete session cookies

I just had this issue. I noticed that even after I closed my browser I had many Chrome processes running. Turns out these were each from my Chrome extension.

Under advanced settings I unchecked 'Continue running background apps when Google Chrome is closed' and my session cookies started working as they should.

Still a pain in the rear for all of us developers that have been coding expecting that session cookies would get cleared when the user is done browsing.

Delete cookie by name?

I'm not really sure if that was the situation with Roundcube version from May '12, but for current one the answer is that you can't delete roundcube_sessauth cookie from JavaScript, as it is marked as HttpOnly. And this means it's not accessible from JS client side code and can be removed only by server side script or by direct user action (via some browser mechanics like integrated debugger or some plugin).

How to Check whether Session is Expired or not in asp.net

Use Session.Contents.Count:

if (Session.Contents.Count == 0)
{
    Response.Write(".NET session has Expired");
    Response.End();
}
else
{
    InitializeControls();
}

The code above assumes that you have at least one session variable created when the user first visits your site. If you don't have one then you are most likely not using a database for your app. For your case you can just manually assign a session variable using the example below.

protected void Page_Load(object sender, EventArgs e)
{
    Session["user_id"] = 1;
}

Best of luck to you!

Google access token expiration time

From Google OAuth2.0 for Client documentation,

  • expires_in -- The number of seconds left before the token becomes invalid.

How do you cache an image in Javascript

Once an image has been loaded in any way into the browser, it will be in the browser cache and will load much faster the next time it is used whether that use is in the current page or in any other page as long as the image is used before it expires from the browser cache.

So, to precache images, all you have to do is load them into the browser. If you want to precache a bunch of images, it's probably best to do it with javascript as it generally won't hold up the page load when done from javascript. You can do that like this:

function preloadImages(array) {
    if (!preloadImages.list) {
        preloadImages.list = [];
    }
    var list = preloadImages.list;
    for (var i = 0; i < array.length; i++) {
        var img = new Image();
        img.onload = function() {
            var index = list.indexOf(this);
            if (index !== -1) {
                // remove image from the array once it's loaded
                // for memory consumption reasons
                list.splice(index, 1);
            }
        }
        list.push(img);
        img.src = array[i];
    }
}

preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"]);

This function can be called as many times as you want and each time, it will just add more images to the precache.

Once images have been preloaded like this via javascript, the browser will have them in its cache and you can just refer to the normal URLs in other places (in your web pages) and the browser will fetch that URL from its cache rather than over the network.

Eventually over time, the browser cache may fill up and toss the oldest things that haven't been used in awhile. So eventually, the images will get flushed out of the cache, but they should stay there for awhile (depending upon how large the cache is and how much other browsing is done). Everytime the images are actually preloaded again or used in a web page, it refreshes their position in the browser cache automatically so they are less likely to get flushed out of the cache.

The browser cache is cross-page so it works for any page loaded into the browser. So you can precache in one place in your site and the browser cache will then work for all the other pages on your site.


When precaching as above, the images are loaded asynchronously so they will not block the loading or display of your page. But, if your page has lots of images of its own, these precache images can compete for bandwidth or connections with the images that are displayed in your page. Normally, this isn't a noticeable issue, but on a slow connection, this precaching could slow down the loading of the main page. If it was OK for preload images to be loaded last, then you could use a version of the function that would wait to start the preloading until after all other page resources were already loaded.

function preloadImages(array, waitForOtherResources, timeout) {
    var loaded = false, list = preloadImages.list, imgs = array.slice(0), t = timeout || 15*1000, timer;
    if (!preloadImages.list) {
        preloadImages.list = [];
    }
    if (!waitForOtherResources || document.readyState === 'complete') {
        loadNow();
    } else {
        window.addEventListener("load", function() {
            clearTimeout(timer);
            loadNow();
        });
        // in case window.addEventListener doesn't get called (sometimes some resource gets stuck)
        // then preload the images anyway after some timeout time
        timer = setTimeout(loadNow, t);
    }

    function loadNow() {
        if (!loaded) {
            loaded = true;
            for (var i = 0; i < imgs.length; i++) {
                var img = new Image();
                img.onload = img.onerror = img.onabort = function() {
                    var index = list.indexOf(this);
                    if (index !== -1) {
                        // remove image from the array once it's loaded
                        // for memory consumption reasons
                        list.splice(index, 1);
                    }
                }
                list.push(img);
                img.src = imgs[i];
            }
        }
    }
}

preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"], true);
preloadImages(["url99.jpg", "url98.jpg"], true);

PHP-FPM and Nginx: 502 Bad Gateway

I made all this similar tweaks, but from time to time I was getting 501/502 errors (daily).

This are my settings on /etc/php5/fpm/pool.d/www.conf to avoid 501 and 502 nginx errors… The server has 16Gb RAM. This configuration is for a 8Gb RAM server so…

sudo nano /etc/php5/fpm/pool.d/www.conf

then set the following values for

pm.max_children = 70
pm.start_servers = 20
pm.min_spare_servers = 20
pm.max_spare_servers = 35
pm.max_requests = 500

After this changes restart php-fpm

sudo service php-fpm restart

Nginx subdomain configuration

Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines

How can I start and check my MySQL log?

For me, general_log didn't worked. But adding this to my.ini worked

[mysqld]
log-output=FILE
slow_query_log = 1
slow_query_log_file = "d:/temp/developer.log"

PHP Excel Header

You are giving multiple Content-Type headers. application/vnd.ms-excel is enough.

And there are couple of syntax error too. To statement termination with ; on the echo statement and wrong filename extension.

header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=abc.xls");  //File name extension was wrong
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
echo "Some Text"; //no ending ; here

Call a REST API in PHP

If you have a url and your php supports it, you could just call file_get_contents:

$response = file_get_contents('http://example.com/path/to/api/call?param1=5');

if $response is JSON, use json_decode to turn it into php array:

$response = json_decode($response);

if $response is XML, use simple_xml class:

$response = new SimpleXMLElement($response);

http://sg2.php.net/manual/en/simplexml.examples-basic.php

Celery Received unregistered task of type (run example)

If you are using the apps config in installed apps like this:

LOCAL_APPS = [
'apps.myapp.apps.MyAppConfig']

Then in your config app, import the task in ready method like this:

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'apps.myapp'

    def ready(self):
        try:
            import apps.myapp.signals  # noqa F401
            import apps.myapp.tasks
        except ImportError:
            pass

How to refresh token with Google API client?

I used the example by smartcodes with the current version of the Google API, but that one didn't work. I think his API is too outdated.

So, I just wrote my own version, based on one of the API examples... It outputs access token, request token, token type, ID token, expiration time and creation time as strings

If your client credentials and developer key are correct, this code should work out of the box.

<?php
// Call set_include_path() as needed to point to your client library.
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
session_start();

$client = new Google_Client();
$client->setApplicationName("Get Token");
// Visit https://code.google.com/apis/console?api=plus to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$oauth2 = new Google_Oauth2Service($client);

if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    return;
}

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}

if (isset($_REQUEST['logout'])) {
    unset($_SESSION['token']);
    $client->revokeToken();
}
?>
<!doctype html>
<html>
    <head><meta charset="utf-8"></head>
    <body>
        <header><h1>Get Token</h1></header>
        <?php
        if ($client->getAccessToken()) {
            $_SESSION['token'] = $client->getAccessToken();
            $token = json_decode($_SESSION['token']);
            echo "Access Token = " . $token->access_token . '<br/>';
            echo "Refresh Token = " . $token->refresh_token . '<br/>';
            echo "Token type = " . $token->token_type . '<br/>';
            echo "Expires in = " . $token->expires_in . '<br/>';
            echo "ID Token = " . $token->id_token . '<br/>';
            echo "Created = " . $token->created . '<br/>';
            echo "<a class='logout' href='?logout'>Logout</a>";
        } else {
            $authUrl = $client->createAuthUrl();
            print "<a class='login' href='$authUrl'>Connect Me!</a>";
        }
        ?>
    </body>
</html>

How long do browsers cache HTTP 301s?

I will post answer that helped me:

go to url:

chrome://settings/clearBrowserData

it should invoke popup and then..

  • select only: cached images and files.
  • select time box : from beginning

What is the http-header "X-XSS-Protection"?

This header is getting somehow deprecated. You can read more about it here - X-XSS-Protection

  • Chrome has removed their XSS Auditor
  • Firefox has not, and will not implement X-XSS-Protection
  • Edge has retired their XSS filter

This means that if you do not need to support legacy browsers, it is recommended that you use Content-Security-Policy without allowing unsafe-inline scripts instead.

Get refresh token google api

If I may expand on user987361's answer:

From the offline access portion of the OAuth2.0 docs:

When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token. If you need to re-prompt the user for consent, include the approval_prompt parameter in the authorization code request, and set the value to force.

So, when you have already granted access, subsequent requests for a grant_type of authorization_code will not return the refresh_token, even if access_type was set to offline in the query string of the consent page.

As stated in the quote above, in order to obtain a new refresh_token after already receiving one, you will need to send your user back through the prompt, which you can do by setting approval_prompt to force.

Cheers,

PS This change was announced in a blog post as well.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

In your code where you run the stored procedure you should have something like this:

SqlCommand c = new SqlCommand(...)
//...

Add such a line of code:

c.CommandTimeout = 0;

This will wait as much time as needed for the operation to complete.

Android, How can I Convert String to Date?

using SimpleDateFormat or DateFormat class through

for e.g.

try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
    // handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}

JSON.parse unexpected character error

You can make sure that the object in question is stringified before passing it to parse function by simply using JSON.stringify() .

Updated your line below,

JSON.parse(JSON.stringify({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false}));

or if you have JSON stored in some variable:

JSON.parse(JSON.stringify(yourJSONobject));

How to get the cookie value in asp.net website

FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like

HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;

and decrypt that.

Force file download with php using header()

the htaccess solution

<filesmatch "\.(?i:doc|odf|pdf|cer|txt)$">
  Header set Content-Disposition attachment
</FilesMatch>

you can read this page: https://www.techmesto.com/force-files-to-download-using-htaccess/

htaccess - How to force the client's browser to clear the cache?

The most straight forward is to add filetime to the request. eg

myfile.txt?2014-10-30-13:12:33

versioning by date.

MySQL my.cnf file - Found option without preceding group

What worked for me:

  • Open my.ini with Notepad++
  • Encoding --> convert to ANSI
  • save

How to format a URL to get a file from Amazon S3?

As @stevebot said, do this:

https://<bucket-name>.s3.amazonaws.com/<key>

The one important thing I would like to add is that you either have to make your bucket objects all publicly accessible OR you can add a custom policy to your bucket policy. That custom policy could allow traffic from your network IP range or a different credential.

Reset Windows Activation/Remove license key

On Windows XP -

  1. Reboot into "Safe mode with Command Prompt"
  2. Type "explorer" in the command prompt that comes up and push [Enter]
  3. Click on Start>Run, and type the following :

    rundll32.exe syssetup,SetupOobeBnk

Reboot, and login as normal.

This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.

How to Troubleshoot Intermittent SQL Timeout Errors

My experience with these issues (not on SQL Server though) is that overdone multi-tasking is often the cause of the problem. If there is similar/connected data/tables queried at (almost) the same time by many connections, the DBMS may have trouble keeping all the isolation at check. This is not that much of an issue of disk usage as to making some connections wait for things to be done by other ones. Synchronization is very expensive in terms of CPU usage.

The 100 connections is way too much in my opinion. (In my experience again) even 20 connections asked to be done by one machine may be overly optimistic.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

If you don't want use connection pool (you sure, that your app has only one connection), you can do this - if connection falls you must establish new one - call method .openSession() instead .getCurrentSession()

For example:

SessionFactory sf = null;
// get session factory
// ...
//
Session session = null;
try {
        session = sessionFactory.getCurrentSession();
} catch (HibernateException ex) {
        session = sessionFactory.openSession();
}

If you use Mysql, you can set autoReconnect property:

    <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/database?autoReconnect=true</property>

I hope this helps.

Disable text input history

<input type="text" autocomplete="off" />

POST JSON to API using Rails and HTTParty

I solved this by adding .to_json and some heading information

@result = HTTParty.post(@urlstring_to_post.to_str, 
    :body => { :subject => 'This is the screen name', 
               :issue_type => 'Application Problem', 
               :status => 'Open', 
               :priority => 'Normal', 
               :description => 'This is the description for the problem'
             }.to_json,
    :headers => { 'Content-Type' => 'application/json' } )

Pushing to Git returning Error Code 403 fatal: HTTP request failed

The only thing that helped me is this answer for another question:

Git's famous "ERROR: Permission to .git denied to user"

In summary, if you are like me with Windows, search "Credential manager" and open it. There, you can find your Git credential. Change the username (which you must have changed to something else).

You can also find it under "Control Panel" - "User Account" - "Credential Manager".

How to prevent caching of my Javascript file?

Configure your webserver to send caching control HTTP headers for the script.

Fake headers in the HTML documents:

  1. Aren't as well supported as real HTTP headers
  2. Apply to the HTML document, not to resources that it links to

How to update and delete a cookie?

check this out A little framework: a complete cookies reader/writer with full Unicode support

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  Revision #1 - September 4, 2014
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*|  https://developer.mozilla.org/User:fusionchess
|*|  https://github.com/madmurphy/cookies.js
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path[, domain]])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

var docCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    if (!sKey) { return false; }
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

How do I create sql query for searching partial matches?

This may work as well.

SELECT * 
FROM myTable
WHERE CHARINDEX('mall', name) > 0
  OR CHARINDEX('mall', description) > 0

The identity used to sign the executable is no longer valid

You have your provisioning profiles outdated.

  1. xcode
  2. Preferences
  3. Accounts
  4. Select your apple id
  5. View Details (Right-bottom corner)
  6. Download All
  7. Run again and DONE!

Why do access tokens expire?

In addition to the other responses:

Once obtained, Access Tokens are typically sent along with every request from Clients to protected Resource Servers. This induce a risk for access token stealing and replay (assuming of course that access tokens are of type "Bearer" (as defined in the initial RFC6750).

Examples of those risks, in real life:

  • Resource Servers generally are distributed application servers and typically have lower security levels compared to Authorization Servers (lower SSL/TLS config, less hardening, etc.). Authorization Servers on the other hand are usually considered as critical Security infrastructure and are subject to more severe hardening.

  • Access Tokens may show up in HTTP traces, logs, etc. that are collected legitimately for diagnostic purposes on the Resource Servers or clients. Those traces can be exchanged over public or semi-public places (bug tracers, service-desk, etc.).

  • Backend RS applications can be outsourced to more or less trustworthy third-parties.

The Refresh Token, on the other hand, is typically transmitted only twice over the wires, and always between the client and the Authorization Server: once when obtained by client, and once when used by client during refresh (effectively "expiring" the previous refresh token). This is a drastically limited opportunity for interception and replay.

Last thought, Refresh Tokens offer very little protection, if any, against compromised clients.

Better way to represent array in java properties file

I can suggest using delimiters and using the

String.split(delimiter)

Example properties file:

MON=0800#Something#Something1, Something2

prop.load(new FileInputStream("\\\\Myseccretnetwork\\Project\\props.properties"));
String[]values = prop.get("MON").toString().split("#");

Hope that helps

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

I had a similar error..This might be due to two reasons. a) If you have used variables, re-evaluate the expressions in which variables are used and make sure the expression is evaluated without errors. b) If you are deleting the excel sheet and creating excel sheet on the fly in your package.

Leverage browser caching, how on apache or .htaccess?

First we need to check if we have enabled mod_headers.c and mod_expires.c.

sudo apache2 -l

If we don't have it, we need to enable them

sudo a2enmod headers

Then we need to restart apache

sudo apache2 restart

At last, add the rules on .htaccess (seen on other answers), for example

ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType text/css A86400
ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000
#
<FilesMatch "\.(gif|jpe?g|png|ico|css|js|swf)$">
Header set Cache-Control "public"
</FilesMatch>

Set disable attribute based on a condition for Html.TextBoxFor

I like the extension method approach so you don't have to pass through all possible parameters.
However using Regular expressions can be quite tricky (and somewhat slower) so I used XDocument instead:

public static MvcHtmlString SetDisabled(this MvcHtmlString html, bool isDisabled)
{
    var xDocument = XDocument.Parse(html.ToHtmlString());
    if (!(xDocument.FirstNode is XElement element))
    {
        return html;
    }

    element.SetAttributeValue("disabled", isDisabled ? "disabled" : null);
    return MvcHtmlString.Create(element.ToString());
}

Use the extension method like this:
@Html.EditorFor(m => m.MyProperty).SetDisabled(Model.ExpireDate == null)

Assign a login to a user created without login (SQL Server)

I found that this question was still relevant but not clearly answered in my case.

Using SQL Server 2012 with an orphaned SQL_USER this was the fix;

USE databasename                      -- The database I had recently attached
EXEC sp_change_users_login 'Report'   -- Display orphaned users
EXEC sp_change_users_login 'Auto_Fix', 'UserName', NULL, 'Password'

jQuery check if Cookie exists, if not create it

I think the bulletproof way is:

if (typeof $.cookie('token') === 'undefined'){
 //no cookie
} else {
 //have cookie
}

Checking the type of a null, empty or undefined var always returns 'undefined'

Edit: You can get there even easier:

if (!!$.cookie('token')) {
 // have cookie
} else {
 // no cookie
}

!! will turn the falsy values to false. Bear in mind that this will turn 0 to false!

How do I get a background location update every n minutes in my iOS application?

I did write an app using Location services, app must send location every 10s. And it worked very well.

Just use the "allowDeferredLocationUpdatesUntilTraveled:timeout" method, following Apple's doc.

What I did are:

Required: Register background mode for update Location.

1. Create LocationManger and startUpdatingLocation, with accuracy and filteredDistance as whatever you want:

-(void) initLocationManager    
{
    // Create the manager object
    self.locationManager = [[[CLLocationManager alloc] init] autorelease];
    _locationManager.delegate = self;
    // This is the most important property to set for the manager. It ultimately determines how the manager will
    // attempt to acquire location and thus, the amount of power that will be consumed.
    _locationManager.desiredAccuracy = 45;
    _locationManager.distanceFilter = 100;
    // Once configured, the location manager must be "started".
    [_locationManager startUpdatingLocation];
}

2. To keep app run forever using allowDeferredLocationUpdatesUntilTraveled:timeout method in background, you must restart updatingLocation with new parameter when app moves to background, like this:

- (void)applicationWillResignActive:(UIApplication *)application {
     _isBackgroundMode = YES;

    [_locationManager stopUpdatingLocation];
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [_locationManager setDistanceFilter:kCLDistanceFilterNone];
    _locationManager.pausesLocationUpdatesAutomatically = NO;
    _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
    [_locationManager startUpdatingLocation];
 }

3. App gets updatedLocations as normal with locationManager:didUpdateLocations: callback:

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//  store data
    CLLocation *newLocation = [locations lastObject];
    self.userLocation = newLocation;

   //tell the centralManager that you want to deferred this updatedLocation
    if (_isBackgroundMode && !_deferringUpdates)
    {
        _deferringUpdates = YES;
        [self.locationManager allowDeferredLocationUpdatesUntilTraveled:CLLocationDistanceMax timeout:10];
    }
}

4. But you should handle the data in then locationManager:didFinishDeferredUpdatesWithError: callback for your purpose

- (void) locationManager:(CLLocationManager *)manager didFinishDeferredUpdatesWithError:(NSError *)error {

     _deferringUpdates = NO;

     //do something 
}

5. NOTE: I think we should reset parameters of LocationManager each time app switches between background/forground mode.

What is the difference between buffer and cache memory in Linux?

Buffer is an area of memory used to temporarily store data while it's being moved from one place to another.

Cache is a temporary storage area used to store frequently accessed data for rapid access. Once the data is stored in the cache, future use can be done by accessing the cached copy rather than re-fetching the original data, so that the average access time is shorter.

Note: buffer and cache can be allocated on disk as well

Entity Framework Timeouts

If you are using DbContext and EF v6+, alternatively you can use:

this.context.Database.CommandTimeout = 180;

How to validate date with format "mm/dd/yyyy" in JavaScript?

The function will return true if the given string is in the right format('MM/DD/YYYY') else it will return false. (I found this code online & modified it a little)

_x000D_
_x000D_
function isValidDate(date) {_x000D_
    var temp = date.split('/');_x000D_
    var d = new Date(temp[2] + '/' + temp[0] + '/' + temp[1]);_x000D_
    return (d && (d.getMonth() + 1) == temp[0] && d.getDate() == Number(temp[1]) && d.getFullYear() == Number(temp[2]));_x000D_
}_x000D_
_x000D_
console.log(isValidDate('02/28/2015'));_x000D_
            
_x000D_
_x000D_
_x000D_

org.hibernate.MappingException: Could not determine type for: java.util.Set

Solution:

@Entity
@Table(name = "USER")
@Access(AccessType.FIELD)
public class User implements UserDetails, Serializable {

    private static final long serialVersionUID = 2L;

    @Id
    @Column(name = "USER_ID", updatable=false, nullable=false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "USERNAME")
    private String username;

    @Column(name = "PASSWORD")
    private String password;

    @Column(name = "NAME")
    private String name;

    @Column(name = "EMAIL")
    private String email;

    @Column(name = "LOCKED")
    private boolean locked;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = Role.class)
    @JoinTable(name = "USER_ROLE", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
    private Set<Role> roles;

    @Override
    public GrantedAuthority[] getAuthorities() {
        List<GrantedAuthorityImpl> list = new ArrayList<GrantedAuthorityImpl>(0);
        for (Role role : roles) {
            list.add(new GrantedAuthorityImpl(role.getRole()));
        }
        return (GrantedAuthority[]) list.toArray(new GrantedAuthority[list.size()]);
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !isLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @Override
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isLocked() {
        return locked;
    }

    public void setLocked(boolean locked) {
        this.locked = locked;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
}

Role.java same as above.

Check if cookie exists else set cookie to Expire in 10 days

You need to read and write document.cookie

if (document.cookie.indexOf("visited=") >= 0) {
  // They've been here before.
  alert("hello again");
}
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
}

Getting HTTP headers with Node.js

I'm not sure how you might do this with Node, but the general idea would be to send an HTTP HEAD request to the URL you're interested in.

HEAD

Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.


Something like this, based it on this question:

var cli = require('cli');
var http = require('http');
var url = require('url');

cli.parse();

cli.main(function(args, opts) {
        this.debug(args[0]);

        var siteUrl = url.parse(args[0]);
        var site = http.createClient(80, siteUrl.host);
        console.log(siteUrl);

        var request = site.request('HEAD', siteUrl.pathname, {'host' : siteUrl.host})
        request.end();

        request.on('response', function(response) {
                response.setEncoding('utf8');
                console.log('STATUS: ' + response.statusCode);
                response.on('data', function(chunk) {
                        console.log("DATA: " + chunk);
                });
        });
});

Creating a JavaScript cookie on a domain and reading it across sub domains

You can also use the Cookies API and do:

browser.cookies.set({
  url: 'example.com',
  name: 'HelloWorld',
  value: 'HelloWorld',
  expirationDate: myDate
}

MDN Set() Method Documentation

change Oracle user account status from EXPIRE(GRACE) to OPEN

set long 9999999
set lin 400
select DBMS_METADATA.GET_DDL('USER','YOUR_USER_NAME') from dual;

This will output something like this:

SQL> select DBMS_METADATA.GET_DDL('USER','WILIAM') from dual;

DBMS_METADATA.GET_DDL('USER','WILIAM')
--------------------------------------------------------------------------------

   CREATE USER "WILIAM" IDENTIFIED BY VALUES 'S:6680C1468F5F3B36B726CE7620F
FD9657F0E0E49AE56AAACE847BA368CEB;120F24A4C2554B4F'
      DEFAULT TABLESPACE "USER"
      TEMPORARY TABLESPACE "TEMP"
      PASSWORD EXPIRE

Just use the first piece of that with alter user instead:

ALTER USER "WILIAM" IDENTIFIED BY VALUES 'S:6680C1468F5F3B36B726CE7620F
FD9657F0E0E49AE56AAACE847BA368CEB;120F24A4C2554B4F';

This will put the account back in to OPEN status without changing the password (as long as you cut and paste correctly the hash value from the output of DBMS_METADATA.GET_DDL) and you don't even need to know what the password is.

Correct way to delete cookies server-side

For GlassFish Jersey JAX-RS implementation I have resolved this issue by common method is describing all common parameters. At least three of parameters have to be equal: name(="name"), path(="/") and domain(=null) :

public static NewCookie createDomainCookie(String value, int maxAgeInMinutes) {
    ZonedDateTime time = ZonedDateTime.now().plusMinutes(maxAgeInMinutes);
    Date expiry = time.toInstant().toEpochMilli();
    NewCookie newCookie = new NewCookie("name", value, "/", null, Cookie.DEFAULT_VERSION,null, maxAgeInMinutes*60, expiry, false, false);
    return newCookie;
}

And use it the common way to set cookie:

NewCookie domainNewCookie = RsCookieHelper.createDomainCookie(token, 60);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();

and to delete the cookie:

NewCookie domainNewCookie = RsCookieHelper.createDomainCookie("", 0);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();

ASP.NET Forms Authentication failed for the request. Reason: The ticket supplied has expired

I was getting this same error, in our case it was caused by a load balancer. We hade to make sure that the persistance was set to Source IP. Otherwise the login form was opened by one server, and processed by the other, which would fail to set the authentication cookie correctly. Maybe this helps someone else

Read a javascript cookie by name

One of the shortest ways is this, however as mentioned previously it can return the wrong cookie if there's similar names (MyCookie vs AnotherMyCookie):

var regex = /MyCookie=(.[^;]*)/ig;
var match = regex.exec(document.cookie);
var value = match[1];

I use this in a chrome extension so I know the name I'm setting, and I can make sure there won't be a duplicate, more or less.

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

This happens when a session other than the one used to alter a table is holding a lock likely because of a DML (update/delete/insert). If you are developing a new system, it is likely that you or someone in your team issues the update statement and you could kill the session without much consequence. Or you could commit from that session once you know who has the session open.

If you have access to a SQL admin system use it to find the offending session. And perhaps kill it.

You could use v$session and v$lock and others but I suggest you google how to find that session and then how to kill it.

In a production system, it really depends. For oracle 10g and older, you could execute

LOCK TABLE mytable in exclusive mode;
alter table mytable modify mycolumn varchar2(5);

In a separate session but have the following ready in case it takes too long.

alter system kill session '....

It depends on what system do you have, older systems are more likely to not commit every single time. That is a problem since there may be long standing locks. So your lock would prevent any new locks and wait for a lock that who knows when will be released. That is why you have the other statement ready. Or you could look for PLSQL scripts out there that do similar things automatically.

In version 11g there is a new environment variable that sets a wait time. I think it likely does something similar to what I described. Mind you that locking issues don't go away.

ALTER SYSTEM SET ddl_lock_timeout=20;
alter table mytable modify mycolumn varchar2(5);

Finally it may be best to wait until there are few users in the system to do this kind of maintenance.

How do I get the serial key for Visual Studio Express?

The question is about VS 2008 Express.

Microsoft's web page for registering Visual Studio 2008 Express has been dead (404) for some time, so registering it is not possible.

Instead, as a workaround, you can temporarily remove the requirement to register VS2008Exp by deleting (or renaming) the registry key:

HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration

To ensure that this is working beforehand, click Help -> register product within VS2008.

You should see text like

"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 10 more days before you will be required to register it."

Close the application, delete that key, reopen, click help->register product.

The text should now say

"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 30 more days before you will be required to register it."

So you have two options - delete that key manually every 30 days, or run it from a batch file that also contains a line like:

reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f

[Edit: User @i486 confirms on testing that this workaround works even after the expiration period has expired]

[Edit2: User @Wyatt8740 has a much more elegant way to prevent the value from reappearing.]

How to get cookie's expire time

Putting an encoded json inside the cookie is my favorite method, to get properly formated data out of a cookie. Try that:

$expiry = time() + 12345;
$data = (object) array( "value1" => "just for fun", "value2" => "i'll save whatever I want here" );
$cookieData = (object) array( "data" => $data, "expiry" => $expiry );
setcookie( "cookiename", json_encode( $cookieData ), $expiry );

then when you get your cookie next time:

$cookie = json_decode( $_COOKIE[ "cookiename" ] );

you can simply extract the expiry time, which was inserted as data inside the cookie itself..

$expiry = $cookie->expiry;

and additionally the data which will come out as a usable object :)

$data = $cookie->data;
$value1 = $cookie->data->value1;

etc. I find that to be a much neater way to use cookies, because you can nest as many small objects within other objects as you wish!

Ways to implement data versioning in MongoDB

I worked through this solution that accommodates a published, draft and historical versions of the data:

{
  published: {},
  draft: {},
  history: {
    "1" : {
      metadata: <value>,
      document: {}
    },
    ...
  }
}

I explain the model further here: http://software.danielwatrous.com/representing-revision-data-in-mongodb/

For those that may implement something like this in Java, here's an example:

http://software.danielwatrous.com/using-java-to-work-with-versioned-data/

Including all the code that you can fork, if you like

https://github.com/dwatrous/mongodb-revision-objects

Div table-cell vertical align not working

Set the height for the parent element.

mysql datetime comparison

But this is obviously performing a 'string' comparison

No. The string will be automatically cast into a DATETIME value.

See 11.2. Type Conversion in Expression Evaluation.

When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.

How can I compare two dates in PHP?

If all your dates are posterior to the 1st of January of 1970, you could use something like:

$today = date("Y-m-d");
$expire = $row->expireDate; //from database

$today_time = strtotime($today);
$expire_time = strtotime($expire);

if ($expire_time < $today_time) { /* do Something */ }

If you are using PHP 5 >= 5.2.0, you could use the DateTime class:

$today_dt = new DateTime($today);
$expire_dt = new DateTime($expire);

if ($expire_dt < $today_dt) { /* Do something */ }

Or something along these lines.

Java time-based map/cache with expiring keys

This is a sample implementation that i did for the same requirement and concurrency works well. Might be useful for someone.

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 
 * @author Vivekananthan M
 *
 * @param <K>
 * @param <V>
 */
public class WeakConcurrentHashMap<K, V> extends ConcurrentHashMap<K, V> {

    private static final long serialVersionUID = 1L;

    private Map<K, Long> timeMap = new ConcurrentHashMap<K, Long>();
    private long expiryInMillis = 1000;
    private static final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss:SSS");

    public WeakConcurrentHashMap() {
        initialize();
    }

    public WeakConcurrentHashMap(long expiryInMillis) {
        this.expiryInMillis = expiryInMillis;
        initialize();
    }

    void initialize() {
        new CleanerThread().start();
    }

    @Override
    public V put(K key, V value) {
        Date date = new Date();
        timeMap.put(key, date.getTime());
        System.out.println("Inserting : " + sdf.format(date) + " : " + key + " : " + value);
        V returnVal = super.put(key, value);
        return returnVal;
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        for (K key : m.keySet()) {
            put(key, m.get(key));
        }
    }

    @Override
    public V putIfAbsent(K key, V value) {
        if (!containsKey(key))
            return put(key, value);
        else
            return get(key);
    }

    class CleanerThread extends Thread {
        @Override
        public void run() {
            System.out.println("Initiating Cleaner Thread..");
            while (true) {
                cleanMap();
                try {
                    Thread.sleep(expiryInMillis / 2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        private void cleanMap() {
            long currentTime = new Date().getTime();
            for (K key : timeMap.keySet()) {
                if (currentTime > (timeMap.get(key) + expiryInMillis)) {
                    V value = remove(key);
                    timeMap.remove(key);
                    System.out.println("Removing : " + sdf.format(new Date()) + " : " + key + " : " + value);
                }
            }
        }
    }
}


Git Repo Link (With Listener Implementation)

https://github.com/vivekjustthink/WeakConcurrentHashMap

Cheers!!

How to set a cookie to expire in 1 hour in Javascript?

Code :

var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
document.cookie = 
'username=' + value + 
'; expires=' + now.toUTCString() + 
'; path=/';

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

Try using a .netrc file, it will authenticate over https. Create a file call .netrc in your home directory and put this in it:

machine github.com login myusername password mypass

See this post for more info:

https://plus.google.com/u/0/104462765626035447305/posts/WbwD4zcm2fj

Is there a limit on an Excel worksheet's name length?

My solution was to use a short nickname (less than 31 characters) and then write the entire name in cell 0.

How to delete a cookie using jQuery?

What you are doing is correct, the problem is somewhere else, e.g. the cookie is being set again somehow on refresh.

javax.faces.application.ViewExpiredException: View could not be restored

I ran into this problem myself and realized that it was because of a side-effect of a Filter that I created which was filtering all requests on the appliation. As soon as I modified the filter to pick only certain requests, this problem did not occur. It maybe good to check for such filters in your application and see how they behave.

Error: Uncaught SyntaxError: Unexpected token <

I don't know whether you got the answer. I met this issue today, and I thought I got a possible right answer: you don't put the script file in a right location.

Most people don't meet this issue because they put the scripts into their server directory directly. I meet this because I make a link of the source file (the html file) to the server root directory. I didn't link the script files, and I don't know how nginx find them. But they are not loaded correctly.

After I linked all files to the server root directory, problem solved.

Explanation of BASE terminology

It has to do with BASE: the BASE jumper kind is always Basically Available (to new relationships), in a Soft state (none of his relationship last very long) and Eventually consistent (one day he will get married).

Set a cookie to never expire

Set a far future absolute time:

setcookie("CookieName", "CookieValue", 2147483647);

It is better to use an absolute time than calculating it relative to the present as recommended in the accepted answer.

The maximum value compatible with 32 bits systems is:

2147483647 = 2^31 = ~year 2038

How to get cookie expiration date / creation date from javascript?

The information is not available through document.cookie, but if you're really desperate for it, you could try performing a request through the XmlHttpRequest object to the current page and access the cookie header using getResponseHeader().

How can I create persistent cookies in ASP.NET?

//add cookie

var panelIdCookie = new HttpCookie("panelIdCookie");
panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture));
panelIdCookie.Expires = DateTime.Now.AddMonths(2); 
Response.Cookies.Add(panelIdCookie);

//read cookie

    var httpCookie = Request.Cookies["panelIdCookie"];
                if (httpCookie != null)
                {
                    panelId = Convert.ToInt32(httpCookie["panelId"]);
                }

Changing password with Oracle SQL Developer

Depending on the admin settings, you may have to specify your old password using the REPLACE option

alter user <username> identified by <newpassword> replace <oldpassword> 

npm ERR cb() never called

I tried many things from internet. Only below method worked for me. If every answer in this question don't work, try below steps in below order. Note :

  • Reboots required
  • Use cmd to execute code (VSCode didn't worked for me)
  1. Delete local node module folder
  2. Delete local package-lock file
  3. Uninstall node.js
  4. Reboot
  5. Delete the folders: "C:\Users\ YOUR LOGIN NAME \AppData\Roaming\npm" and "C:\Users\ YOUR LOGIN NAME \AppData\Roaming\npm-cache"
  6. Look for other npm folders under AppData and delete them too.
  7. Reboot
  8. Reinstall node.js
  9. Reboot
  10. npm cache clean --force
  11. npm cache verify
  12. npm install --force

How do I add a placeholder on a CharField in Django?

The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or '[email protected]'

It also allows the placeholder to depend on the instance for ModelForms with instance specified.

Adding sheets to end of workbook in Excel (normal method not working?)

Try this

mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name

Fatal error: Out of memory, but I do have plenty of memory (PHP)

I would start by upgrading PHP to 5.4+ as it's up to 50% faster for some applications. They fixed a large number of memory leaks. Please see becnhamrks: http://news.php.net/php.internals/57760

How to generate unique IDs for form labels in React?

Don't use IDs at all if you don't need to, instead wrap the input in a label like this:

<label>
   My Label
   <input type="text"/>
</label>

Then you won't need to worry about unique IDs.

How to add not null constraint to existing column in MySQL

Would like to add:

After update, such as

ALTER TABLE table_name modify column_name tinyint(4) NOT NULL;

If you get

ERROR 1138 (22004): Invalid use of NULL value

Make sure you update the table first to have values in the related column (so it's not null)

How Long Does it Take to Learn Java for a Complete Newbie?

I teach Java Programming at a high school, and our course runs 14 weeks. This is enough time to give students a solid foundation in object oriented programming, but students are not experienced enough to develop and large projects or anything too complicated.

Many schools use the textbook by Lambert & Osbborne:

Lambert, K. & Osborne, M. Fundamentals of Java: AP Computer Science Essentials for the AP Exam. 3rd ed. 2006. Thomson Course Technology.

Splitting strings in PHP and get last part

$string = 'abc-123-xyz-789';
$exploded = explode('-', $string);
echo end($exploded);

EDIT::Finally got around to removing the E_STRICT issue

Can I add background color only for padding?

I am sorry everyone that this is the solution the true one where you dont have to actually set the padding.

http://jsfiddle.net/techsin/TyXRY/1/

What i have done...

  • Applied two gradients on background with both having one start and end color. Instead of using solid color. Reason being that you can't have two solid colors for one background.
  • Then applied different background-clip property to each.
  • thus making one color extend to content box and other to border, revealing the padding.

Clever if i say so to myself.

div {
    padding: 35px;
    background-image:
      linear-gradient(to bottom,
        rgba(240, 255, 40, 1) 0%,
        rgba(240, 255, 40, 1) 100%),
      linear-gradient(to bottom,
        rgba(240, 40, 40, 1) 0%,
        rgba(240, 40, 40, 1) 100%);
    background-clip: content-box, padding-box;
}

How do I edit $PATH (.bash_profile) on OSX?

Simplest answer is:

Step 1: Fire up Terminal.app

Step 2: Type nano .bash_profile – This command will open the .bash_profile document (or create it if it doesn’t already exist) in the easiest to use text editor in Terminal – Nano.

Step 3: Now you can make a simple change to the file. Paste these lines of code to change your Terminal prompt.

export PS1="___________________ | \w @ \h (\u) \n| => "

export PS2="| => "

Step 4: Now save your changes by typing ctrl +o Hit return to save. Then exit Nano by typing ctrl+x

Step 5: Now we need to *activate your changes. Type source .bash_profile and watch your prompt change.

That's it! Enjoy!

How to make phpstorm display line numbers by default?

By typing command + shift + A you will get a search prompt and write line numbers . Now you can trigger button on or off

phpstorm

Escape text for HTML

If you're using .NET 4 or above and you don't want to reference System.Web, you can use WebUtility.HtmlEncode from System

var encoded = WebUtility.HtmlEncode(unencoded);

This has the same effect as HttpUtility.HtmlEncode and should be preferred over System.Security.SecurityElement.Escape.

Is there an "exists" function for jQuery?

I have found if ($(selector).length) {} to be insufficient. It will silently break your app when selector is an empty object {}.

var $target = $({});        
console.log($target, $target.length);

// Console output:
// -------------------------------------
// [? Object              ] 1
//    ? __proto__: Object

My only suggestion is to perform an additional check for {}.

if ($.isEmptyObject(selector) || !$(selector).length) {
    throw new Error('Unable to work with the given selector.');
}

I'm still looking for a better solution though as this one is a bit heavy.

Edit: WARNING! This doesn't work in IE when selector is a string.

$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE

raw vs. html_safe vs. h to unescape html

The difference is between Rails’ html_safe() and raw(). There is an excellent post by Yehuda Katz on this, and it really boils down to this:

def raw(stringish)

  stringish.to_s.html_safe

end

Yes, raw() is a wrapper around html_safe() that forces the input to String and then calls html_safe() on it. It’s also the case that raw() is a helper in a module whereas html_safe() is a method on the String class which makes a new ActiveSupport::SafeBuffer instance — that has a @dirty flag in it.

Refer to "Rails’ html_safe vs. raw".

FileNotFoundException while getting the InputStream object from HttpURLConnection

I don't know about your Spring/JAXB combination, but the average REST webservice won't return a response body on POST/PUT, just a response status. You'd like to determine it instead of the body.

Replace

InputStream response = con.getInputStream();

by

int status = con.getResponseCode();

All available status codes and their meaning are available in the HTTP spec, as linked before. The webservice itself should also come along with some documentation which overviews all status codes supported by the webservice and their special meaning, if any.

If the status starts with 4nn or 5nn, you'd like to use getErrorStream() instead to read the response body which may contain the error details.

InputStream error = con.getErrorStream();

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I had this error. Nothing worked for me until I opened the SQLServer log file in the "MSSQL10_50" Log folder. That clearly stated which file could not be overwritten. It turned out that the .mdf file was being written into the "MSSQL10" data folder. I made sure that folder had the same SQLServer user permissions as the "MSSQL10_50" equivalent folder. Then it all worked.

The issue here is that the error detail is logged but not reported, so check the logs.

JDBC connection failed, error: TCP/IP connection to host failed

Easy Solution

Got to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager ->Expand SQL Server Network Configuration-> Protocol ->Enable TCP/IP Right box

Double Click on TCP/IP and go to IP Adresses Tap and Put port 1433 under TCP port.

enter image description here

n-grams in python, four, five, six grams?

You can easily whip up your own function to do this using itertools:

from itertools import izip, islice, tee
s = 'spam and eggs'
N = 3
trigrams = izip(*(islice(seq, index, None) for index, seq in enumerate(tee(s, N))))
list(trigrams)
# [('s', 'p', 'a'), ('p', 'a', 'm'), ('a', 'm', ' '),
# ('m', ' ', 'a'), (' ', 'a', 'n'), ('a', 'n', 'd'),
# ('n', 'd', ' '), ('d', ' ', 'e'), (' ', 'e', 'g'),
# ('e', 'g', 'g'), ('g', 'g', 's')]

Is there an opposite of include? for Ruby Arrays?

module Enumerable
  def does_not_include?(item)
    !include?(item)
  end
end

Ok, but seriously, the unless works fine.

Importing a Maven project into Eclipse from Git


Step 1 : Setting Up Eclipse

First of all you'll need to have a few Eclipse plug-ins installed. So use eclipse IDE software install feature in the help dropdown menu ? Install new software, and add link to Available Software Site, then install it.

  1. GIT plugin (EGIT)- http://download.eclipse.org/egit/updates
  2. Eclipse Maven plugin (M2Eclipse) - http://download.eclipse.org/technology/m2e/releases
  3. Maven SCM Handler for EGit (m2e-egit)

    Install from the M2E Marketplace (Settings ? Maven ? Discovery ? Open Catalog and search for " m2e-egit")


Step 2 : Clone the repository

Clone(download) your Maven Projects from Git

Check out non-eclipse Maven Projects from Git (File ? Import.. ? Maven ? Check out Maven Projects from SCM)

File ? Import.. ? Maven ? Check out Maven Projects from SCM

Now add your git repository link to SCM URI field.Then click next & finish.

How do I add an element to array in reducer of React native redux?

push does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:

import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {

    arr:[]
}

export default function userState(state = initialUserState, action){
     console.log(arr);
     switch (action.type){
        case ADD_ITEM :
          return { 
             ...state,
             arr:[...state.arr, action.newItem]
        }

        default:return state
     }
}

How to set up fixed width for <td>?

Use d-flex instead of row for "tr" in Bootstrap 4

The thing is that "row" class takes more width then the parent container, which introduces issues.

_x000D_
_x000D_
<table class="table">_x000D_
  <tbody>_x000D_
    <tr class="d-flex">_x000D_
      <td class="col-sm-8">Hello</td>_x000D_
      <td class="col-sm-4">World</td>_x000D_
    </tr>_x000D_
    <tr class="d-flex">_x000D_
      <td class="col-sm-8">8 columns</td>_x000D_
      <td class="col-sm-4">4 columns</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Changing the sign of a number in PHP?

function invertSign($value)
{
    return -$value;
}

Negative list index?

Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.

click command in selenium webdriver does not work

This is a long standing issue with chromedriver(still present in 2020).

In Chrome I changed from a zoom of 90% to 100% and that solved the problem. ref

I find TheLifeOfSteve's answer more reliable.

Easy way to test a URL for 404 in PHP?

If you are using PHP's curl bindings, you can check the error code using curl_getinfo as such:

$handle = curl_init($url);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);

/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
    /* Handle 404 here. */
}

curl_close($handle);

/* Handle $response here. */

In Visual Studio C++, what are the memory allocation representations?

There's actually quite a bit of useful information added to debug allocations. This table is more complete:

http://www.nobugs.org/developer/win32/debug_crt_heap.html#table

Address  Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments
0x00320FD8  -40    0x01090009    0x01090009     0x01090009    0x0109005A     Win32 heap info
0x00320FDC  -36    0x01090009    0x00180700     0x01090009    0x00180400     Win32 heap info
0x00320FE0  -32    0xBAADF00D    0x00320798     0xDDDDDDDD    0x00320448     Ptr to next CRT heap block (allocated earlier in time)
0x00320FE4  -28    0xBAADF00D    0x00000000     0xDDDDDDDD    0x00320448     Ptr to prev CRT heap block (allocated later in time)
0x00320FE8  -24    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Filename of malloc() call
0x00320FEC  -20    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Line number of malloc() call
0x00320FF0  -16    0xBAADF00D    0x00000008     0xDDDDDDDD    0xFEEEFEEE     Number of bytes to malloc()
0x00320FF4  -12    0xBAADF00D    0x00000001     0xDDDDDDDD    0xFEEEFEEE     Type (0=Freed, 1=Normal, 2=CRT use, etc)
0x00320FF8  -8     0xBAADF00D    0x00000031     0xDDDDDDDD    0xFEEEFEEE     Request #, increases from 0
0x00320FFC  -4     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x00321000  +0     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321004  +4     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321008  +8     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x0032100C  +12    0xBAADF00D    0xBAADF00D     0xDDDDDDDD    0xFEEEFEEE     Win32 heap allocations are rounded up to 16 bytes
0x00321010  +16    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321014  +20    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321018  +24    0x00000010    0x00000010     0x00000010    0xFEEEFEEE     Win32 heap bookkeeping
0x0032101C  +28    0x00000000    0x00000000     0x00000000    0xFEEEFEEE     Win32 heap bookkeeping
0x00321020  +32    0x00090051    0x00090051     0x00090051    0xFEEEFEEE     Win32 heap bookkeeping
0x00321024  +36    0xFEEE0400    0xFEEE0400     0xFEEE0400    0xFEEEFEEE     Win32 heap bookkeeping
0x00321028  +40    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping
0x0032102C  +44    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping

How can I put a database under git (version control)?

I'd like to put the entire database under version control, what database engine can I use so that I can put the actual database under version control instead of its dump?

This is not database engine dependent. By Microsoft SQL Server there are lots of version controlling programs. I don't think that problem can be solved with git, you have to use a pgsql specific schema version control system. I don't know whether such a thing exists or not...

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

Oracle PL/SQL string compare issue

To fix the core question, "how should I detect that these two variables don't have the same value when one of them is null?", I don't like the approach of nvl(my_column, 'some value that will never, ever, ever appear in the data and I can be absolutely sure of that') because you can't always guarantee that a value won't appear... especially with NUMBERs.

I have used the following:

if (str1 is null) <> (str2 is null) or str1 <> str2 then
  dbms_output.put_line('not equal');
end if;

Disclaimer: I am not an Oracle wizard and I came up with this one myself and have not seen it elsewhere, so there may be some subtle reason why it's a bad idea. But it does avoid the trap mentioned by APC, that comparing a null to something else gives neither TRUE nor FALSE but NULL. Because the clauses (str1 is null) will always return TRUE or FALSE, never null.

(Note that PL/SQL performs short-circuit evaluation, as noted here.)

JavaScript getElementByID() not working

You need to put the JavaScript at the end of the body tag.

It doesn't find it because it's not in the DOM yet!

You can also wrap it in the onload event handler like this:

window.onload = function() {
var refButton = document.getElementById( 'btnButton' );
refButton.onclick = function() {
   alert( 'I am clicked!' );
}
}

Django gives Bad Request (400) when DEBUG = False

For me as I have already xampp on 127.0.0.1 and django on 127.0.1.1 and i kept trying adding hosts

ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'www.yourdomain.com', '*', '127.0.1.1']

and i got the same error or (400) bad request enter image description here

so I change the url to 127.0.1.1:(the used port)/project and voila !

you have to check what is your virtual network address, for me as i use bitnami django stack 2.2.3-1 on Linux i can check which port django is using. if you have an error ( 400 bad request ) then i guess django on different virtual network .. good luck enter image description here

range() for floats

I don't know a built-in function, but writing one like this shouldn't be too complicated.

def frange(x, y, jump):
  while x < y:
    yield x
    x += jump

As the comments mention, this could produce unpredictable results like:

>>> list(frange(0, 100, 0.1))[-1]
99.9999999999986

To get the expected result, you can use one of the other answers in this question, or as @Tadhg mentioned, you can use decimal.Decimal as the jump argument. Make sure to initialize it with a string rather than a float.

>>> import decimal
>>> list(frange(0, 100, decimal.Decimal('0.1')))[-1]
Decimal('99.9')

Or even:

import decimal

def drange(x, y, jump):
  while x < y:
    yield float(x)
    x += decimal.Decimal(jump)

And then:

>>> list(drange(0, 100, '0.1'))[-1]
99.9

Array.sort() doesn't sort numbers correctly

try this:

a = new Array();
a.push(10);
a.push(60);
a.push(20);
a.push(30);
a.push(100);
a.sort(Test)

document.write(a);


function Test(a,b)
{
    return a > b ? true : false;
}

SimpleDateFormat parsing date with 'Z' literal

In the pattern, the inclusion of a 'z' date-time component indicates that timezone format needs to conform to the General time zone "standard", examples of which are Pacific Standard Time; PST; GMT-08:00.

A 'Z' indicates that the timezone conforms to the RFC 822 time zone standard, e.g. -0800.

I think you need a DatatypeConverter ...

@Test
public void testTimezoneIsGreenwichMeanTime() throws ParseException {
    final Calendar calendar = javax.xml.bind.DatatypeConverter.parseDateTime("2010-04-05T17:16:00Z");
    TestCase.assertEquals("gotten timezone", "GMT+00:00", calendar.getTimeZone().getID());
}

iReport not starting using JRE 8

For me, the combination of Stuart Gathman's and Raviath's answer in this thread did the trick in Windows Server 2016 for iReport 5.6.0.

In addition, I added a symlink within C:\program files\java\jre7 to jdk8 like this:

cmd /c mklink /d "C:\program files\java\jre7\bin" "C:\Program Files\Java\jdk1.8.0_181\bin"

because iReport was constantly complaining that it could not find java.exe within C:\program files\java\jre7\bin\ - So I served it the available java.exe (in my case V8.181) under the desired path and it swallowed it gladly.

Indenting code in Sublime text 2?

You can find it in Edit ? Line ? Reindent, but it does not have a shortcut by default. You can add a shortcut by going to the menu Preferences ? Keybindings ? User, then add there:

{ "keys": ["f12"], "command": "reindent", "args": {"single_line": false} }  

(example of using the F12 key for that functionality)

The config files use JSON-syntax, so these curly braces have to be placed comma-separated in the square-brackets that are there by default. If you don't have any other key-bindings already, then your whole Keybindings ? User file would look like this, of course:

[
    { "keys": ["f12"], "command": "reindent", "args": {"single_line": false}}
]

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Google Apps KitKat for Genymotion.

Download the Google Apps ZIP file from the link which contain the essential Google Apps such as Play Store, Gmail, YouTube, etc.

https://www.mediafire.com/?qbbt4lhyu9q10ix

After finishing booting, drag and drop the ZIP file we downloaded named update-gapps-4-4-2-signed.zip to the Genymotion Window. It starts installing the Google Apps, and it asks for your confirmation. Confirm it.

tmux set -g mouse-mode on doesn't work

As @Graham42 noted, mouse option has changed in version 2.1. Scrolling now requires for you to enter copy mode first. To enable scrolling almost identical to how it was before 2.1 add following to your .tmux.conf.

set-option -g mouse on

# make scrolling with wheels work
bind -n WheelUpPane if-shell -F -t = "#{mouse_any_flag}" "send-keys -M" "if -Ft= '#{pane_in_mode}' 'send-keys -M' 'select-pane -t=; copy-mode -e; send-keys -M'"
bind -n WheelDownPane select-pane -t= \; send-keys -M

This will enable scrolling on hover over a pane and you will be able to scroll that pane line by line.

Source: https://groups.google.com/d/msg/tmux-users/TRwPgEOVqho/Ck_oth_SDgAJ

How to reset sequence in postgres and fill id column with new data?

Just resetting the sequence and updating all rows may cause duplicate id errors. In many cases you have to update all rows twice. First with higher ids to avoid the duplicates, then with the ids you actually want.

Please avoid to add a fixed amount to all ids (as recommended in other comments). What happens if you have more rows than this fixed amount? Assuming the next value of the sequence is higher than all the ids of the existing rows (you just want to fill the gaps), i would do it like:

UPDATE table SET id = DEFAULT;
ALTER SEQUENCE seq RESTART;
UPDATE table SET id = DEFAULT;

Meaning of - <?xml version="1.0" encoding="utf-8"?>

An XML declaration is not required in all XML documents; however XHTML document authors are strongly encouraged to use XML declarations in all their documents. Such a declaration is required when the character encoding of the document is other than the default UTF-8 or UTF-16 and no encoding was determined by a higher-level protocol. Here is an example of an XHTML document. In this example, the XML declaration is included.

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html 
 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Virtual Library</title>
  </head>
  <body>
    <p>Moved to <a href="http://example.org/">example.org</a>.</p>
 </body>
</html>

Please refer to the W3 standards for XML.

Make anchor link go some pixels above where it's linked to

try this code, it has already a smooth animation when clicked the link.

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top - 100
    }, 500);
});

Excel formula to search if all cells in a range read "True", if not, then show "False"

You can just AND the results together if they are stored as TRUE / FALSE values:

=AND(A1:D2)

Or if stored as text, use an array formula - enter the below and press Ctrl+Shift+Enter instead of Enter.

=AND(EXACT(A1:D2,"TRUE"))

Python JSON serialize a Decimal object

For those who don't want to use a third-party library... An issue with Elias Zamaria's answer is that it converts to float, which can run into problems. For example:

>>> json.dumps({'x': Decimal('0.0000001')}, cls=DecimalEncoder)
'{"x": 1e-07}'
>>> json.dumps({'x': Decimal('100000000000.01734')}, cls=DecimalEncoder)
'{"x": 100000000000.01733}'

The JSONEncoder.encode() method lets you return the literal json content, unlike JSONEncoder.default(), which has you return a json compatible type (like float) that then gets encoded in the normal way. The problem with encode() is that it (normally) only works at the top level. But it's still usable, with a little extra work (python 3.x):

import json
from collections.abc import Mapping, Iterable
from decimal import Decimal

class DecimalEncoder(json.JSONEncoder):
    def encode(self, obj):
        if isinstance(obj, Mapping):
            return '{' + ', '.join(f'{self.encode(k)}: {self.encode(v)}' for (k, v) in obj.items()) + '}'
        if isinstance(obj, Iterable) and (not isinstance(obj, str)):
            return '[' + ', '.join(map(self.encode, obj)) + ']'
        if isinstance(obj, Decimal):
            return f'{obj.normalize():f}'  # using normalize() gets rid of trailing 0s, using ':f' prevents scientific notation
        return super().encode(obj)

Which gives you:

>>> json.dumps({'x': Decimal('0.0000001')}, cls=DecimalEncoder)
'{"x": 0.0000001}'
>>> json.dumps({'x': Decimal('100000000000.01734')}, cls=DecimalEncoder)
'{"x": 100000000000.01734}'

What is "loose coupling?" Please provide examples

Two components are higly coupled when they depend on concrete implementation of each other.

Suppose I have this code somewhere in a method in my class:

this.some_object = new SomeObject();

Now my class depends on SomeObject, and they're highly coupled. On the other hand, let's say I have a method InjectSomeObject:

void InjectSomeObject(ISomeObject so) { // note we require an interface, not concrete implementation
  this.some_object = so;
}

Then the first example can just use injected SomeObject. This is useful during testing. With normal operation you can use heavy, database-using, network-using classes etc. while for tests passing a lightweight, mock implementation. With tightly coupled code you can't do that.

You can make some parts of this work easer by using dependency injection containers. You can read more about DI at Wikipedia: http://en.wikipedia.org/wiki/Dependency_injection.

It is sometimes easy to take this too far. At some point you have to make things concrete, or your program will be less readable and understandable. So use this techniques mainly at components boundary, and know what you are doing. Make sure you are taking advantage of loose coupling. If not, you probably don't need it in that place. DI may make your program more complex. Make sure you make a good tradeoff. In other words, maintain good balance. As always when designing systems. Good luck!

PHP split alternative?

You can use the easier function preg_match instead, It's better and faster than all of the other ones.

$var = "<tag>Get this var</tag>";
preg_match("/<tag>(.*)<\/tag>/", $var , $new_var);
echo $new_var['1']; 

Output: Get this var

How to sort a collection by date in MongoDB?

db.getCollection('').find({}).sort({_id:-1}) 

This will sort your collection in descending order based on the date of insertion

MVC DateTime binding with incorrect date format

I set the below config on my MVC4 and it works like a charm

<globalization uiCulture="auto" culture="auto" />

Java: Insert multiple rows into MySQL with PreparedStatement

@Ali Shakiba your code needs some modification. Error part:

for (int i = 0; i < myArray.length; i++) {
     myStatement.setString(i, myArray[i][1]);
     myStatement.setString(i, myArray[i][2]);
}

Updated code:

String myArray[][] = {
    {"1-1", "1-2"},
    {"2-1", "2-2"},
    {"3-1", "3-2"}
};

StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");

for (int i = 0; i < myArray.length - 1; i++) {
    mySql.append(", (?, ?)");
}

mysql.append(";"); //also add the terminator at the end of sql statement
myStatement = myConnection.prepareStatement(mySql.toString());

for (int i = 0; i < myArray.length; i++) {
    myStatement.setString((2 * i) + 1, myArray[i][1]);
    myStatement.setString((2 * i) + 2, myArray[i][2]);
}

myStatement.executeUpdate();

Converting char[] to byte[]

private static byte[] charArrayToByteArray(char[] c_array) {
        byte[] b_array = new byte[c_array.length];
        for(int i= 0; i < c_array.length; i++) {
            b_array[i] = (byte)(0xFF & (int)c_array[i]);
        }
        return b_array;
}

Install apps silently, with granted INSTALL_PACKAGES permission

You should define

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

in your manifest, then if whether you are in system partition (/system/app) or you have your application signed by the manufacturer, you are going to have INSTALL_PACKAGES permission.

My suggestion is to create a little android project with 1.5 compatibility level used to call installPackages via reflection and to export a jar with methods to install packages and to call the real methods. Then, by importing the jar in your project you will be ready to install packages.

javascript remove "disabled" attribute from html input

Best answer is just removeAttribute

element.removeAttribute("disabled");

Remove local git tags that are no longer on the remote repository

Good question. :) I don't have a complete answer...

That said, you can get a list of remote tags via git ls-remote. To list the tags in the repository referenced by origin, you'd run:

git ls-remote --tags origin

That returns a list of hashes and friendly tag names, like:

94bf6de8315d9a7b22385e86e1f5add9183bcb3c        refs/tags/v0.1.3
cc047da6604bdd9a0e5ecbba3375ba6f09eed09d        refs/tags/v0.1.4
...
2f2e45bedf67dedb8d1dc0d02612345ee5c893f2        refs/tags/v0.5.4

You could certainly put together a bash script to compare the tags generated by this list with the tags you have locally. Take a look at git show-ref --tags, which generates the tag names in the same form as git ls-remote).


As an aside, git show-ref has an option that does the opposite of what you'd like. The following command would list all the tags on the remote branch that you don't have locally:

git ls-remote --tags origin | git show-ref --tags --exclude-existing

How to delete only the content of file in python

How to delete only the content of file in python

There is several ways of set the logical size of a file to 0, depending how you access that file:

To empty an open file:

def deleteContent(pfile):
    pfile.seek(0)
    pfile.truncate()

To empty a open file whose file descriptor is known:

def deleteContent(fd):
    os.ftruncate(fd, 0)
    os.lseek(fd, 0, os.SEEK_SET)

To empty a closed file (whose name is known)

def deleteContent(fName):
    with open(fName, "w"):
        pass



I have a temporary file with some content [...] I need to reuse that file

That being said, in the general case it is probably not efficient nor desirable to reuse a temporary file. Unless you have very specific needs, you should think about using tempfile.TemporaryFile and a context manager to almost transparently create/use/delete your temporary files:

import tempfile

with tempfile.TemporaryFile() as temp:
     # do whatever you want with `temp`

# <- `tempfile` guarantees the file being both closed *and* deleted
#     on exit of the context manager

Where should I put <script> tags in HTML markup?

Just before the closing body tag, as stated on

http://developer.yahoo.com/performance/rules.html#js_bottom

Put Scripts at the Bottom

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

I know this is an old post and that it wants an answer for .NET 1.1 but there's already a very good answer for that. I thought it would be good to have an answer for those people who land on this post that may have a more recent version of the .Net framework, such as myself when I went looking for an answer to the same question.

In those cases there is an even simpler way to write the contents of a StringBuilder to a text file. It can be done with one line of code. It may not be the most efficient but that wasn't really the question now was it.

System.IO.File.WriteAllText(@"C:\MyDir\MyNewTextFile.txt",sbMyStringBuilder.ToString());

How to encode a URL in Swift

URLQueryAllowedCharacterSet should not be used for URL encoding of query parameters because this charset includes &, ?, / etc. which serve as delimiters in a URL query, e.g.

/?paramname=paramvalue&paramname=paramvalue

These characters are allowed in URL queries as a whole but not in parameter values.

RFC 3986 specifically talks about unreserved characters, which are different from allowed:

2.3. Unreserved Characters

Characters that are allowed in a URI but do not have a reserved
purpose are called unreserved. These include uppercase and lowercase letters, decimal digits, hyphen, period, underscore, and tilde.

  unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"

Accordingly:

extension String {
    var URLEncoded:String {
        var URLEncoded:String {
    let unreservedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
    let unreservedCharsSet: CharacterSet = CharacterSet(charactersIn: unreservedChars)
    let encodedString = self.addingPercentEncoding(withAllowedCharacters: unreservedCharsSet)!
    return encodedString
}
    }
}

The code above doesn't make a call to alphanumericCharacterSet because of the enormous size of the charset it returns (103806 characters). And in view of how many Unicode characters alphanumericCharacterSet allows for, using it for the purpose of URL encoding would be simply erroneous.

Usage:

let URLEncodedString = myString.URLEncoded

Run a Python script from another Python script, passing in arguments

import subprocess
subprocess.call(" python script2.py 1", shell=True)

apache mod_rewrite is not working or not enabled

On centOS7 I changed the file /etc/httpd/conf/httpd.conf

from AllowOverride None to AllowOverride All

Excel VBA Open workbook, perform actions, save as, close

I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..

Opening A Seperate File:

ChDir "[Path here]"                          'get into the right folder here
Workbooks.Open Filename:= "[Path here]"      'include the filename in this path

'copy data into current workbook or whatever you want here

ActiveWindow.Close                          'closes out the file

Opening A File With Specified Date If It Exists:

I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.

Some common error checking statements:

On Error Resume Next   'if error occurs continues on to the next line (ignores it)

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

Or (better option):

if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?

you would most likely want to use the GoTo ErrorHandler shown below to achieve this

On Error GoTo ErrorHandler:

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

ErrorHandler:
'Display error message or any code you want to run on error here

Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm


Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/

Hope this helps!


Example on how to ensure error code doesn't run EVERYtime:

if you debug through the code without the Exit Sub BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.

  Sub Macro

    On Error GoTo ErrorHandler:

    ChDir "[Path here]"                         
    Workbooks.Open Filename:= "[Path here]"      'try to open file here

    Exit Sub      'Code will exit BEFORE ErrorHandler if everything goes smoothly
                  'Otherwise, on error, ErrorHandler will be run

    ErrorHandler:
    'Display error message or any code you want to run on error here

  End Sub

Also, look at this other question in you need more reference to how this works: goto block not working VBA


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

You can use HTML,

foreach(...)
echo $data1 . '&nbsp' . $data2 . '&nbsp' . $data3 . '<br/>';

C# Equivalent of SQL Server DataTypes

SQL Server and .Net Data Type mapping

SQL Server and .Net Data Type mapping

Why are Python's 'private' methods not actually private?

It's not like you absolutly can't get around privateness of members in any language (pointer arithmetics in C++, Reflections in .NET/Java).

The point is that you get an error if you try to call the private method by accident. But if you want to shoot yourself in the foot, go ahead and do it.

Edit: You don't try to secure your stuff by OO-encapsulation, do you?

how to insert datetime into the SQL Database table?

DateTime values should be inserted as if they are strings surrounded by single quotes '20201231' but in many cases they need to be casted explicitly to datetime CAST(N'20201231' AS DATETIME) to avoid bad execution plans with CONVERSION_IMPLICIT warnings that affect negatively the performance. Hier is an example:

CREATE TABLE dbo.T(D DATETIME)

--wrong way
INSERT INTO dbo.T (D) VALUES ('20201231'), ('20201231')

Warnings in the execution plan

--better way
INSERT INTO dbo.T (D) VALUES (CAST(N'20201231' AS DATETIME)), (CAST(N'20201231' AS DATETIME))

No warnings

SET NOCOUNT ON usage

I know it's pretty old question. but just for update.

Best way to use "SET NOCOUNT ON" is to put it up as a first statement in your SP and setting it OFF again just before the last SELECT statement.

How to Ping External IP from Java Android

Ping for the google server or any other server

public boolean isConecctedToInternet() {

    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException e)          { e.printStackTrace(); }
    catch (InterruptedException e) { e.printStackTrace(); }
    return false;
}

How can I change the value of the elements in a vector?

Just use:

for (int i = 0; i < v.size(); i++)
{
    v[i] -= valueToSubstract;
}

Or its equivalent (and more readable?):

for (int i = 0; i < v.size(); i++)
    v[i] = v[i] - valueToSubstract;

How do I keep a label centered in WinForms?

You will achive it with setting property Anchor: None.

How to avoid the "divide by zero" error in SQL?

EDIT: I'm getting a lot of downvotes on this recently...so I thought I'd just add a note that this answer was written before the question underwent it's most recent edit, where returning null was highlighted as an option...which seems very acceptable. Some of my answer was addressed to concerns like that of Edwardo, in the comments, who seemed to be advocating returning a 0. This is the case I was railing against.

ANSWER: I think there's an underlying issue here, which is that division by 0 is not legal. It's an indication that something is fundementally wrong. If you're dividing by zero, you're trying to do something that doesn't make sense mathematically, so no numeric answer you can get will be valid. (Use of null in this case is reasonable, as it is not a value that will be used in later mathematical calculations).

So Edwardo asks in the comments "what if the user puts in a 0?", and he advocates that it should be okay to get a 0 in return. If the user puts zero in the amount, and you want 0 returned when they do that, then you should put in code at the business rules level to catch that value and return 0...not have some special case where division by 0 = 0.

That's a subtle difference, but it's important...because the next time someone calls your function and expects it to do the right thing, and it does something funky that isn't mathematically correct, but just handles the particular edge case it's got a good chance of biting someone later. You're not really dividing by 0...you're just returning an bad answer to a bad question.

Imagine I'm coding something, and I screw it up. I should be reading in a radiation measurement scaling value, but in a strange edge case I didn't anticipate, I read in 0. I then drop my value into your function...you return me a 0! Hurray, no radiation! Except it's really there and it's just that I was passing in a bad value...but I have no idea. I want division to throw the error because it's the flag that something is wrong.

How to get the current date/time in Java

java.util.Date date = new java.util.Date();

It's automatically populated with the time it's instantiated.

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

How do I list loaded plugins in Vim?

:help local-additions

Lists local plugins added.

MySQL CREATE FUNCTION Syntax

MySQL create function syntax:

DELIMITER //

CREATE FUNCTION GETFULLNAME(fname CHAR(250),lname CHAR(250))
    RETURNS CHAR(250)
    BEGIN
        DECLARE fullname CHAR(250);
        SET fullname=CONCAT(fname,' ',lname);
        RETURN fullname;
    END //

DELIMITER ;

Use This Function In Your Query

SELECT a.*,GETFULLNAME(a.fname,a.lname) FROM namedbtbl as a


SELECT GETFULLNAME("Biswarup","Adhikari") as myname;

Watch this Video how to create mysql function and how to use in your query

Create Mysql Function Video Tutorial

C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

example:

c++ -Wall filefork.cpp -lrt -O2

For gcc version 4.6.1, -lrt must be after filefork.cpp otherwise you get a link error.

Some older gcc version doesn't care about the position.

How does the stack work in assembly language?

stack is part of memory. it use for input and output of functions. also it use for remembering function's return.

esp register is remember the stack address.

stack and esp are implemented by hardware. also you can implement it yourself. it will make your program very slow.

example:

nop // esp = 0012ffc4

push 0 //esp = 0012ffc0 ,Dword[0012ffc0]=00000000

call proc01 // esp = 0012ffbc ,Dword[0012ffbc] = eip , eip = adrr[proc01]

pop eax // eax = Dword[esp], esp = esp + 4

Insert multiple rows with one query MySQL

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "myDB";


// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]');";

$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";

$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";


 if ($conn->multi_query($sql) === TRUE) {

  echo "New records created successfully";

 } else {

   echo "Error: " . $sql . "<br>" . $conn->error;

}

$conn->close();

Source W3schools

What is the best way to ensure only one instance of a Bash script is running?

One line ultimate solution:

[ "$(pgrep -fn $0)" -ne "$(pgrep -fo $0)" ] && echo "At least 2 copies of $0 are running"

How to restart Jenkins manually?

If nothing works then find the Jenkins process by

ps aux | grep java

and then kill it:

kill -9 [PID]

sudo service jenkins start

Edit : Look for the java process which is related to jenkins

How do I write a batch script that copies one directory to another, replaces old files?

In your batch file do this

set source=C:\Users\Habib\test
set destination=C:\Users\Habib\testdest\
xcopy %source% %destination% /y

If you want to copy the sub directories including empty directories then do:

xcopy %source% %destination% /E /y

If you only want to copy sub directories and not empty directories then use /s like:

xcopy %source% %destination% /s /y

Create a list from two object lists with linq

Does the following code work for your problem? I've used a foreach with a bit of linq inside to do the combining of lists and assumed that people are equal if their names match, and it seems to print the expected values out when run. Resharper doesn't offer any suggestions to convert the foreach into linq so this is probably as good as it'll get doing it this way.

public class Person
{
   public string Name { get; set; }
   public int Value { get; set; }
   public int Change { get; set; }

   public Person(string name, int value)
   {
      Name = name;
      Value = value;
      Change = 0;
   }
}


class Program
{
   static void Main(string[] args)
   {
      List<Person> list1 = new List<Person>
                              {
                                 new Person("a", 1),
                                 new Person("b", 2),
                                 new Person("c", 3),
                                 new Person("d", 4)
                              };
      List<Person> list2 = new List<Person>
                              {
                                 new Person("a", 4),
                                 new Person("b", 5),
                                 new Person("e", 6),
                                 new Person("f", 7)
                              };

      List<Person> list3 = list2.ToList();

      foreach (var person in list1)
      {
         var existingPerson = list3.FirstOrDefault(x => x.Name == person.Name);
         if (existingPerson != null)
         {
            existingPerson.Change = existingPerson.Value - person.Value;
         }
         else
         {
            list3.Add(person);
         }
      }

      foreach (var person in list3)
      {
         Console.WriteLine("{0} {1} {2} ", person.Name,person.Value,person.Change);
      }
      Console.Read();
   }
}

Static Vs. Dynamic Binding in Java

Because the compiler knows the binding at compile time. If you invoke a method on an interface, for example, then the compiler can't know and the binding is resolved at runtime because the actual object having a method invoked on it could possible be one of several. Therefore that is runtime or dynamic binding.

Your invocation is bound to the Animal class at compile time because you've specified the type. If you passed that variable into another method somewhere else, noone would know (apart from you because you wrote it) what actual class it would be. The only clue is the declared type of Animal.

How to validate array in Laravel?

I have this array as my request data from a HTML+Vue.js data grid/table:

[0] => Array
    (
        [item_id] => 1
        [item_no] => 3123
        [size] => 3e
    )
[1] => Array
    (
        [item_id] => 2
        [item_no] => 7688
        [size] => 5b
    )

And use this to validate which works properly:

$this->validate($request, [
    '*.item_id' => 'required|integer',
    '*.item_no' => 'required|integer',
    '*.size'    => 'required|max:191',
]);

Extract only right most n letters from a string

Use this:

String text = "PER 343573";
String numbers = text;
if (text.Length > 6)
{
    numbers = text.Substring(text.Length - 6);
}

How to know if other threads have finished?

There are a number of ways you can do this:

  1. Use Thread.join() in your main thread to wait in a blocking fashion for each Thread to complete, or
  2. Check Thread.isAlive() in a polling fashion -- generally discouraged -- to wait until each Thread has completed, or
  3. Unorthodox, for each Thread in question, call setUncaughtExceptionHandler to call a method in your object, and program each Thread to throw an uncaught Exception when it completes, or
  4. Use locks or synchronizers or mechanisms from java.util.concurrent, or
  5. More orthodox, create a listener in your main Thread, and then program each of your Threads to tell the listener that they have completed.

How to implement Idea #5? Well, one way is to first create an interface:

public interface ThreadCompleteListener {
    void notifyOfThreadComplete(final Thread thread);
}

then create the following class:

public abstract class NotifyingThread extends Thread {
  private final Set<ThreadCompleteListener> listeners
                   = new CopyOnWriteArraySet<ThreadCompleteListener>();
  public final void addListener(final ThreadCompleteListener listener) {
    listeners.add(listener);
  }
  public final void removeListener(final ThreadCompleteListener listener) {
    listeners.remove(listener);
  }
  private final void notifyListeners() {
    for (ThreadCompleteListener listener : listeners) {
      listener.notifyOfThreadComplete(this);
    }
  }
  @Override
  public final void run() {
    try {
      doRun();
    } finally {
      notifyListeners();
    }
  }
  public abstract void doRun();
}

and then each of your Threads will extend NotifyingThread and instead of implementing run() it will implement doRun(). Thus when they complete, they will automatically notify anyone waiting for notification.

Finally, in your main class -- the one that starts all the Threads (or at least the object waiting for notification) -- modify that class to implement ThreadCompleteListener and immediately after creating each Thread add itself to the list of listeners:

NotifyingThread thread1 = new OneOfYourThreads();
thread1.addListener(this); // add ourselves as a listener
thread1.start();           // Start the Thread

then, as each Thread exits, your notifyOfThreadComplete method will be invoked with the Thread instance that just completed (or crashed).

Note that better would be to implements Runnable rather than extends Thread for NotifyingThread as extending Thread is usually discouraged in new code. But I'm coding to your question. If you change the NotifyingThread class to implement Runnable then you have to change some of your code that manages Threads, which is pretty straightforward to do.

HighCharts Hide Series Name from the Legend

showInLegend is a series-specific option that can hide the series from the legend. If the requirement is to hide the legends completely then it is better to use enabled: false property as shown below:

legend: { enabled: false }

More information about legend is here

Is there a simple way that I can sort characters in a string in alphabetical order

You can use LINQ:

String.Concat(str.OrderBy(c => c))

If you want to remove duplicates, add .Distinct().

Converting a JToken (or string) to a given Type

var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);

throws a parsing exception due to missing quotes around the first argument (I think). I got it to work by adding the quotes:

var i2 = JsonConvert.DeserializeObject("\"" + obj["id"].ToString() + "\"", type);

Equation for testing if a point is inside a circle

Calculate the Distance

D = Math.Sqrt(Math.Pow(center_x - x, 2) + Math.Pow(center_y - y, 2))
return D <= radius

that's in C#...convert for use in python...

How to get all the AD groups for a particular user?

I would like to say that Microsoft LDAP has some special ways to search recursively for all of memberships of a user.

  1. The Matching Rule you can specify for the "member" attribute. In particular, using the Microsoft Exclusive LDAP_MATCHING_RULE_IN_CHAIN rule for "member" attribute allows recursive/nested membership searching. The rule is used when you add it after the member attribute. Ex. (member:1.2.840.113556.1.4.1941:= XXXXX )

  2. For the same Domain as the Account, The filter can use <SID=S-1-5-21-XXXXXXXXXXXXXXXXXXXXXXX> instead of an Accounts DistinguishedName attribute which is very handy to use cross domain if needed. HOWEVER it appears you need to use the ForeignSecurityPrincipal <GUID=YYYY> as it will not resolve your SID as it appears the <SID=> tag does not consider ForeignSecurityPrincipal object type. You can use the ForeignSecurityPrincipal DistinguishedName as well.

Using this knowledge, you can LDAP query those hard to get memberships, such as the "Domain Local" groups an Account is a member of but unless you looked at the members of the group, you wouldn't know if user was a member.

//Get Direct+Indirect Memberships of User (where SID is XXXXXX)

string str = "(& (objectCategory=group)(member:1.2.840.113556.1.4.1941:=<SID=XXXXXX>) )";

//Get Direct+Indirect **Domain Local** Memberships of User (where SID is XXXXXX)

string str2 = "(& (objectCategory=group)(|(groupType=-2147483644)(groupType=4))(member:1.2.840.113556.1.4.1941:=<SID=XXXXXX>) )";

//TAA DAA



Feel free to try these LDAP queries after substituting the SID of a user you want to retrieve all group memberships of. I figure this is similiar if not the same query as what the PowerShell Command Get-ADPrincipalGroupMembership uses behind the scenes. The command states "If you want to search for local groups in another domain, use the ResourceContextServer parameter to specify the alternate server in the other domain."

If you are familiar enough with C# and Active Directory, you should know how to perform an LDAP search using the LDAP queries provided.

Additional Documentation:

Java: Integer equals vs. ==

The JVM is caching Integer values. Hence the comparison with == only works for numbers between -128 and 127.

Refer: #Immutable_Objects_.2F_Wrapper_Class_Caching

What causes this error? "Runtime error 380: Invalid property value"

What causes runtime error 380? Attempting to set a property of an object or control to a value that is not allowed. Look through the code that runs when your search form loads (Form_Load etc.) for any code that sets a property to something that depends on runtime values.

My other advice is to add some error handling and some logging to track down the exact line that is causing the error.

  • Logging Sprinkle statements through the code that say "Got to X", "Got to Y", etc. Use these to find the exact location of the error. You can write to a text file or the event log or use OutputDebugString.
  • Error handling Here's how to get a stack trace for the error. Add an error handler to every routine that might be involved, like this code below. The essential free tool MZTools can do this automatically. You could also use Erl to report line numbers and find the exact line - MZTools can automatically put in line numbers for you.

_

 On Error Goto Handler
   <routine contents>   
 Handler: 
   Err.Raise Err.Number, "(function_name)->" & Err.source, Err.Description 

Finding a branch point with Git?

To find commits from the branching point, you could use this.

git log --ancestry-path master..topicbranch

Can Json.NET serialize / deserialize to / from a stream?

The current version of Json.net does not allow you to use the accepted answer code. A current alternative is:

public static object DeserializeFromStream(Stream stream)
{
    var serializer = new JsonSerializer();

    using (var sr = new StreamReader(stream))
    using (var jsonTextReader = new JsonTextReader(sr))
    {
        return serializer.Deserialize(jsonTextReader);
    }
}

Documentation: Deserialize JSON from a file stream

How can I change the default Django date template format?

Just use this:

{{you_date_field|date:'Y-m-d'}}

This will show something like 2016-10-16. You can use the format as you want.

Splitting a string at every n-th character

I recently encountered this issue, and here is the solution I came up with

final int LENGTH = 10;
String test = "Here is a very long description, it is going to be past 10";

Map<Integer,StringBuilder> stringBuilderMap = new HashMap<>();
for ( int i = 0; i < test.length(); i++ ) {
    int position = i / LENGTH; // i<10 then 0, 10<=i<19 then 1, 20<=i<30 then 2, etc.

    StringBuilder currentSb = stringBuilderMap.computeIfAbsent( position, pos -> new StringBuilder() ); // find sb, or create one if not present
    currentSb.append( test.charAt( i ) ); // add the current char to our sb
}

List<String> comments = stringBuilderMap.entrySet().stream()
        .sorted( Comparator.comparing( Map.Entry::getKey ) )
        .map( entrySet -> entrySet.getValue().toString() )
        .collect( Collectors.toList() );
//done



// here you can see the data
comments.forEach( cmt -> System.out.println( String.format( "'%s' ... length= %d", cmt, cmt.length() ) ) );
// PRINTS:
// 'Here is a ' ... length= 10
// 'very long ' ... length= 10
// 'descriptio' ... length= 10
// 'n, it is g' ... length= 10
// 'oing to be' ... length= 10
// ' past 10' ... length= 8

// make sure they are equal
String joinedString = String.join( "", comments );
System.out.println( "\nOriginal strings are equal " + joinedString.equals( test ) );
// PRINTS: Original strings are equal true

How to encode the filename parameter of Content-Disposition header in HTTP?

There is discussion of this, including links to browser testing and backwards compatibility, in the proposed RFC 5987, "Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters."

RFC 2183 indicates that such headers should be encoded according to RFC 2184, which was obsoleted by RFC 2231, covered by the draft RFC above.

Is it possible to specify proxy credentials in your web.config?

Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision

ReactJS - Does render get called any time "setState" is called?

Another reason for "lost update" can be the next:

  • If the static getDerivedStateFromProps is defined then it is rerun in every update process according to official documentation https://reactjs.org/docs/react-component.html#updating.
  • so if that state value comes from props at the beginning it is overwrite in every update.

If it is the problem then U can avoid setting the state during update, you should check the state parameter value like this

static getDerivedStateFromProps(props: TimeCorrectionProps, state: TimeCorrectionState): TimeCorrectionState {
   return state ? state : {disable: false, timeCorrection: props.timeCorrection};
}

Another solution is add a initialized property to state, and set it up in the first time (if the state is initialized to non null value.)

How can we draw a vertical line in the webpage?

You can use <hr> for a vertical line as well.
Set the width to 1 and the size(height) as long as you want.
I used 500 in my example(demo):

With <hr width="1" size="500">

DEMO

HttpServletRequest get JSON POST data

Normaly you can GET and POST parameters in a servlet the same way:

request.getParameter("cmd");

But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

Display number with leading zeros

width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted

Import regular CSS file in SCSS file?

Simple workaround:

All, or nearly all css file can be also interpreted as if it would be scss. It also enables to import them inside a block. Rename the css to scss, and import it so.

In my actual configuration I do the following:

First I copy the .css file into a temporary one, this time with .scss extension. Grunt example config:

copy: {
    dev: {
        files: [
            {
                src: "node_modules/some_module/some_precompiled.css",
                dest: "target/resources/some_module_styles.scss"
            }
        ]
    }
}

Then you can import the .scss file from your parent scss (in my example, it is even imported into a block):

my-selector {
  @import "target/resources/some_module_styles.scss";
  ...other rules...
}

Note: this could be dangerous, because it will effectively result that the css will be parsed multiple times. Check your original css for that it contains any scss-interpretable artifact (it is improbable, but if it happen, the result will be hard to debug and dangerous).

How to create a HTML Table from a PHP array?

echo "<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>";
foreach($shop as $v){
    echo "<tr>";
    foreach($v as $vv){
        echo "<td>{$vv}</td>";
    }
    echo "<tr>";
}
echo "</table>";

What parameters should I use in a Google Maps URL to go to a lat-lon?

This doesn't have to be much more complicated than passing in a value for the 'q' parameter. Google is a search engine after all and can handle the same stuff it handles when users type queries into its text boxes

"maps.google.com?/q=32.5234,-78.23432"

How to display pie chart data values of each slice in chart.js

I found an excellent Chart.js plugin that does exactly what you want: https://github.com/emn178/Chart.PieceLabel.js

Getting the filenames of all files in a folder

You could do it like that:

File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
  if (listOfFiles[i].isFile()) {
    System.out.println("File " + listOfFiles[i].getName());
  } else if (listOfFiles[i].isDirectory()) {
    System.out.println("Directory " + listOfFiles[i].getName());
  }
}

Do you want to only get JPEG files or all files?

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

I needed an example using React.Component so I am posting it:

import React from 'react';
import * as Redux from 'react-redux';

class NavigationHeader extends React.Component {

}

const mapStateToProps = function (store) {
    console.log(`mapStateToProps ${store}`);
    return {
        navigation: store.navigation
    };
};

export default Redux.connect(mapStateToProps)(NavigationHeader);

Difference between Visibility.Collapsed and Visibility.Hidden

The difference is that Visibility.Hidden hides the control, but reserves the space it occupies in the layout. So it renders whitespace instead of the control. Visibilty.Collapsed does not render the control and does not reserve the whitespace. The space the control would take is 'collapsed', hence the name.

The exact text from the MSDN:

Collapsed: Do not display the element, and do not reserve space for it in layout.

Hidden: Do not display the element, but reserve space for the element in layout.

Visible: Display the element.

See: http://msdn.microsoft.com/en-us/library/system.windows.visibility.aspx

onclick event function in JavaScript

<script>
//$(document).ready(function () {
function showcontent() {
        document.getElementById("demo22").innerHTML = "Hello World";
}
//});// end of ready function
</script>

I had the same problem where onclick function calls would not work. I had included the function inside the usual "$(document).ready(function(){});" block used to wrap jquery scripts. Commenting this block out solved the problem.

Invalid column name sql error

Code To insert Data in Access Db using c#

Code:-

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace access_db_csharp
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
   public SqlConnection con = new SqlConnection(@"Place Your connection string");
            
           private void Savebutton_Click(object sender, EventArgs e)
    {
         SqlCommand cmd = new SqlCommand("insert into  Data (Name,PhoneNo,Address) values(@parameter1,@parameter2,@parameter3)",con);
                cmd.Parameters.AddWithValue("@parameter1", (textBox1.Text));
                cmd.Parameters.AddWithValue("@parameter2", textBox2.Text);
                cmd.Parameters.AddWithValue("@parameter3", (textBox4.Text));
                cmd.ExecuteNonQuery();

                }

    private void Form1_Load(object sender, EventArgs e)
    {
        con.ConnectionString = connectionstring;
        con.Open();
    }
}
}

how to draw smooth curve through N points using javascript HTML5 canvas?

The first answer will not pass through all the points. This graph will exactly pass through all the points and will be a perfect curve with the points as [{x:,y:}] n such points.

var points = [{x:1,y:1},{x:2,y:3},{x:3,y:4},{x:4,y:2},{x:5,y:6}] //took 5 example points
ctx.moveTo((points[0].x), points[0].y);

for(var i = 0; i < points.length-1; i ++)
{

  var x_mid = (points[i].x + points[i+1].x) / 2;
  var y_mid = (points[i].y + points[i+1].y) / 2;
  var cp_x1 = (x_mid + points[i].x) / 2;
  var cp_x2 = (x_mid + points[i+1].x) / 2;
  ctx.quadraticCurveTo(cp_x1,points[i].y ,x_mid, y_mid);
  ctx.quadraticCurveTo(cp_x2,points[i+1].y ,points[i+1].x,points[i+1].y);
}

Find unique lines

uniq -u has been driving me crazy because it did not work.

So instead of that, if you have python (most Linux distros and servers already have it):

Assuming you have the data file in notUnique.txt

#Python
#Assuming file has data on different lines
#Otherwise fix split() accordingly.

uniqueData = []
fileData = open('notUnique.txt').read().split('\n')

for i in fileData:
  if i.strip()!='':
    uniqueData.append(i)

print uniqueData

###Another option (less keystrokes):
set(open('notUnique.txt').read().split('\n'))

Note that due to empty lines, the final set may contain '' or only-space strings. You can remove that later. Or just get away with copying from the terminal ;)

#

Just FYI, From the uniq Man page:

"Note: 'uniq' does not detect repeated lines unless they are adjacent. You may want to sort the input first, or use 'sort -u' without 'uniq'. Also, comparisons honor the rules specified by 'LC_COLLATE'."

One of the correct ways, to invoke with: # sort nonUnique.txt | uniq

Example run:

$ cat x
3
1
2
2
2
3
1
3

$ uniq x
3
1
2
3
1
3

$ uniq -u x
3
1
3
1
3

$ sort x | uniq
1
2
3

Spaces might be printed, so be prepared!

How do I fill arrays in Java?

In Java-8 you can use IntStream to produce a stream of numbers that you want to repeat, and then convert it to array. This approach produces an expression suitable for use in an initializer:

int[] data = IntStream.generate(() -> value).limit(size).toArray();

Above, size and value are expressions that produce the number of items that you want tot repeat and the value being repeated.

Demo.

Javascript reduce() on Object

What you actually want in this case are the Object.values. Here is a concise ES6 implementation with that in mind:

const add = {
  a: {value:1},
  b: {value:2},
  c: {value:3}
}

const total = Object.values(add).reduce((t, {value}) => t + value, 0)

console.log(total) // 6

or simply:

const add = {
  a: 1,
  b: 2,
  c: 3
}

const total = Object.values(add).reduce((t, n) => t + n)

console.log(total) // 6

Generating statistics from Git repository

git-bars can show you "commits per day/week/year/etc".

You can install it with pip install git-bars (cf. https://github.com/knadh/git-bars)

The output looks like this:

$ git-bars -p month
370 commits over 19 month(s)
2019-10  7    ¯¯¯¯¯¯
2019-09  36   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2019-08  7    ¯¯¯¯¯¯
2019-07  10   ¯¯¯¯¯¯¯¯
2019-05  4    ¯¯¯
2019-04  2    ¯
2019-03  28   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2019-02  32   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2019-01  16   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-12  41   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-11  52   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-10  57   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-09  37   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-08  17   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-07  1    
2018-04  7    ¯¯¯¯¯¯
2018-03  12   ¯¯¯¯¯¯¯¯¯¯
2018-02  2    ¯
2016-01  2    ¯

JavaScript check if value is only undefined, null or false

I think what you're looking for is !!val==false which can be turned to !val (even shorter):

You see:

function checkValue(value) {
    console.log(!!value);
}

checkValue(); // false
checkValue(null); // false
checkValue(undefined); // false
checkValue(false); // false
checkValue(""); // false

checkValue(true); // true
checkValue({}); // true
checkValue("any string"); // true

That works by flipping the value by using the ! operator.

If you flip null once for example like so :

console.log(!null) // that would output --> true

If you flip it twice like so :

console.log(!!null) // that would output --> false

Same with undefined or false.

Your code:

if(val==null || val===false){
  ;
}

would then become:

if(!val) {
  ;
}

That would work for all cases even when there's a string but it's length is zero. Now if you want it to also work for the number 0 (which would become false if it was double flipped) then your if would become:

if(!val && val !== 0) {
  // code runs only when val == null, undefined, false, or empty string ""
}

Google Maps V3 marker with label

Support for single character marker labels was added to Google Maps in version 3.21 (Aug 2015). See the new marker label API.

You can now create your label marker like this:

var marker = new google.maps.Marker({
  position: new google.maps.LatLng(result.latitude, result.longitude), 
  icon: markerIcon,
  label: {
    text: 'A'
  }
});

If you would like to see the 1 character restriction removed, please vote for this issue.

Update October 2016:

This issue was fixed and as of version 3.26.10, Google Maps natively supports multiple character labels in combination with custom icons using MarkerLabels.

How do I reflect over the members of dynamic object?

If the IDynamicMetaObjectProvider can provide the dynamic member names, you can get them. See GetMemberNames implementation in the apache licensed PCL library Dynamitey (which can be found in nuget), it works for ExpandoObjects and DynamicObjects that implement GetDynamicMemberNames and any other IDynamicMetaObjectProvider who provides a meta object with an implementation of GetDynamicMemberNames without custom testing beyond is IDynamicMetaObjectProvider.

After getting the member names it's a little more work to get the value the right way, but Impromptu does this but it's harder to point to just the interesting bits and have it make sense. Here's the documentation and it is equal or faster than reflection, however, unlikely to be faster than a dictionary lookup for expando, but it works for any object, expando, dynamic or original - you name it.

What should my Objective-C singleton look like?

With Objective C class methods, we can just avoid using the singleton pattern the usual way, from:

[[Librarian sharedInstance] openLibrary]

to:

[Librarian openLibrary]

by wrapping the class inside another class that just has Class Methods, that way there is no chance of accidentally creating duplicate instances, as we're not creating any instance!

I wrote a more detailed blog here :)

Javascript : natural sort of alphanumerical strings

Building on @Adrien Be's answer above and using the code that Brian Huisman & David koelle created, here is a modified prototype sorting for an array of objects:

//Usage: unsortedArrayOfObjects.alphaNumObjectSort("name");
//Test Case: var unsortedArrayOfObjects = [{name: "a1"}, {name: "a2"}, {name: "a3"}, {name: "a10"}, {name: "a5"}, {name: "a13"}, {name: "a20"}, {name: "a8"}, {name: "8b7uaf5q11"}];
//Sorted: [{name: "8b7uaf5q11"}, {name: "a1"}, {name: "a2"}, {name: "a3"}, {name: "a5"}, {name: "a8"}, {name: "a10"}, {name: "a13"}, {name: "a20"}]

// **Sorts in place**
Array.prototype.alphaNumObjectSort = function(attribute, caseInsensitive) {
  for (var z = 0, t; t = this[z]; z++) {
    this[z].sortArray = new Array();
    var x = 0, y = -1, n = 0, i, j;

    while (i = (j = t[attribute].charAt(x++)).charCodeAt(0)) {
      var m = (i == 46 || (i >=48 && i <= 57));
      if (m !== n) {
        this[z].sortArray[++y] = "";
        n = m;
      }
      this[z].sortArray[y] += j;
    }
  }

  this.sort(function(a, b) {
    for (var x = 0, aa, bb; (aa = a.sortArray[x]) && (bb = b.sortArray[x]); x++) {
      if (caseInsensitive) {
        aa = aa.toLowerCase();
        bb = bb.toLowerCase();
      }
      if (aa !== bb) {
        var c = Number(aa), d = Number(bb);
        if (c == aa && d == bb) {
          return c - d;
        } else {
          return (aa > bb) ? 1 : -1;
        }
      }
    }

    return a.sortArray.length - b.sortArray.length;
  });

  for (var z = 0; z < this.length; z++) {
    // Here we're deleting the unused "sortArray" instead of joining the string parts
    delete this[z]["sortArray"];
  }
}

How to update a menu item shown in the ActionBar?

For clarity, I thought that a direct example of grabbing onto a resource can be shown from the following that I think contributes to the response for this question with a quick direct example.

private MenuItem menuItem_;

@Override
public boolean onCreateOptionsMenu(Menu menuF) 
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_layout, menuF);
    menuItem_ = menuF.findItem(R.id.menu_item_identifier);
    return true;
}

In this case you hold onto a MenuItem reference at the beginning and then change the state of it (for icon state changes for example) at a later given point in time.

How to display special characters in PHP

This works for me:

Create/edit .htaccess file with these lines:

AddDefaultCharset UTF-8
AddCharset UTF-8 .php

If you prefer create/edit php.ini:

default_charset = "utf-8"

Sources:

How to turn off word wrapping in HTML?

Added webkit specific values missing from above

white-space: -moz-pre-wrap; /* Firefox */
white-space: -o-pre-wrap; /* Opera */
white-space: pre-wrap; /* Chrome */
word-wrap: break-word; /* IE */

File upload along with other object in Jersey restful web service

Your ApplicationConfig should register the MultiPartFeature.class from the glassfish.jersey.media.. so as to enable file upload

@javax.ws.rs.ApplicationPath(ResourcePath.API_ROOT)
public class ApplicationConfig extends ResourceConfig {  
public ApplicationConfig() {
        //register the necessary headers files needed from client
        register(CORSConfigurationFilter.class);
        //The jackson feature and provider is used for object serialization
        //between client and server objects in to a json
        register(JacksonFeature.class);
        register(JacksonProvider.class);
        //Glassfish multipart file uploader feature
        register(MultiPartFeature.class);
        //inject and registered all resources class using the package
        //not to be tempered with
        packages("com.flexisaf.safhrms.client.resources");
        register(RESTRequestFilter.class);
    }

How to generate XML file dynamically using PHP?

$query=mysql_query("select * from tablename")or die(mysql_error()); 
$xml="<libraray>\n\t\t";
while($data=mysql_fetch_array($query))
{

    $xml .="<mail_address>\n\t\t";
    $xml .= "<id>".$data['id']."</id>\n\t\t";
    $xml .= "<email>".$data['email_address']."</email>\n\t\t";
    $xml .= "<verify_code>".$data['verify']."</verify_code>\n\t\t";
    $xml .= "<status>".$data['status']."</status>\n\t\t";
    $xml.="</mail_address>\n\t";
}
$xml.="</libraray>\n\r";
$xmlobj=new SimpleXMLElement($xml);
$xmlobj->asXML("text.xml");

Its simple just connect with your database it will create test.xml file in your project folder

"Thinking in AngularJS" if I have a jQuery background?

jQuery

jQuery makes ridiculously long JavaScript commands like getElementByHerpDerp shorter and cross-browser.

AngularJS

AngularJS allows you to make your own HTML tags/attributes that do things which work well with dynamic web applications (since HTML was designed for static pages).

Edit:

Saying "I have a jQuery background how do I think in AngularJS?" is like saying "I have an HTML background how do I think in JavaScript?" The fact that you're asking the question shows you most likely don't understand the fundamental purposes of these two resources. This is why I chose to answer the question by simply pointing out the fundamental difference rather than going through the list saying "AngularJS makes use of directives whereas jQuery uses CSS selectors to make a jQuery object which does this and that etc....". This question does not require a lengthy answer.

jQuery is a way to make programming JavaScript in the browser easier. Shorter, cross-browser commands, etc.

AngularJS extends HTML, so you don't have to put <div> all over the place just to make an application. It makes HTML actually work for applications rather than what it was designed for, which is static, educational web pages. It accomplishes this in a roundabout way using JavaScript, but fundamentally it is an extension of HTML, not JavaScript.

How to build jars from IntelliJ properly?

It is probably little bit late, but I managed to solve it this way -> open with winrar and delete ECLIPSEF.RSA and ECLIPSEF.SF in META-INF folder, moreover put "Main-class: main_class_name" (without ".class") in MANIFEST.MF. Make sure that you pressed "Enter" twice after the last line, otherwise it won't work.

JavaScript closure inside loops – simple practical example

The main issue with the code shown by the OP is that i is never read until the second loop. To demonstrate, imagine seeing an error inside of the code

funcs[i] = function() {            // and store them in funcs
    throw new Error("test");
    console.log("My value: " + i); // each should log its value.
};

The error actually does not occur until funcs[someIndex] is executed (). Using this same logic, it should be apparent that the value of i is also not collected until this point either. Once the original loop finishes, i++ brings i to the value of 3 which results in the condition i < 3 failing and the loop ending. At this point, i is 3 and so when funcs[someIndex]() is used, and i is evaluated, it is 3 - every time.

To get past this, you must evaluate i as it is encountered. Note that this has already happened in the form of funcs[i] (where there are 3 unique indexes). There are several ways to capture this value. One is to pass it in as a parameter to a function which is shown in several ways already here.

Another option is to construct a function object which will be able to close over the variable. That can be accomplished thusly

jsFiddle Demo

funcs[i] = new function() {   
    var closedVariable = i;
    return function(){
        console.log("My value: " + closedVariable); 
    };
};

Positive Number to Negative Number in JavaScript?

Math.abs(num) => Always positive
-Math.abs(num) => Always negative

You do realize however, that for your code

if($this.find('.pdxslide-activeSlide').index() < slideNum-1){ slideNum = -slideNum }
console.log(slideNum)

If the index found is 3 and slideNum is 3,
then 3 < 3-1 => false
so slideNum remains positive??

It looks more like a logic error to me.

Should I use @EJB or @Inject

Injection already existed in Java EE 5 with the @Resource, @PersistentUnit or @EJB annotations, for example. But it was limited to certain resources (datasource, EJB . . .) and into certain components (Servlets, EJBs, JSF backing bean . . .). With CDI you can inject nearly anything anywhere thanks to the @Inject annotation.

Scanner is skipping nextLine() after using next() or nextFoo()?

It's because when you enter a number then press Enter, input.nextInt() consumes only the number, not the "end of line". When input.nextLine() executes, it consumes the "end of line" still in the buffer from the first input.

Instead, use input.nextLine() immediately after input.nextInt()

oracle diff: how to compare two tables?

select * from table1 where table1.col1 in (select table2.col1 from table2)

Assuming col1 is the primary key column and this will give all rows in table1 respective to the table2 column 1.

select * from table1 where table1.col1 not in (select table2.col1 from table2)

Hope this helps

The import org.apache.commons cannot be resolved in eclipse juno

The mentioned package/classes are not present in the compiletime classpath. Basically, Java has no idea what you're talking about when you say to import this and that. It can't find them in the classpath.

It's part of Apache Commons FileUpload. Just download the JAR and drop it in /WEB-INF/lib folder of the webapp project and this error should disappear. Don't forget to do the same for Apache Commons IO, that's where FileUpload depends on, otherwise you will get the same problem during runtime.


Unrelated to the concrete problem, I see that you're using Tomcat 7, which is a Servlet 3.0 compatible container. Do you know that you can just use the new request.getPart() method to obtain the uploaded file without the need for the whole Commons FileUpload stuff? Just add @MultipartConfig annotation to the servlet class so that you can use it. See also How to upload files to server using JSP/Servlet?

How to edit a JavaScript alert box title?

I Found this Sweetalert for customize header box javascript.

For example

swal({
  title: "Are you sure?",
  text: "You will not be able to recover this imaginary file!",
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "Yes, delete it!",
  closeOnConfirm: false
},
function(){
  swal("Deleted!", "Your imaginary file has been deleted.", "success");
});

How to install SimpleJson Package for Python

Download the source code, unzip it to and directory, and execute python setup.py install.

How to show PIL images on the screen?

I tested this and it works fine for me:

from PIL import Image
im = Image.open('image.jpg')
im.show()

Virtual network interface in Mac OS X

Go to Network Preferences.

At the bottom of the list of network adapters, click the + icons

Select the existing interface that you want to arp (say Ethernet 1), and give the Service Name that you want for the new port (say Ethernet 1.1) then press create.

Now you have the new virtual interface in the gui and can manage IP addresses etc it in the normal way.

ifconfig -a will confirm that you have multiple IPs on the interface, and these will still be there when you reboot.

Its a Mac. Don't fight it, do it the easy way.

favicon not working in IE

Run Internet Explorer as Administrator. If you open IE in normal mode then favicon will not display on IE 11 (Win 7). I am not sure about the behavior on other version of browsers.

How to maintain a Unique List in Java?

You may want to use one of the implementing class of java.util.Set<E> Interface e.g. java.util.HashSet<String> collection class.

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

source command not found in sh shell

Bourne shell (sh) uses PATH to locate in source <file>. If the file you are trying to source is not in your path, you get the error 'file not found'.

Try:

source ./<filename>

Does Visual Studio Code have box select/multi-line edit?

The shortcuts I use in Visual Studio for multiline (aka box) select are Shift + Alt + up/down/left/right

To create this in Visual Studio Code you can add these keybindings to the keybindings.json file (menu FilePreferencesKeyboard shortcuts).

{ "key": "shift+alt+down", "command": "editor.action.insertCursorBelow",
                                 "when": "editorTextFocus" },
{ "key": "shift+alt+up", "command": "editor.action.insertCursorAbove",
                                 "when": "editorTextFocus" },
{ "key": "shift+alt+right", "command": "cursorRightSelect",
                                     "when": "editorTextFocus" },
{ "key": "shift+alt+left", "command": "cursorLeftSelect",
                                     "when": "editorTextFocus" }

Entity Framework: table without primary key

From a practical standpoint, every table--even a denormalized table like a warehouse table--should have a primary key. Or, failing that, it should at least have a unique, non-nullable index.

Without some kind of unique key, duplicate records can (and will) appear in the table, which is very problematic both for ORM layers and also for basic comprehension of the data. A table that has duplicate records is probably a symptom of bad design.

At the very least, the table should at least have an identity column. Adding an auto-generating ID column takes about 2 minutes in SQL Server and 5 minutes in Oracle. For that extra bit of effort, many, many problems will be avoided.

Push method in React Hooks (useState)?

To expand a little further, here are some common examples. Starting with:

const [theArray, setTheArray] = useState(initialArray);
const [theObject, setTheObject] = useState(initialObject);

Push element at end of array

setTheArray(prevArray => [...prevArray, newValue])

Push/update element at end of object

setTheObject(prevState => ({ ...prevState, currentOrNewKey: newValue}));

Push/update element at end of array of objects

setTheArray(prevState => [...prevState, {currentOrNewKey: newValue}]);

Push element at end of object of arrays

let specificArrayInObject = theObject.array.slice();
specificArrayInObject.push(newValue);
const newObj = { ...theObject, [event.target.name]: specificArrayInObject };
theObject(newObj);

Here are some working examples too. https://codesandbox.io/s/reacthooks-push-r991u

How to switch between python 2.7 to python 3 from command line?

There is an easier way than all of the above; You can use the PY_PYTHON environment variable. From inside the cmd.exe shell;

For the latest version of Python 2

set PY_PYTHON=2

For the latest version of Python 3

set PY_PYTHON=3

If you want it to be permanent, set it in the control panel. Or use setx instead of set in the cmd.exe shell.

How do I seed a random class to avoid getting duplicate random values

I use this for most situations, keep the seed if there is a need to repeat the sequence

    var seed = (int) DateTime.Now.Ticks;
    var random = new Random(seed);

or

    var random = new Random((int)DateTime.Now.Ticks);

Saving a high resolution image in R

You can do the following. Add your ggplot code after the first line of code and end with dev.off().

tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()

res=300 specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.

Change width and height in the code above depending on the desired output.

Note that this also works for other R plots including plot, image, and pheatmap.

Other file formats

In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.

How should I remove all the leading spaces from a string? - swift

I'd use this extension, to be flexible and mimic how other collections do it:

extension String {
    func filter(pred: Character -> Bool) -> String {
        var res = String()
        for c in self.characters {
            if pred(c) {
                res.append(c)
            }
        }
        return res
    }
}

"this is a String".filter { $0 != Character(" ") } // "thisisaString"

What's the maximum value for an int in PHP?

It depends on your OS, but 2147483647 is the usual value, according to the manual.

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

You only need to delete one folder it is throwing error for. Just go to your M2 repo and org/apache/maven/plugins/maven-compiler-plugins and delete the folder 2.3.2

How to check all checkboxes using jQuery?

html :

    <div class="col-md-3 general-sidebar" id="CategoryGrid">
                                                    <h5>Category &amp; Sub Category <span style="color: red;">* </span></h5>
                                                    <div class="checkbox">
                                                        <label>
                                                            <input onclick="checkUncheckAll(this)" type="checkbox">
                                                            All
                                                        </label>
                                                    </div>
                                                <div class="checkbox"><label><input class="cat" type="checkbox" value="Quality">Quality</label></div>
<div class="checkbox"><label><input class="subcat" type="checkbox" value="Planning process and execution">Planning process and execution</label></div>

javascript:

function checkUncheckAll(ele) {
    if (ele.checked) {
        $('.cat').prop('checked', ele.checked);
        $('.subcat').prop('checked', ele.checked);
    }
    else {
        $('.cat').prop('checked', ele.checked);
        $('.subcat').prop('checked', ele.checked);
    }
}

How to give a Linux user sudo access?

Edit /etc/sudoers file either manually or using the visudo application. Remember: System reads /etc/sudoers file from top to the bottom, so you could overwrite a particular setting by putting the next one below. So to be on the safe side - define your access setting at the bottom.

Angular JS break ForEach

onSelectionChanged(event) {
    let selectdata = event['api']['immutableService']['gridOptionsWrapper']['gridOptions']['rowData'];
    let selected_flag = 0;

    selectdata.forEach(data => {
      if (data.selected == true) {
        selected_flag = 1;
      }
    });

    if (selected_flag == 1) {
      this.showForms = true;
    } else {
      this.showForms = false;
    }
}

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

I've changed the recursion to iteration.

def MovingTheBall(listOfBalls,position,numCell):
while 1:
    stop=1
    positionTmp = (position[0]+choice([-1,0,1]),position[1]+choice([-1,0,1]),0)
    for i in range(0,len(listOfBalls)):
        if positionTmp==listOfBalls[i].pos:
            stop=0
    if stop==1:
        if (positionTmp[0]==0 or positionTmp[0]>=numCell or positionTmp[0]<=-numCell or positionTmp[1]>=numCell or positionTmp[1]<=-numCell):
            stop=0
        else:
            return positionTmp

Works good :D

MS Access - execute a saved query by name in VBA

Thre are 2 ways to run Action Query in MS Access VBA:


  1. You can use DoCmd.OpenQuery statement. This allows you to control these warnings:

Action Query Warning Example

BUT! Keep in mind that DoCmd.SetWarnings will remain set even after the function completes. This means that you need to make sure that you leave it in a condition that suits your needs

Function RunActionQuery(QueryName As String)
    On Error GoTo Hell              'Set Error Hanlder
    DoCmd.SetWarnings True          'Turn On Warnings
    DoCmd.OpenQuery QueryName       'Execute Action Query
    DoCmd.SetWarnings False         'Turn On Warnings
    Exit Function
Hell:
    If Err.Number = 2501 Then       'If Query Was Canceled
        MsgBox Err.Description, vbInformation
    Else                            'Everything else
        MsgBox Err.Description, vbCritical
    End If
End Function

  1. You can use CurrentDb.Execute method. This alows you to keep Action Query failures under control. The SetWarnings flag does not affect it. Query is executed always without warnings.
Function RunActionQuery()
    'To Catch the Query Error use dbFailOnError option
    On Error GoTo Hell
    CurrentDb.Execute "Query1", dbFailOnError
    Exit Function
Hell:
    Debug.Print Err.Description
End Function

It is worth noting that the dbFailOnError option responds only to data processing failures. If the Query contains an error (such as a typo), then a runtime error is generated, even if this option is not specified


In addition, you can use DoCmd.Hourglass True and DoCmd.Hourglass False to control the mouse pointer if your Query takes longer

using href links inside <option> tag

The <select> tag creates a dropdown list. You can't put html links inside a dropdown.

However, there are JavaScript libraries that provide similar functionality. Here is one example: http://www.dynamicdrive.com/dynamicindex1/dropmenuindex.htm

Bootstrap $('#myModal').modal('show') is not working

the solution of 'bootstrap modal is not opening' is, put your Jquery CDN first in the head tag (after starting head tag).

I wasted two days in finding this problem.

Installing specific laravel version with composer create-project

If you want to use a stable version of your preferred Laravel version of choice, use:

composer create-project --prefer-dist laravel/laravel project-name "5.5.*"

That will pick out the most recent or best update of version 5.5.* (5.5.28)

Deck of cards JAVA

There are many errors in your code, for example you are not really calling your deck by just typing deck in your Shuffle method. You can only call it by typing theCard.deck

I have changed your shuffle method:

public void Shuffle(){
    for (int i = 0; i < theCard.deck.length; i++) {
        int index = (int)(Math.random()*theCard.deck.length );
        int temp = theCard.deck[i];
        theCard.deck[i] = theCard.deck[index];
        theCard.deck[index] = temp;
        remainingCards--;
    }
}

Also, as it is said you have structural problem. You should name classes as you understand in real life, for example, when you say card, it is only one card, when you say deck it is supposed to be 52+2 cards. In this way your code would be more understandable.

In Java, how do you determine if a thread is running?

I think you can use GetState(); It can return the exact state of a thread.

ImportError: no module named win32api

I had an identical problem, which I solved by restarting my Python editor and shell. I had installed pywin32 but the new modules were not picked up until the restarts.

If you've already done that, do a search in your Python installation for win32api and you should find win32api.pyd under ${PYTHON_HOME}\Lib\site-packages\win32.

How to find good looking font color if background color is known?

Have you considered letting the user of your application select their own color scheme? Without fail you won't be able to please all of your users with your selection but you can allow them to find what pleases them.

Attach the Java Source Code

The option provided by"praveenak" can also be applied to any other jar files with source file provided. For example, for JavaFx, we right click jfxrt.jar, select "Properties" and enter jdk1.8.0_05/javafx-src.zip for "Path" under External location.

Calculate correlation for more than two variables?

Use the same function (cor) on a data frame, e.g.:

> cor(VADeaths)
             Rural Male Rural Female Urban Male Urban Female
Rural Male    1.0000000    0.9979869  0.9841907    0.9934646
Rural Female  0.9979869    1.0000000  0.9739053    0.9867310
Urban Male    0.9841907    0.9739053  1.0000000    0.9918262
Urban Female  0.9934646    0.9867310  0.9918262    1.0000000

Or, on a data frame also holding discrete variables, (also sometimes referred to as factors), try something like the following:

> cor(mtcars[,unlist(lapply(mtcars, is.numeric))])
            mpg        cyl       disp         hp        drat         wt        qsec         vs          am       gear        carb
mpg   1.0000000 -0.8521620 -0.8475514 -0.7761684  0.68117191 -0.8676594  0.41868403  0.6640389  0.59983243  0.4802848 -0.55092507
cyl  -0.8521620  1.0000000  0.9020329  0.8324475 -0.69993811  0.7824958 -0.59124207 -0.8108118 -0.52260705 -0.4926866  0.52698829
disp -0.8475514  0.9020329  1.0000000  0.7909486 -0.71021393  0.8879799 -0.43369788 -0.7104159 -0.59122704 -0.5555692  0.39497686
hp   -0.7761684  0.8324475  0.7909486  1.0000000 -0.44875912  0.6587479 -0.70822339 -0.7230967 -0.24320426 -0.1257043  0.74981247
drat  0.6811719 -0.6999381 -0.7102139 -0.4487591  1.00000000 -0.7124406  0.09120476  0.4402785  0.71271113  0.6996101 -0.09078980
wt   -0.8676594  0.7824958  0.8879799  0.6587479 -0.71244065  1.0000000 -0.17471588 -0.5549157 -0.69249526 -0.5832870  0.42760594
qsec  0.4186840 -0.5912421 -0.4336979 -0.7082234  0.09120476 -0.1747159  1.00000000  0.7445354 -0.22986086 -0.2126822 -0.65624923
vs    0.6640389 -0.8108118 -0.7104159 -0.7230967  0.44027846 -0.5549157  0.74453544  1.0000000  0.16834512  0.2060233 -0.56960714
am    0.5998324 -0.5226070 -0.5912270 -0.2432043  0.71271113 -0.6924953 -0.22986086  0.1683451  1.00000000  0.7940588  0.05753435
gear  0.4802848 -0.4926866 -0.5555692 -0.1257043  0.69961013 -0.5832870 -0.21268223  0.2060233  0.79405876  1.0000000  0.27407284
carb -0.5509251  0.5269883  0.3949769  0.7498125 -0.09078980  0.4276059 -0.65624923 -0.5696071  0.05753435  0.2740728  1.00000000

Python style - line continuation with strings?

This is a pretty clean way to do it:

myStr = ("firstPartOfMyString"+
         "secondPartOfMyString"+
         "thirdPartOfMyString")

Select multiple rows with the same value(s)

This may work for you:

select t1.*
from table t1
join (select t2.Chromosome, t2.Locus
    from table2
    group by t2.Chromosome, t2.Locus
    having count(*) > 1) u on u.Chromosome = t1.Chromosome and u.Locus = t1.Locus

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

This works for me:

@Transactional
public void remove(Integer groupId) {
    Group group = groupRepository.findOne(groupId);
    group.getUsers().removeAll(group.getUsers());

    // Other business logic

    groupRepository.delete(group);
}

Also, mark the method @Transactional (org.springframework.transaction.annotation.Transactional), this will do whole process in one session, saves some time.

How to read file binary in C#?

Generally, I don't really see a possible way to do this. I've exhausted all of the options that the earlier comments gave you, and they don't seem to work. You could try this:

        `private void button1_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.InitialDirectory = "This PC\\Documents";
        openFileDialog1.Filter = "All Files (*.*)|*.*";
        openFileDialog1.FilterIndex = 1;
        openFileDialog1.RestoreDirectory = true;
        openFileDialog1.Title = "Open a file with code";

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string exeCode = string.Empty;
            using (BinaryReader br = new BinaryReader(File.OpenRead(openFileDialog1.FileName))) //Sets a new integer to the BinaryReader
            {
                br.BaseStream.Seek(0x4D, SeekOrigin.Begin); //The seek is starting from 0x4D
                exeCode = Encoding.UTF8.GetString(br.ReadBytes(1000000000)); //Reads as many bytes as it can from the beginning of the .exe file
            }
            using (BinaryReader br = new BinaryReader(File.OpenRead(openFileDialog1.FileName)))
                br.Close(); //Closes the BinaryReader. Without it, opening the file with any other command will result the error "This file is being used by another process".

            richTextBox1.Text = exeCode;
        }
    }`
  • That's the code for the "Open..." button, but here's the code for the "Save..." button:

    ` private void button2_Click(object sender, EventArgs e) { SaveFileDialog save = new SaveFileDialog();

        save.Filter = "All Files (*.*)|*.*";
        save.Title = "Save Your Changes";
        save.InitialDirectory = "This PC\\Documents";
        save.FilterIndex = 1;
    
        if (save.ShowDialog() == DialogResult.OK)
        {
    
            using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(save.FileName))) //Sets a new integer to the BinaryReader
            {
                bw.BaseStream.Seek(0x4D, SeekOrigin.Begin); //The seek is starting from 0x4D
                bw.Write(richTextBox1.Text);
            }
        }
    }`
    
    • That's the save button. This works fine, but only shows the '!This cannot be run in DOS-Mode!' - Otherwise, if you can fix this, I don't know what to do.

    • My Site

Fatal error: Call to undefined function imap_open() in PHP

I had the same issue. After changing a semicolon in the php.ini file I solved my problem. Let's see how can you solve it?

First, open php.ini file. xampp/php/php.ini

Search extension=imap

remove semicolon before extension and save this file.

Code before remove semicolon ;extension=imap

Code after remove semicolon extension=imap

Finally, open the XAMPP Control panel and restart Apache.

UPDATE with CASE and IN - Oracle

Got a solution that runs. Don't know if it is optimal though. What I do is to split the string according to http://blogs.oracle.com/aramamoo/2010/05/how_to_split_comma_separated_string_and_pass_to_in_clause_of_select_statement.html

Using:
select regexp_substr(' 1, 2 , 3 ','[^,]+', 1, level) from dual
connect by regexp_substr('1 , 2 , 3 ', '[^,]+', 1, level) is not null;

So my final code looks like this ($bp_gr1' are strings like 1,2,3):

UPDATE TAB1
SET    BUDGPOST_GR1 =
          CASE
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( '$BP_GR1',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR1',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR1'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( ' $BP_GR2',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR2',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR2'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( ' $BP_GR3',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR3',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR3'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( '$BP_GR4',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR4',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR4'
             ELSE
                'SAKNAR BUDGETGRUPP'
          END;

Is there a way to make it run faster?

rails simple_form - hidden field - create?

try this

= f.input :title, :as => :hidden, :input_html => { :value => "some value" }

Add common prefix to all cells in Excel

Type this in cell B1, and copy down...

="X"&A1

This would also work:

=CONCATENATE("X",A1)

And here's one of many ways to do this in VBA (Disclaimer: I don't code in VBA very often!):

Sub AddX()
    Dim i As Long

    With ActiveSheet
    For i = 1 To .Range("A65536").End(xlUp).Row Step 1
        .Cells(i, 2).Value = "X" & Trim(Str(.Cells(i, 1).Value))
    Next i
    End With
End Sub

Call to undefined method mysqli_stmt::get_result

So if the MySQL Native Driver (mysqlnd) driver is not available, and therefore using bind_result and fetch instead of get_result, the code becomes:

include 'conn.php';
$conn = new Connection();
$query = 'SELECT EmailVerified, Blocked FROM users WHERE Email = ? AND SLA = ? AND `Password` = ?';
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('sss', $_POST['EmailID'], $_POST['SLA'], $_POST['Password']);
$stmt->execute();
$stmt->bind_result($EmailVerified, $Blocked);
while ($stmt->fetch())
{
   /* Use $EmailVerified and $Blocked */
}
$stmt->close();
$conn->mysqli->close();

Which UUID version to use?

Postgres documentation describes the differences between UUIDs. A couple of them:

V3:

uuid_generate_v3(namespace uuid, name text) - This function generates a version 3 UUID in the given namespace using the specified input name.

V4:

uuid_generate_v4 - This function generates a version 4 UUID, which is derived entirely from random numbers.

Get HTML source of WebElement in Selenium WebDriver using Python

The method to get the rendered HTML I prefer is the following:

driver.get("http://www.google.com")
body_html = driver.find_element_by_xpath("/html/body")
print body_html.text

However, the above method removes all the tags (yes, the nested tags as well) and returns only text content. If you interested in getting the HTML markup as well, then use the method below.

print body_html.getAttribute("innerHTML")

Return multiple values from a function, sub or type?

You can also use a variant array as the return result to return a sequence of arbitrary values:

Function f(i As Integer, s As String) As Variant()
    f = Array(i + 1, "ate my " + s, Array(1#, 2#, 3#))
End Function

Sub test()
    result = f(2, "hat")
    i1 = result(0)
    s1 = result(1)
    a1 = result(2)
End Sub

Ugly and bug prone because your caller needs to know what's being returned to use the result, but occasionally useful nonetheless.

Clear the form field after successful submission of php form

Put the onClick function in the button submit:

<input type="text" id="firstname">
<input type="text" id="lastname">
<input type="submit" value="Submit" onClick="clearform();" />

In the <head>, define the function clearform(), and set the textbox value to "":

function clearform()
{
    document.getElementById("firstname").value=""; //don't forget to set the textbox id
    document.getElementById("lastname").value="";
}

This way the textbox will be cleared when you click the submit button.

How do I get the current date and current time only respectively in Django?

A related info, to the question...

In django, use timezone.now() for the datetime field, as django supports timezone, it just returns datetime based on the USE TZ settings, or simply timezone 'aware' datetime objects

For a reference, I've got TIME_ZONE = 'Asia/Kolkata' and USE_TZ = True,

from django.utils import timezone
import datetime

print(timezone.now())  # The UTC time
print(timezone.localtime())  # timezone specified time, 
print(datetime.datetime.now())  # default local time

# output
2020-12-11 09:13:32.430605+00:00
2020-12-11 14:43:32.430605+05:30  # IST is UTC+5:30
2020-12-11 14:43:32.510659

refer timezone settings and Internationalization and localization in django docs for more details.

Using sed to split a string with a delimiter

If you're using gnu sed then you can use \x0A for newline:

sed 's/:/\x0A/g' ~/Desktop/myfile.txt

Lotus Notes email as an attachment to another email

I might be very late but encoutered this problem sometime before and saw this link. Thanks . Please check this shall work.

Goto Create menu -> Section--> Copy email to be inserted

Waiting for Target Device to Come Online

Like urupvog's answer, make sure that you aren't running any other virtual machines like VirtualBox. When I restarted my computer, AVD worked until I started Vagrant for backend development (then it wouldn't launch).

See Android emulator and virtualbox cannot run at same time for more info.

File Upload In Angular?

I've upload file using reference. No package is required to upload file this way.

// code to be written in .ts file

@ViewChild("fileInput") fileInput;

addFile(): void {
let fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
  let fileToUpload = fi.files[0];
    this.admin.addQuestionApi(fileToUpload)
      .subscribe(
        success => {
          this.loading = false;
          this.flashMessagesService.show('Uploaded successfully', {
            classes: ['alert', 'alert-success'],
            timeout: 1000,
          });
        },
        error => {
          this.loading = false;
          if(error.statusCode==401) this.router.navigate(['']);
          else
            this.flashMessagesService.show(error.message, {
              classes: ['alert', 'alert-danger'],
              timeout: 1000,
            });
        });
  }

}

// code to be written in service.ts file

addQuestionApi(fileToUpload: any){
var headers = this.getHeadersForMultipart();
let input = new FormData();
input.append("file", fileToUpload);

return this.http.post(this.baseUrl+'addQuestions', input, {headers:headers})
      .map(response => response.json())
      .catch(this.errorHandler);

}

// code to be written in html

<input type="file" #fileInput>

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

Simple! Throw this at the like, bottom of your CSS file and this part of the CSS will be modified within a phone: -

/* ON A PHONE */
@media only screen and (max-width: 600px) { /* CSS HERE ONLY ON PHONE */ }

And voila!

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

There's one big difference between CLOCK_REALTIME and MONOTONIC. CLOCK_REALTIME can jump forward or backward according to NTP. By default, NTP allows the clock rate to be speeded up or slowed down by up to 0.05%, but NTP cannot cause the monotonic clock to jump forward or backward.

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

Class.forName() gets a reference to a Class, Class.forName().newInstance() tries to use the no-arg constructor for the Class to return a new instance.

Eloquent get only one column as an array

I came across this question and thought I would clarify that the lists() method of a eloquent builder object was depreciated in Laravel 5.2 and replaced with pluck().

// <= Laravel 5.1
Word_relation::where('word_one', $word_id)->lists('word_one')->toArray();
// >= Laravel 5.2
Word_relation::where('word_one', $word_id)->pluck('word_one')->toArray();

These methods can also be called on a Collection for example

// <= Laravel 5.1
  $collection = Word_relation::where('word_one', $word_id)->get();
  $array = $collection->lists('word_one');

// >= Laravel 5.2
  $collection = Word_relation::where('word_one', $word_id)->get();
  $array = $collection->pluck('word_one');

How to retrieve the last autoincremented ID from a SQLite table?

With SQL Server you'd SELECT SCOPE_IDENTITY() to get the last identity value for the current process.

With SQlite, it looks like for an autoincrement you would do

SELECT last_insert_rowid()

immediately after your insert.

http://www.mail-archive.com/[email protected]/msg09429.html

In answer to your comment to get this value you would want to use SQL or OleDb code like:

using (SqlConnection conn = new SqlConnection(connString))
{
    string sql = "SELECT last_insert_rowid()";
    SqlCommand cmd = new SqlCommand(sql, conn);
    conn.Open();
    int lastID = (Int32) cmd.ExecuteScalar();
}

bundle install returns "Could not locate Gemfile"

When I had similar problem gem update --system helped me. Run this before bundle install

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

Try ISDATE() function in SQL Server. If 1, select valid date. If 0 selects invalid dates.

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail 
WHERE ISDATE(LoginTime) = 1

EDIT :

As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT

SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail 

or

SELECT LEFT(LoginTime,10) FROM AuditTrail

EDIT 2 :

The major reason for the error will be in your date in WHERE clause.ie,

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('06/18/2012' AS DATE)

will be different from

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('18/06/2012' AS DATE)

CONCLUSION

In EDIT 2 the first query tries to filter in mm/dd/yyyy format, while the second query tries to filter in dd/mm/yyyy format. Either of them will fail and throws error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

So please make sure to filter date either with mm/dd/yyyy or with dd/mm/yyyy format, whichever works in your db.

Hide/encrypt password in bash file to stop accidentally seeing it

Following line in above code is not working

DB_PASSWORD=$(eval echo ${DB_PASSWORD} | base64 --decode)

Correct line is:

DB_PASSWORD=`echo $PASSWORD|base64 -d`

And save the password in other file as PASSWORD.

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

Building on what is mentioned in the comments, the simplest solution would be:

@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {

    //whatever

}

class SomeDto {

   private List<WhateverBudgerPerDateDTO> budgetPerDate;


  //getters setters
}

The solution assumes that the HTTP request you are creating actually has

Content-Type:application/json instead of text/plain

When is del useful in Python?

The "del" command is very useful for controlling data in an array, for example:

elements = ["A", "B", "C", "D"]
# Remove first element.
del elements[:1]
print(elements)

Output:

['B', 'C', 'D']

Python Binomial Coefficient

Note that starting Python 3.8, the standard library provides the math.comb function to compute the binomial coefficient:

math.comb(n, k)

which is the number of ways to choose k items from n items without repetition
n! / (k! (n - k)!):

import math
math.comb(10, 5)  # 252
math.comb(10, 10) # 1

Check input value length

<input type='text' minlength=3 /><br />

if browser supports html5,

it will automatical be validate attributes(minlength) in tag

but Safari(iOS) doesn't working

What is `git push origin master`? Help with git's refs, heads and remotes

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.