Programs & Examples On #Bufferedreader

Java class that reads text from a character-input stream, buffering characters so as to provide for an efficient reading of characters, arrays, and lines.

Android Reading from an Input stream efficiently

Have you tried the built in method to convert a stream to a string? It's part of the Apache Commons library (org.apache.commons.io.IOUtils).

Then your code would be this one line:

String total = IOUtils.toString(inputStream);

The documentation for it can be found here: http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#toString%28java.io.InputStream%29

The Apache Commons IO library can be downloaded from here: http://commons.apache.org/io/download_io.cgi

Do I need to close() both FileReader and BufferedReader?

I'm late, but:

BufferReader.java:

public BufferedReader(Reader in) {
  this(in, defaultCharBufferSize);
}

(...)

public void close() throws IOException {
    synchronized (lock) {
        if (in == null)
            return;
        try {
            in.close();
        } finally {
            in = null;
            cb = null;
        }
    }
}

Java using scanner enter key pressed

Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        Double d = scan.nextDouble();


        String newStr = "";
        Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
        while( charScanner.hasNext() ) { 
            String  c = charScanner.next();

            if (c.equalsIgnoreCase("\r")) {
                break;
            }
            else {
                newStr += c;    
            }
        }

        System.out.println("String: " + newStr);
        System.out.println("Int: " + i);
        System.out.println("Double: " + d);

This code works fine

Using BufferedReader.readLine() in a while loop properly

You're calling br.readLine() a second time inside the loop.
Therefore, you end up reading two lines each time you go around.

Scanner vs. BufferedReader

I suggest to use BufferedReader for reading text. Scanner hides IOException while BufferedReader throws it immediately.

Convert InputStream to BufferedReader

InputStream is;
InputStreamReader r = new InputStreamReader(is);
BufferedReader br = new BufferedReader(r);

How to read until end of file (EOF) using BufferedReader in Java?

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

How to use BufferedReader in Java

Try this to read a file:

BufferedReader reader = null;

try {
    File file = new File("sample-file.dat");
    reader = new BufferedReader(new FileReader(file));

    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

JavaScript replace/regex

In terms of pattern interpretation, there's no difference between the following forms:

  • /pattern/
  • new RegExp("pattern")

If you want to replace a literal string using the replace method, I think you can just pass a string instead of a regexp to replace.

Otherwise, you'd have to escape any regexp special characters in the pattern first - maybe like so:

function reEscape(s) {
    return s.replace(/([.*+?^$|(){}\[\]])/mg, "\\$1");
}

// ...

var re = new RegExp(reEscape(pattern), "mg");
this.markup = this.markup.replace(re, value);

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

Maybe check Hibernate Validator 4.0, the Reference Implementation of the JSR 303: Bean Validation.

This is an example of an annotated class:

public class Address {

    @NotNull 
    private String line1;
    private String line2;
    private String zip;
    private String state;

    @Length(max = 20)
    @NotNull
    private String country;

    @Range(min = -2, max = 50, message = "Floor out of range")
    public int floor;

        ...
}

For an introduction, see Getting started with JSR 303 (Bean Validation) – part 1 and part 2 or the "Getting started" section of the reference guide which is part of the Hibernate Validator distribution.

Display an array in a readable/hierarchical format

print_r() is mostly for debugging. If you want to print it in that format, loop through the array, and print the elements out.

foreach($data as $d){
  foreach($d as $v){
    echo $v."\n";
  }
}

Accessing JPEG EXIF rotation data in JavaScript on the client side

If you only want the orientation tag and nothing else and don't like to include another huge javascript library I wrote a little code that extracts the orientation tag as fast as possible (It uses DataView and readAsArrayBuffer which are available in IE10+, but you can write your own data reader for older browsers):

_x000D_
_x000D_
function getOrientation(file, callback) {_x000D_
    var reader = new FileReader();_x000D_
    reader.onload = function(e) {_x000D_
_x000D_
        var view = new DataView(e.target.result);_x000D_
        if (view.getUint16(0, false) != 0xFFD8)_x000D_
        {_x000D_
            return callback(-2);_x000D_
        }_x000D_
        var length = view.byteLength, offset = 2;_x000D_
        while (offset < length) _x000D_
        {_x000D_
            if (view.getUint16(offset+2, false) <= 8) return callback(-1);_x000D_
            var marker = view.getUint16(offset, false);_x000D_
            offset += 2;_x000D_
            if (marker == 0xFFE1) _x000D_
            {_x000D_
                if (view.getUint32(offset += 2, false) != 0x45786966) _x000D_
                {_x000D_
                    return callback(-1);_x000D_
                }_x000D_
_x000D_
                var little = view.getUint16(offset += 6, false) == 0x4949;_x000D_
                offset += view.getUint32(offset + 4, little);_x000D_
                var tags = view.getUint16(offset, little);_x000D_
                offset += 2;_x000D_
                for (var i = 0; i < tags; i++)_x000D_
                {_x000D_
                    if (view.getUint16(offset + (i * 12), little) == 0x0112)_x000D_
                    {_x000D_
                        return callback(view.getUint16(offset + (i * 12) + 8, little));_x000D_
                    }_x000D_
                }_x000D_
            }_x000D_
            else if ((marker & 0xFF00) != 0xFF00)_x000D_
            {_x000D_
                break;_x000D_
            }_x000D_
            else_x000D_
            { _x000D_
                offset += view.getUint16(offset, false);_x000D_
            }_x000D_
        }_x000D_
        return callback(-1);_x000D_
    };_x000D_
    reader.readAsArrayBuffer(file);_x000D_
}_x000D_
_x000D_
// usage:_x000D_
var input = document.getElementById('input');_x000D_
input.onchange = function(e) {_x000D_
    getOrientation(input.files[0], function(orientation) {_x000D_
        alert('orientation: ' + orientation);_x000D_
    });_x000D_
}
_x000D_
<input id='input' type='file' />
_x000D_
_x000D_
_x000D_

values:

-2: not jpeg
-1: not defined

enter image description here

For those using Typescript, you can use the following code:

export const getOrientation = (file: File, callback: Function) => {
  var reader = new FileReader();

  reader.onload = (event: ProgressEvent) => {

    if (! event.target) {
      return;
    }

    const file = event.target as FileReader;
    const view = new DataView(file.result as ArrayBuffer);

    if (view.getUint16(0, false) != 0xFFD8) {
        return callback(-2);
    }

    const length = view.byteLength
    let offset = 2;

    while (offset < length)
    {
        if (view.getUint16(offset+2, false) <= 8) return callback(-1);
        let marker = view.getUint16(offset, false);
        offset += 2;

        if (marker == 0xFFE1) {
          if (view.getUint32(offset += 2, false) != 0x45786966) {
            return callback(-1);
          }

          let little = view.getUint16(offset += 6, false) == 0x4949;
          offset += view.getUint32(offset + 4, little);
          let tags = view.getUint16(offset, little);
          offset += 2;
          for (let i = 0; i < tags; i++) {
            if (view.getUint16(offset + (i * 12), little) == 0x0112) {
              return callback(view.getUint16(offset + (i * 12) + 8, little));
            }
          }
        } else if ((marker & 0xFF00) != 0xFF00) {
            break;
        }
        else {
            offset += view.getUint16(offset, false);
        }
    }
    return callback(-1);
  };

  reader.readAsArrayBuffer(file);
}

What is tail call optimization?

Tail-call optimization is where you are able to avoid allocating a new stack frame for a function because the calling function will simply return the value that it gets from the called function. The most common use is tail-recursion, where a recursive function written to take advantage of tail-call optimization can use constant stack space.

Scheme is one of the few programming languages that guarantee in the spec that any implementation must provide this optimization, so here are two examples of the factorial function in Scheme:

(define (fact x)
  (if (= x 0) 1
      (* x (fact (- x 1)))))

(define (fact x)
  (define (fact-tail x accum)
    (if (= x 0) accum
        (fact-tail (- x 1) (* x accum))))
  (fact-tail x 1))

The first function is not tail recursive because when the recursive call is made, the function needs to keep track of the multiplication it needs to do with the result after the call returns. As such, the stack looks as follows:

(fact 3)
(* 3 (fact 2))
(* 3 (* 2 (fact 1)))
(* 3 (* 2 (* 1 (fact 0))))
(* 3 (* 2 (* 1 1)))
(* 3 (* 2 1))
(* 3 2)
6

In contrast, the stack trace for the tail recursive factorial looks as follows:

(fact 3)
(fact-tail 3 1)
(fact-tail 2 3)
(fact-tail 1 6)
(fact-tail 0 6)
6

As you can see, we only need to keep track of the same amount of data for every call to fact-tail because we are simply returning the value we get right through to the top. This means that even if I were to call (fact 1000000), I need only the same amount of space as (fact 3). This is not the case with the non-tail-recursive fact, and as such large values may cause a stack overflow.

You must add a reference to assembly 'netstandard, Version=2.0.0.0

I think the solution might be this issue on GitHub:

Try add netstandard reference in web.config like this:"

<system.web>
  <compilation debug="true" targetFramework="4.7.1" >
    <assemblies>
      <add assembly="netstandard, Version=2.0.0.0, Culture=neutral, 
            PublicKeyToken=cc7b13ffcd2ddd51"/>
    </assemblies>
  </compilation>
  <httpRuntime targetFramework="4.7.1" />

I realise you're using 4.6.1 but the choice of .NET 4.7.1 is significant as older Framework versions are not fully compatible with .NET Standard 2.0.

I know this from painful experience, when I introduced .NET Standard libraries I had a lot of issues with NUGET packages and references breaking. The other change you need to consider is upgrading to PackageReferences instead of package.config files.

See this guide and you might also want a tool to help the upgrade. It does require a late VS 15.7 version though.

How to unmerge a Git merge?

You can reset your branch to the state it was in just before the merge if you find the commit it was on then.

One way is to use git reflog, it will list all the HEADs you've had. I find that git reflog --relative-date is very useful as it shows how long ago each change happened.

Once you find that commit just do a git reset --hard <commit id> and your branch will be as it was before.

If you have SourceTree, you can look up the <commit id> there if git reflog is too overwhelming.

Reading a text file using OpenFileDialog in windows forms

Here's one way:

Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = theDialog.OpenFile()) != null)
        {
            using (myStream)
            {
                // Insert code to read the stream here.
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
    }
}

Modified from here:MSDN OpenFileDialog.OpenFile

EDIT Here's another way more suited to your needs:

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenFileDialog theDialog = new OpenFileDialog();
    theDialog.Title = "Open Text File";
    theDialog.Filter = "TXT files|*.txt";
    theDialog.InitialDirectory = @"C:\";
    if (theDialog.ShowDialog() == DialogResult.OK)
    {
        string filename = theDialog.FileName;

        string[] filelines = File.ReadAllLines(filename);

        List<Employee> employeeList = new List<Employee>();
        int linesPerEmployee = 4;
        int currEmployeeLine = 0;
        //parse line by line into instance of employee class
        Employee employee = new Employee();
        for (int a = 0; a < filelines.Length; a++)
        {

            //check if to move to next employee
            if (a != 0 && a % linesPerEmployee == 0)
            {
                employeeList.Add(employee);
                employee = new Employee();
                currEmployeeLine = 1;
            }

            else
            {
                currEmployeeLine++;
            }
            switch (currEmployeeLine)
            {
                case 1:
                    employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
                    break;
                case 2:
                    employee.Name = filelines[a].Trim();
                    break;
                case 3:
                    employee.Address = filelines[a].Trim();
                    break;
                case 4:
                    string[] splitLines = filelines[a].Split(' ');

                    employee.Wage = Convert.ToDouble(splitLines[0].Trim());
                    employee.Hours = Convert.ToDouble(splitLines[1].Trim());
                    break;


            }

        }
        //Test to see if it works
        foreach (Employee emp in employeeList)
        {
            MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
                emp.Name + Environment.NewLine +
                emp.Address + Environment.NewLine +
                emp.Wage + Environment.NewLine +
                emp.Hours + Environment.NewLine);
        }
    }
}

Fixed size div?

As reply to Jonathan Sampson, this is the best way to do it, without a clearing div:

.container { width:450px; overflow:hidden }
.cube { width:150px; height:150px; float:left }

<div class="container">
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
</div>

Build Android Studio app via command line

there are two build types to build your application using the Gradle build settings: one for debugging your application — debug — and one for building your final package for release — release mode.

Building in Debug Mode

  • First Navigate to Android studio project Root folder using CMD enter image description here

  • run this command gradlew.bat assembleDebug

  • Output window look like this enter image description here

Build signed apk in Release Mode

  • Edit the build.gradle file to build your project in release mode:

    android {
    ...
    defaultConfig { ... }
    signingConfigs {
        release {
            storeFile file("myreleasekey.keystore")
            storePassword "password"
            keyAlias "MyReleaseKey"
            keyPassword "password"
        }
    }
    buildTypes {
        release {
            ...
            signingConfig signingConfigs.release
        }
    }}
    

enter image description here

  • run this command gradlew.bat assembleRelease

Done.Good Luck!

ReactJS map through Object

Also you can use Lodash to direct convert object to array:

_.toArray({0:{a:4},1:{a:6},2:{a:5}})
[{a:4},{a:6},{a:5}]

In your case:

_.toArray(subjects).map((subject, i) => (
    <li className="travelcompany-input" key={i}>
        <span className="input-label">Name: {subject[name]}</span>
    </li>
))}

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

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

Some good answers, but the problem with all solutions I have tried is that the images doesn´t fade into each other. Instead the first one fades completely out and than the next one fades in.

After a few hours of testing a found this sollution. Thx to http://www.1squarepear.com/adding-a-responsive-bootstrap-image-carousel-that-fades-instead-of-slides/

  1. In the HTML code change from .slide to .fade on the .carousel element
  2. Add this in the css:

    .carousel.fade { opacity: 1; } .carousel.fade .item { transition: opacity ease-out .7s; left: 0; opacity: 0; /* hide all slides */ top: 0; position: absolute; width: 100%; display: block; } .carousel.fade .item:first-child { top: auto; opacity: 1; /* show first slide */ position: relative; } .carousel.fade .item.active { opacity: 1; }

How to comment/uncomment in HTML code

No. Unless you find a tool that does what you described for you.

Making a Sass mixin with optional arguments

You can always assign null to your optional arguments. Here is a simple fix

@mixin box-shadow($top, $left, $blur, $color, $inset:null) { //assigning null to inset value makes it optional
    -webkit-box-shadow: $top $left $blur $color $inset;
    -moz-box-shadow: $top $left $blur $color $inset;
    box-shadow: $top $left $blur $color $inset;
}

Attaching a Sass/SCSS to HTML docs

You can not "attach" a SASS/SCSS file to an HTML document.

SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.

There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.

It's as simple as adding 2 lines of code to your HTML file.

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>

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

nonatomic property means @synthesized methods are not going to be generated threadsafe -- but this is much faster than the atomic property since extra checks are eliminated.

strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

weak ownership means that you don't own it and it just keeps track of the object till the object it was assigned to stays , as soon as the second object is released it loses is value. For eg. obj.a=objectB; is used and a has weak property , than its value will only be valid till objectB remains in memory.

copy property is very well explained here

strong,weak,retain,copy,assign are mutually exclusive so you can't use them on one single object... read the "Declared Properties " section

hoping this helps you out a bit...

Running Groovy script from the command line

#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;

println("hello");

how to implement login auth in node.js

_x000D_
_x000D_
======authorization====== MIDDLEWARE_x000D_
_x000D_
const jwt = require('../helpers/jwt')_x000D_
const User = require('../models/user')_x000D_
_x000D_
module.exports = {_x000D_
  authentication: function(req, res, next) {_x000D_
    try {_x000D_
      const user = jwt.verifyToken(req.headers.token, process.env.JWT_KEY)_x000D_
      User.findOne({ email: user.email }).then(result => {_x000D_
        if (result) {_x000D_
          req.body.user = result_x000D_
          req.params.user = result_x000D_
          next()_x000D_
        } else {_x000D_
          throw new Error('User not found')_x000D_
        }_x000D_
      })_x000D_
    } catch (error) {_x000D_
      console.log('langsung dia masuk sini')_x000D_
_x000D_
      next(error)_x000D_
    }_x000D_
  },_x000D_
_x000D_
  adminOnly: function(req, res, next) {_x000D_
    let loginUser = req.body.user_x000D_
    if (loginUser && loginUser.role === 'admin') {_x000D_
      next()_x000D_
    } else {_x000D_
      next(new Error('Not Authorized'))_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
====error handler==== MIDDLEWARE_x000D_
const errorHelper = require('../helpers/errorHandling')_x000D_
_x000D_
module.exports = function(err, req, res, next) {_x000D_
  //   console.log(err)_x000D_
  let errorToSend = errorHelper(err)_x000D_
  // console.log(errorToSend)_x000D_
  res.status(errorToSend.statusCode).json(errorToSend)_x000D_
}_x000D_
_x000D_
_x000D_
====error handling==== HELPER_x000D_
var nodeError = ["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]_x000D_
var mongooseError = ["MongooseError","DisconnectedError","DivergentArrayError","MissingSchemaError","DocumentNotFoundError","MissingSchemaError","ObjectExpectedError","ObjectParameterError","OverwriteModelError","ParallelSaveError","StrictModeError","VersionError"]_x000D_
var mongooseErrorFromClient = ["CastError","ValidatorError","ValidationError"];_x000D_
var jwtError = ["TokenExpiredError","JsonWebTokenError","NotBeforeError"]_x000D_
_x000D_
function nodeErrorMessage(message){_x000D_
    switch(message){_x000D_
        case "Token is undefined":{_x000D_
            return 403;_x000D_
        }_x000D_
        case "User not found":{_x000D_
            return 403;_x000D_
        }_x000D_
        case "Not Authorized":{_x000D_
            return 401;_x000D_
        }_x000D_
        case "Email is Invalid!":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Password is Invalid!":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Incorrect password for register as admin":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Item id not found":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Email or Password is invalid": {_x000D_
            return 400_x000D_
        }_x000D_
        default :{_x000D_
            return 500;_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
module.exports = function(errorObject){_x000D_
    // console.log("===ERROR OBJECT===")_x000D_
    // console.log(errorObject)_x000D_
    // console.log("===ERROR STACK===")_x000D_
    // console.log(errorObject.stack);_x000D_
_x000D_
    let statusCode = 500;  _x000D_
    let returnObj = {_x000D_
        error : errorObject_x000D_
    }_x000D_
    if(jwtError.includes(errorObject.name)){_x000D_
        statusCode = 403;_x000D_
        returnObj.message = "Token is Invalid"_x000D_
        returnObj.source = "jwt"_x000D_
    }_x000D_
    else if(nodeError.includes(errorObject.name)){_x000D_
        returnObj.error = JSON.parse(JSON.stringify(errorObject, ["message", "arguments", "type", "name"]))_x000D_
        returnObj.source = "node";_x000D_
        statusCode = nodeErrorMessage(errorObject.message);_x000D_
        returnObj.message = errorObject.message;_x000D_
    }else if(mongooseError.includes(errorObject.name)){_x000D_
        returnObj.source = "database"_x000D_
        returnObj.message = "Error from server"_x000D_
    }else if(mongooseErrorFromClient.includes(errorObject.name)){_x000D_
        returnObj.source = "database";_x000D_
        errorObject.message ? returnObj.message = errorObject.message : returnObj.message = "Bad Request"_x000D_
        statusCode = 400;_x000D_
    }else{_x000D_
        returnObj.source = "unknown error";_x000D_
        returnObj.message = "Something error";_x000D_
    }_x000D_
    returnObj.statusCode = statusCode;_x000D_
    _x000D_
    return returnObj;_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
===jwt====_x000D_
const jwt = require('jsonwebtoken')_x000D_
_x000D_
function generateToken(payload) {_x000D_
    let token = jwt.sign(payload, process.env.JWT_KEY)_x000D_
    return token_x000D_
}_x000D_
_x000D_
function verifyToken(token) {_x000D_
    let payload = jwt.verify(token, process.env.JWT_KEY)_x000D_
    return payload_x000D_
}_x000D_
_x000D_
module.exports = {_x000D_
    generateToken, verifyToken_x000D_
}_x000D_
_x000D_
===router index===_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
_x000D_
// router.get('/', )_x000D_
router.use('/users', require('./users'))_x000D_
router.use('/products', require('./product'))_x000D_
router.use('/transactions', require('./transaction'))_x000D_
_x000D_
module.exports = router_x000D_
_x000D_
====router user ====_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
const User = require('../controllers/userController')_x000D_
const auth = require('../middlewares/auth')_x000D_
_x000D_
/* GET users listing. */_x000D_
router.post('/register', User.register)_x000D_
router.post('/login', User.login)_x000D_
router.get('/', auth.authentication, User.getUser)_x000D_
router.post('/logout', auth.authentication, User.logout)_x000D_
module.exports = router_x000D_
_x000D_
_x000D_
====app====_x000D_
require('dotenv').config()_x000D_
const express = require('express')_x000D_
const cookieParser = require('cookie-parser')_x000D_
const logger = require('morgan')_x000D_
const cors = require('cors')_x000D_
const indexRouter = require('./routes/index')_x000D_
const errorHandler = require('./middlewares/errorHandler')_x000D_
const mongoose = require('mongoose')_x000D_
const app = express()_x000D_
_x000D_
mongoose.connect(process.env.DB_URI, {_x000D_
  useNewUrlParser: true,_x000D_
  useUnifiedTopology: true,_x000D_
  useCreateIndex: true,_x000D_
  useFindAndModify: false_x000D_
})_x000D_
_x000D_
app.use(cors())_x000D_
app.use(logger('dev'))_x000D_
app.use(express.json())_x000D_
app.use(express.urlencoded({ extended: false }))_x000D_
app.use(cookieParser())_x000D_
_x000D_
app.use('/', indexRouter)_x000D_
app.use(errorHandler)_x000D_
_x000D_
module.exports = app
_x000D_
_x000D_
_x000D_

How to close existing connections to a DB

in restore wizard click "close existing connections to destination database"

in Detach Database wizard click "Drop connection" item.

How do I split a multi-line string into multiple lines?

Like the others said:

inputString.split('\n')  # --> ['Line 1', 'Line 2', 'Line 3']

This is identical to the above, but the string module's functions are deprecated and should be avoided:

import string
string.split(inputString, '\n')  # --> ['Line 1', 'Line 2', 'Line 3']

Alternatively, if you want each line to include the break sequence (CR,LF,CRLF), use the splitlines method with a True argument:

inputString.splitlines(True)  # --> ['Line 1\n', 'Line 2\n', 'Line 3']

Git pull command from different user

Your question is a little unclear, but if what you're doing is trying to get your friend's latest changes, then typically what your friend needs to do is to push those changes up to a remote repo (like one hosted on GitHub), and then you fetch or pull those changes from the remote:

  1. Your friend pushes his changes to GitHub:

    git push origin <branch>
    
  2. Clone the remote repository if you haven't already:

    git clone https://[email protected]/abc/theproject.git
    
  3. Fetch or pull your friend's changes (unnecessary if you just cloned in step #2 above):

    git fetch origin
    git merge origin/<branch>
    

    Note that git pull is the same as doing the two steps above:

    git pull origin <branch>
    

See Also

How to hash a string into 8 digits?

Raymond's answer is great for python2 (though, you don't need the abs() nor the parens around 10 ** 8). However, for python3, there are important caveats. First, you'll need to make sure you are passing an encoded string. These days, in most circumstances, it's probably also better to shy away from sha-1 and use something like sha-256, instead. So, the hashlib approach would be:

>>> import hashlib
>>> s = 'your string'
>>> int(hashlib.sha256(s.encode('utf-8')).hexdigest(), 16) % 10**8
80262417

If you want to use the hash() function instead, the important caveat is that, unlike in Python 2.x, in Python 3.x, the result of hash() will only be consistent within a process, not across python invocations. See here:

$ python -V
Python 2.7.5
$ python -c 'print(hash("foo"))'
-4177197833195190597
$ python -c 'print(hash("foo"))'
-4177197833195190597

$ python3 -V
Python 3.4.2
$ python3 -c 'print(hash("foo"))'
5790391865899772265
$ python3 -c 'print(hash("foo"))'
-8152690834165248934

This means the hash()-based solution suggested, which can be shortened to just:

hash(s) % 10**8

will only return the same value within a given script run:

#Python 2:
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543

#Python 3:
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
12954124
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
32065451

So, depending on if this matters in your application (it did in mine), you'll probably want to stick to the hashlib-based approach.

How do I add a resources folder to my Java project in Eclipse

Try To Give Full path for reading image.

Example image = ImageIO.read(new File("D:/work1/Jan14Stackoverflow/src/Strawberry.jpg"));

your code is not producing any exception after giving the full path. If you want to just read an image file in java code. Refer the following - http://docs.oracle.com/javase/tutorial/2d/images/examples/LoadImageApp.java

If the object of your class is created at end your code works fine for me and displays the image

// PracticeFrame pframe = new PracticeFrame();//comment this

new PracticeFrame().add(panel);

How to set up tmux so that it starts up with specified windows opened?

From my "get.all" script, which I invoke each morning to run a bunch of subsequent "get.XXX" jobs to refresh the software that I track. Some of them are auto-quitting. Others require more interaction once the get has finished (like asking to build emacs).

#!/bin/sh
tmux att -t get ||
tmux \
  new -s get -n capp \; \
  send-keys 'get.capp' C-m \; \
  neww -n emacs \; \
  send-keys 'get.emacs' C-m \; \
  neww -n git \; \
  send-keys 'get.git' C-m \; \
  neww -n mini \; \
  send-keys 'get.mini' C-m \; \
  neww -n port \; \
  send-keys 'get.port' C-m \; \
  neww -n rakudo \; \
  send-keys 'get.rakudo' C-m \; \
  neww -n neil \; \
  send-keys 'get.neil && get.neil2 && exit' C-m \; \
  neww -n red \; \
  send-keys 'get.red && exit' C-m \; \
  neww -n cpan \; \
  send-keys 'get.cpan && exit' C-m \; \
  selectw -t emacs

Get all files that have been modified in git branch

git diff --name-only master...branch-name

to which we want to compare.

The view didn't return an HttpResponse object. It returned None instead

Because the view must return render, not just call it. Change the last line to

return render(request, 'auth_lifecycle/user_profile.html',
           context_instance=RequestContext(request))

Vim: insert the same characters across multiple lines

An alternative that can be more flexible:

Example: To enter the text XYZ at the beginning of the line

:%norm IXYZ

What's happening here?

  • % == Execute on every line
  • norm == Execute the following keys in normal mode
  • I == Insert at beginning of line
  • XYZ == The text you want to enter

Then you hit Enter, and it executes.

Specific to your request:

:%norm Ivendor_

You can also choose a particular range:

:2,4norm Ivendor_

Or execute over a selected visual range:

:'<,'>norm Ivendor_

How to use readline() method in Java?

In summary: I would be careful as to what code you copy. It is possible you are copying code which happens to work, rather than well chosen code.

In intnumber, parseInt is used and in floatnumber valueOf is used why so?

There is no good reason I can see. It's an inconsistent use of the APIs as you suspect.


Java is case sensitive, and there isn't any Readline() method. Perhaps you mean readLine().

DataInputStream.readLine() is deprecated in favour of using BufferedReader.readLine();

However, for your case, I would use the Scanner class.

Scanner sc = new Scanner(System.in);
int intNum = sc.nextInt();
float floatNum = sc.nextFloat();

If you want to know what a class does I suggest you have a quick look at the Javadoc.

Adding event listeners to dynamically added elements using jQuery

$(document).on('click', 'selector', handler);

Where click is an event name, and handler is an event handler, like reference to a function or anonymous function function() {}

PS: if you know the particular node you're adding dynamic elements to - you could specify it instead of document.

babel-loader jsx SyntaxError: Unexpected token

For me the solution was to create the file .babelrc with this content:

{
  "presets": ["react", "es2015", "stage-1"]
}

What do multiple arrow functions mean in javascript?

That is a curried function

First, examine this function with two parameters …

const add = (x, y) => x + y
add(2, 3) //=> 5

Here it is again in curried form …

const add = x => y => x + y

Here is the same1 code without arrow functions …

const add = function (x) {
  return function (y) {
    return x + y
  }
}

Focus on return

It might help to visualize it another way. We know that arrow functions work like this – let's pay particular attention to the return value.

const f = someParam => returnValue

So our add function returns a function – we can use parentheses for added clarity. The bolded text is the return value of our function add

const add = x => (y => x + y)

In other words add of some number returns a function

add(2) // returns (y => 2 + y)

Calling curried functions

So in order to use our curried function, we have to call it a bit differently …

add(2)(3)  // returns 5

This is because the first (outer) function call returns a second (inner) function. Only after we call the second function do we actually get the result. This is more evident if we separate the calls on two lines …

const add2 = add(2) // returns function(y) { return 2 + y }
add2(3)             // returns 5

Applying our new understanding to your code

related: ”What’s the difference between binding, partial application, and currying?”

OK, now that we understand how that works, let's look at your code

handleChange = field => e => {
  e.preventDefault()
  /// Do something here
}

We'll start by representing it without using arrow functions …

handleChange = function(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
    // return ...
  };
};

However, because arrow functions lexically bind this, it would actually look more like this …

handleChange = function(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
    // return ...
  }.bind(this)
}.bind(this)

Maybe now we can see what this is doing more clearly. The handleChange function is creating a function for a specified field. This is a handy React technique because you're required to setup your own listeners on each input in order to update your applications state. By using the handleChange function, we can eliminate all the duplicated code that would result in setting up change listeners for each field. Cool!

1 Here I did not have to lexically bind this because the original add function does not use any context, so it is not important to preserve it in this case.


Even more arrows

More than two arrow functions can be sequenced, if necessary -

const three = a => b => c =>
  a + b + c

const four = a => b => c => d =>
  a + b + c + d

three (1) (2) (3) // 6

four (1) (2) (3) (4) // 10

Curried functions are capable of surprising things. Below we see $ defined as a curried function with two parameters, yet at the call site, it appears as though we can supply any number of arguments. Currying is the abstraction of arity -

_x000D_
_x000D_
const $ = x => k =>_x000D_
  $ (k (x))_x000D_
  _x000D_
const add = x => y =>_x000D_
  x + y_x000D_
_x000D_
const mult = x => y =>_x000D_
  x * y_x000D_
  _x000D_
$ (1)           // 1_x000D_
  (add (2))     // + 2 = 3_x000D_
  (mult (6))    // * 6 = 18_x000D_
  (console.log) // 18_x000D_
  _x000D_
$ (7)            // 7_x000D_
  (add (1))      // + 1 = 8_x000D_
  (mult (8))     // * 8 = 64_x000D_
  (mult (2))     // * 2 = 128_x000D_
  (mult (2))     // * 2 = 256_x000D_
  (console.log)  // 256
_x000D_
_x000D_
_x000D_

Partial application

Partial application is a related concept. It allows us to partially apply functions, similar to currying, except the function does not have to be defined in curried form -

const partial = (f, ...a) => (...b) =>
  f (...a, ...b)

const add3 = (x, y, z) =>
  x + y + z

partial (add3) (1, 2, 3)   // 6

partial (add3, 1) (2, 3)   // 6

partial (add3, 1, 2) (3)   // 6

partial (add3, 1, 2, 3) () // 6

partial (add3, 1, 1, 1, 1) (1, 1, 1, 1, 1) // 3

Here's a working demo of partial you can play with in your own browser -

_x000D_
_x000D_
const partial = (f, ...a) => (...b) =>_x000D_
  f (...a, ...b)_x000D_
  _x000D_
const preventDefault = (f, event) =>_x000D_
  ( event .preventDefault ()_x000D_
  , f (event)_x000D_
  )_x000D_
  _x000D_
const logKeypress = event =>_x000D_
  console .log (event.which)_x000D_
  _x000D_
document_x000D_
  .querySelector ('input[name=foo]')_x000D_
  .addEventListener ('keydown', partial (preventDefault, logKeypress))
_x000D_
<input name="foo" placeholder="type here to see ascii codes" size="50">
_x000D_
_x000D_
_x000D_

How do I change the figure size with subplots?

Alternatively, create a figure() object using the figsize argument and then use add_subplot to add your subplots. E.g.

import matplotlib.pyplot as plt
import numpy as np

f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')

Simple Example

Benefits of this method are that the syntax is closer to calls of subplot() instead of subplots(). E.g. subplots doesn't seem to support using a GridSpec for controlling the spacing of the subplots, but both subplot() and add_subplot() do.

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

I was having same issue. I search "innodb_strict_mode" in my.ini but couldn't found.

I then added the same, it will still show you the warning, but you can continue. just add

innodb_strict_mode = 0;

Add a linebreak in an HTML text area

In a text area, as in the form input, then just a normal line break will work:

<textarea>
This is a text area
line breaks are automatic
</textarea>

If you're talking about normal text on the page, the <br /> (or just <br> if using plain 'ole HTML4) is a line break.

However, I'd say that you often don't actually want a line break. Usually, your text is seperated into paragraphs:

<p>
  This is some text
</p>
<p>
  This is some more
</p>

Which is much better because it gives a clue as to how your text is structured to machines that read it. Machines that read it include screen readers for the partially sighted or blind, seperating text into paragraphs gives it a chance of being presented correctly to these users.

When should I write the keyword 'inline' for a function/method?

1) Nowadays, pretty much never. If it's a good idea to inline a function, the compiler will do it without your help.

2) Always. See #1.

(Edited to reflect that you broke your question into two questions...)

Tricks to manage the available memory in an R session

Unfortunately I did not have time to test it extensively but here is a memory tip that I have not seen before. For me the required memory was reduced with more than 50%. When you read stuff into R with for example read.csv they require a certain amount of memory. After this you can save them with save("Destinationfile",list=ls()) The next time you open R you can use load("Destinationfile") Now the memory usage might have decreased. It would be nice if anyone could confirm whether this produces similar results with a different dataset.

How to remove ASP.Net MVC Default HTTP Headers?

In Asp.Net Core you can edit the web.config files like so:

<httpProtocol>
  <customHeaders>
    <remove name="X-Powered-By" />
  </customHeaders>
</httpProtocol>

You can remove the server header in the Kestrel options:

            .UseKestrel(c =>
            {
                // removes the server header
                c.AddServerHeader = false;
            }) 

Media Queries - In between two widths

@Jonathan Sampson i think your solution is wrong if you use multiple @media.

You should use (min-width first):

@media screen and (min-width:400px) and (max-width:900px){
   ...
}

How to check the maximum number of allowed connections to an Oracle database?

I thought this would work, based on this source.

SELECT
  'Currently, ' 
  || (SELECT COUNT(*) FROM V$SESSION)
  || ' out of ' 
  || DECODE(VL.SESSIONS_MAX,0,'unlimited',VL.SESSIONS_MAX) 
  || ' connections are used.' AS USAGE_MESSAGE
FROM 
  V$LICENSE VL

However, Justin Cave is right. This query gives better results:

SELECT
  'Currently, ' 
  || (SELECT COUNT(*) FROM V$SESSION)
  || ' out of ' 
  || VP.VALUE 
  || ' connections are used.' AS USAGE_MESSAGE
FROM 
  V$PARAMETER VP
WHERE VP.NAME = 'sessions'

How to check if IEnumerable is null or empty?

 public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
    {
        return source != null && source.Any();
    }

my own extension method to check Not null and Any

string decode utf-8

Try looking at decode string encoded in utf-8 format in android but it doesn't look like your string is encoded with anything particular. What do you think the output should be?

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

You can simply check whether the element length is undefined or not just by using

var theHref = $(obj.mainImg_select).attr('href');
if (theHref){
   //get the length here if the element is not undefined
   elementLength = theHref.length
   // do stuff
} else {
   // do other stuff
}

ldap_bind: Invalid Credentials (49)

I don't see an obvious problem with the above.

It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

Try an explicit URI:

ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost

or prevent defaults with:

LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

  • make sure your slapd.conf is being used and is correct (as root)

    slapd -T test -f slapd.conf -d 65535

    You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

  • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

    slapd -h ldap://localhost -d 481

    then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

  • if debug is enabled, then try also

    ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

How to define hash tables in Bash?

Bash 4

Bash 4 natively supports this feature. Make sure your script's hashbang is #!/usr/bin/env bash or #!/bin/bash so you don't end up using sh. Make sure you're either executing your script directly, or execute script with bash script. (Not actually executing a Bash script with Bash does happen, and will be really confusing!)

You declare an associative array by doing:

declare -A animals

You can fill it up with elements using the normal array assignment operator. For example, if you want to have a map of animal[sound(key)] = animal(value):

animals=( ["moo"]="cow" ["woof"]="dog")

Or merge them:

declare -A animals=( ["moo"]="cow" ["woof"]="dog")

Then use them just like normal arrays. Use

  • animals['key']='value' to set value

  • "${animals[@]}" to expand the values

  • "${!animals[@]}" (notice the !) to expand the keys

Don't forget to quote them:

echo "${animals[moo]}"
for sound in "${!animals[@]}"; do echo "$sound - ${animals[$sound]}"; done

Bash 3

Before bash 4, you don't have associative arrays. Do not use eval to emulate them. Avoid eval like the plague, because it is the plague of shell scripting. The most important reason is that eval treats your data as executable code (there are many other reasons too).

First and foremost: Consider upgrading to bash 4. This will make the whole process much easier for you.

If there's a reason you can't upgrade, declare is a far safer option. It does not evaluate data as bash code like eval does, and as such does not allow arbitrary code injection quite so easily.

Let's prepare the answer by introducing the concepts:

First, indirection.

$ animals_moo=cow; sound=moo; i="animals_$sound"; echo "${!i}"
cow

Secondly, declare:

$ sound=moo; animal=cow; declare "animals_$sound=$animal"; echo "$animals_moo"
cow

Bring them together:

# Set a value:
declare "array_$index=$value"

# Get a value:
arrayGet() { 
    local array=$1 index=$2
    local i="${array}_$index"
    printf '%s' "${!i}"
}

Let's use it:

$ sound=moo
$ animal=cow
$ declare "animals_$sound=$animal"
$ arrayGet animals "$sound"
cow

Note: declare cannot be put in a function. Any use of declare inside a bash function turns the variable it creates local to the scope of that function, meaning we can't access or modify global arrays with it. (In bash 4 you can use declare -g to declare global variables - but in bash 4, you can use associative arrays in the first place, avoiding this workaround.)

Summary:

  • Upgrade to bash 4 and use declare -A for associative arrays.
  • Use the declare option if you can't upgrade.
  • Consider using awk instead and avoid the issue altogether.

Convert DateTime to String PHP

You can use the format method of the DateTime class:

$date = new DateTime('2000-01-01');
$result = $date->format('Y-m-d H:i:s');

If format fails for some reason, it will return FALSE. In some applications, it might make sense to handle the failing case:

if ($result) {
  echo $result;
} else { // format failed
  echo "Unknown Time";
}

Insert content into iFrame

If you want all the CSS thats on your webpage in your IFrame, try this:

var headClone, iFrameHead;

// Create a clone of the web-page head
headClone = $('head').clone();

// Find the head of the the iFrame we are looking for
iFrameHead = $('#iframe').contents().find('head');

// Replace 'iFrameHead with your Web page 'head'
iFrameHead.replaceWith(headClone);

// You should now have all the Web page CSS in the Iframe

Good Luck.

How to get HttpContext.Current in ASP.NET Core?

As a general rule, converting a Web Forms or MVC5 application to ASP.NET Core will require a significant amount of refactoring.

HttpContext.Current was removed in ASP.NET Core. Accessing the current HTTP context from a separate class library is the type of messy architecture that ASP.NET Core tries to avoid. There are a few ways to re-architect this in ASP.NET Core.

HttpContext property

You can access the current HTTP context via the HttpContext property on any controller. The closest thing to your original code sample would be to pass HttpContext into the method you are calling:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        MyMethod(HttpContext);

        // Other code
    }
}

public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
    var host = $"{context.Request.Scheme}://{context.Request.Host}";

    // Other code
}

HttpContext parameter in middleware

If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext is passed into your Invoke method automatically:

public Task Invoke(HttpContext context)
{
    // Do something with the current HTTP context...
}

HTTP context accessor

Finally, you can use the IHttpContextAccessor helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.

Request this interface in your constructor:

public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

You can then access the current HTTP context in a safe way:

var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...

IHttpContextAccessor isn't always added to the service container by default, so register it in ConfigureServices just to be safe:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    // if < .NET Core 2.2 use this
    //services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Other code...
}

How do you display code snippets in MS Word preserving format and syntax highlighting?

I have created an easier method using tables, as they are easier to create, manage, and more consistent (with the possibility to save the table's style inside the document itself), but I couldn't find a better way for code colouring scheme, sorry for that.

Steps:

  1. Create a 3x3 table.

  2. Select the table, and make its borders invisible ("No Borders" option), and activate "View Gridlines" option. enter image description here

  3. Make the adjustments to cells' spacing and columns' widths to get the desired aspect. (You will have to get in "Table Properties" for fine tuning). enter image description here

  4. Create a "Paragraph Style" with the name of "Code" just for your code snippets (as mentioned in https://stackoverflow.com/a/25092977/8533804)

  5. Create another "Paragraph Style" with the name of "Code_numberline" that will be based upon the previous created style, but this you will add a numbering line in its definition (this will automate line numbering). enter image description here

  6. Apply "Code_numberline" to the first column, and "Code" to the 3 column. enter image description here

  7. Add a fill in the middle column. enter image description here

  8. Save that table style and enjoy!

Python module for converting PDF to text

slate is a project that makes it very simple to use PDFMiner from a library:

>>> with open('example.pdf') as f:
...    doc = slate.PDF(f)
...
>>> doc
[..., ..., ...]
>>> doc[1]
'Text from page 2...'   

Show Console in Windows Application?

What you want to do is not possible in a sane way. There was a similar question so look at the answers.

Then there's also an insane approach (site down - backup available here.) written by Jeffrey Knight:

Question: How do I create an application that can run in either GUI (windows) mode or command line / console mode?

On the surface of it, this would seem easy: you create a Console application, add a windows form to it, and you're off and running. However, there's a problem:

Problem: If you run in GUI mode, you end up with both a window and a pesky console lurking in the background, and you don't have any way to hide it.

What people seem to want is a true amphibian application that can run smoothly in either mode.

If you break it down, there are actually four use cases here:

User starts application from existing cmd window, and runs in GUI mode
User double clicks to start application, and runs in GUI mode
User starts application from existing cmd window, and runs in command mode
User double clicks to start application, and runs in command mode.

I'm posting the code to do this, but with a caveat.

I actually think this sort of approach will run you into a lot more trouble down the road than it's worth. For example, you'll have to have two different UIs' -- one for the GUI and one for the command / shell. You're going to have to build some strange central logic engine that abstracts from GUI vs. command line, and it's just going to get weird. If it were me, I'd step back and think about how this will be used in practice, and whether this sort of mode-switching is worth the work. Thus, unless some special case called for it, I wouldn't use this code myself, because as soon as I run into situations where I need API calls to get something done, I tend to stop and ask myself "am I overcomplicating things?".

Output type=Windows Application

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Microsoft.Win32;

namespace WindowsApplication
{
    static class Program
    {
        /*
    DEMO CODE ONLY: In general, this approach calls for re-thinking 
    your architecture!
    There are 4 possible ways this can run:
    1) User starts application from existing cmd window, and runs in GUI mode
    2) User double clicks to start application, and runs in GUI mode
    3) User starts applicaiton from existing cmd window, and runs in command mode
    4) User double clicks to start application, and runs in command mode.

    To run in console mode, start a cmd shell and enter:
        c:\path\to\Debug\dir\WindowsApplication.exe console
        To run in gui mode,  EITHER just double click the exe, OR start it from the cmd prompt with:
        c:\path\to\Debug\dir\WindowsApplication.exe (or pass the "gui" argument).
        To start in command mode from a double click, change the default below to "console".
    In practice, I'm not even sure how the console vs gui mode distinction would be made from a
    double click...
        string mode = args.Length > 0 ? args[0] : "console"; //default to console
    */

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool AllocConsole();

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool FreeConsole();

        [DllImport("kernel32", SetLastError = true)]
        static extern bool AttachConsole(int dwProcessId);

        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll", SetLastError = true)]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

        [STAThread]
        static void Main(string[] args)
        {
            //TODO: better handling of command args, (handle help (--help /?) etc.)
            string mode = args.Length > 0 ? args[0] : "gui"; //default to gui

            if (mode == "gui")
            {
                MessageBox.Show("Welcome to GUI mode");

                Application.EnableVisualStyles();

                Application.SetCompatibleTextRenderingDefault(false);

                Application.Run(new Form1());
            }
            else if (mode == "console")
            {

                //Get a pointer to the forground window.  The idea here is that
                //IF the user is starting our application from an existing console
                //shell, that shell will be the uppermost window.  We'll get it
                //and attach to it
                IntPtr ptr = GetForegroundWindow();

                int  u;

                GetWindowThreadProcessId(ptr, out u);

                Process process = Process.GetProcessById(u);

                if (process.ProcessName == "cmd" )    //Is the uppermost window a cmd process?
                {
                    AttachConsole(process.Id);

                    //we have a console to attach to ..
                    Console.WriteLine("hello. It looks like you started me from an existing console.");
                }
                else
                {
                    //no console AND we're in console mode ... create a new console.

                    AllocConsole();

                    Console.WriteLine(@"hello. It looks like you double clicked me to start
                   AND you want console mode.  Here's a new console.");
                    Console.WriteLine("press any key to continue ...");
                    Console.ReadLine();       
                }

                FreeConsole();
            }
        }
    }
}

Is there a way to iterate over a dictionary?

This is iteration using block approach:

    NSDictionary *dict = @{@"key1":@1, @"key2":@2, @"key3":@3};

    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@->%@",key,obj);
        // Set stop to YES when you wanted to break the iteration.
    }];

With autocompletion is very fast to set, and you do not have to worry about writing iteration envelope.

Iterating over every property of an object in javascript using Prototype?

You have to first convert your object literal to a Prototype Hash:

// Store your object literal
var obj = {foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}

// Iterate like so.  The $H() construct creates a prototype-extended Hash.
$H(obj).each(function(pair){
  alert(pair.key);
  alert(pair.value);
});

How to set conditional breakpoints in Visual Studio?

Set a breakpoint as usual. Right click it. Click Condition.

Laravel Advanced Wheres how to pass variable into function?

You can pass the necessary variables from the parent scope into the closure with the use keyword.

For example:

DB::table('users')->where(function ($query) use ($activated) {
    $query->where('activated', '=', $activated);
})->get();

More on that here.

EDIT (2019 update):

PHP 7.4 (will be released at November 28, 2019) introduces a shorter variation of the anonymous functions called arrow functions which makes this a bit less verbose.

An example using PHP 7.4 which is functionally nearly equivalent (see the 3rd bullet point below):

DB::table('users')->where(fn($query) => $query->where('activated', '=', $activated))->get();

Differences compared to the regular syntax:

  • fn keyword instead of function.
  • No need to explicitly list all variables which should be captured from the parent scope - this is now done automatically by-value. See the lack of use keyword in the latter example.
  • Arrow functions always return a value. This also means that it's impossible to use void return type when declaring them.
  • The return keyword must be omitted.
  • Arrow functions must have a single expression which is the return statement. Multi-line functions aren't supported at the moment. You can still chain methods though.

Concatenating Matrices in R

Sounds like you're looking for rbind:

> a<-matrix(nrow=10,ncol=5)
> b<-matrix(nrow=20,ncol=5)
> dim(rbind(a,b))
[1] 30  5

Similarly, cbind stacks the matrices horizontally.

I am not entirely sure what you mean by the last question ("Can I do this for matrices of different rows and columns.?")

Check whether a value is a number in JavaScript or jQuery

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Correct way of getting Client's IP Addresses from http.Request

Here a completely working example

package main

import (  
    // Standard library packages
    "fmt"
    "strconv"
    "log"
    "net"
    "net/http"

    // Third party packages
    "github.com/julienschmidt/httprouter"
    "github.com/skratchdot/open-golang/open"
)



// https://blog.golang.org/context/userip/userip.go
func getIP(w http.ResponseWriter, req *http.Request, _ httprouter.Params){
    fmt.Fprintf(w, "<h1>static file server</h1><p><a href='./static'>folder</p></a>")

    ip, port, err := net.SplitHostPort(req.RemoteAddr)
    if err != nil {
        //return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)

        fmt.Fprintf(w, "userip: %q is not IP:port", req.RemoteAddr)
    }

    userIP := net.ParseIP(ip)
    if userIP == nil {
        //return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
        fmt.Fprintf(w, "userip: %q is not IP:port", req.RemoteAddr)
        return
    }

    // This will only be defined when site is accessed via non-anonymous proxy
    // and takes precedence over RemoteAddr
    // Header.Get is case-insensitive
    forward := req.Header.Get("X-Forwarded-For")

    fmt.Fprintf(w, "<p>IP: %s</p>", ip)
    fmt.Fprintf(w, "<p>Port: %s</p>", port)
    fmt.Fprintf(w, "<p>Forwarded for: %s</p>", forward)
}


func main() {  
    myport := strconv.Itoa(10002);


    // Instantiate a new router
    r := httprouter.New()

    r.GET("/ip", getIP)

    // Add a handler on /test
    r.GET("/test", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
        // Simply write some test data for now
        fmt.Fprint(w, "Welcome!\n")
    })  


    l, err := net.Listen("tcp", "localhost:" + myport)
    if err != nil {
        log.Fatal(err)
    }
    // The browser can connect now because the listening socket is open.


    //err = open.Start("http://localhost:"+ myport + "/test")
    err = open.Start("http://localhost:"+ myport + "/ip")
    if err != nil {
         log.Println(err)
    }

    // Start the blocking server loop.
    log.Fatal(http.Serve(l, r)) 
}

Bitwise operation and usage

I think that the second part of the question:

Also, what are bitwise operators actually used for? I'd appreciate some examples.

Has been only partially addressed. These are my two cents on that matter.

Bitwise operations in programming languages play a fundamental role when dealing with a lot of applications. Almost all low-level computing must be done using this kind of operations.

In all applications that need to send data between two nodes, such as:

  • computer networks;

  • telecommunication applications (cellular phones, satellite communications, etc).

In the lower level layer of communication, the data is usually sent in what is called frames. Frames are just strings of bytes that are sent through a physical channel. This frames usually contain the actual data plus some other fields (coded in bytes) that are part of what is called the header. The header usually contains bytes that encode some information related to the status of the communication (e.g, with flags (bits)), frame counters, correction and error detection codes, etc. To get the transmitted data in a frame, and to build the frames to send data, you will need for sure bitwise operations.

In general, when dealing with that kind of applications, an API is available so you don't have to deal with all those details. For example, all modern programming languages provide libraries for socket connections, so you don't actually need to build the TCP/IP communication frames. But think about the good people that programmed those APIs for you, they had to deal with frame construction for sure; using all kinds of bitwise operations to go back and forth from the low-level to the higher-level communication.

As a concrete example, imagine some one gives you a file that contains raw data that was captured directly by telecommunication hardware. In this case, in order to find the frames, you will need to read the raw bytes in the file and try to find some kind of synchronization words, by scanning the data bit by bit. After identifying the synchronization words, you will need to get the actual frames, and SHIFT them if necessary (and that is just the start of the story) to get the actual data that is being transmitted.

Another very different low level family of application is when you need to control hardware using some (kind of ancient) ports, such as parallel and serial ports. This ports are controlled by setting some bytes, and each bit of that bytes has a specific meaning, in terms of instructions, for that port (see for instance http://en.wikipedia.org/wiki/Parallel_port). If you want to build software that does something with that hardware you will need bitwise operations to translate the instructions you want to execute to the bytes that the port understand.

For example, if you have some physical buttons connected to the parallel port to control some other device, this is a line of code that you can find in the soft application:

read = ((read ^ 0x80) >> 4) & 0x0f; 

Hope this contributes.

pythonic way to do something N times without an index variable?

Assume that you've defined do_something as a function, and you'd like to perform it N times. Maybe you can try the following:

todos = [do_something] * N  
for doit in todos:  
    doit()

PowerShell try/catch/finally

That is very odd.

I went through ItemNotFoundException's base classes and tested the following multiple catches to see what would catch it:

try {
  remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
  write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
  write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
  write-host 'RuntimeException'
}
catch [System.SystemException] {
  write-host 'SystemException'
}
catch [System.Exception] {
  write-host 'Exception'
}
catch {
  write-host 'well, darn'
}

As it turns out, the output was 'RuntimeException'. I also tried it with a different exception CommandNotFoundException:

try {
  do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
  write-host 'CommandNotFoundException'
}
catch {
  write-host 'well, darn'
}

That output 'CommandNotFoundException' correctly.

I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type they could and then use a switch. The following just catches Exception instead of RuntimeException, but is the switch equivalent of my first example that checks all base types of ItemNotFoundException:

try {
  Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
  switch($_.Exception.GetType().FullName) {
    'System.Management.Automation.ItemNotFoundException' {
      write-host 'ItemNotFound'
    }
    'System.Management.Automation.SessionStateException' {
      write-host 'SessionState'
    }
    'System.Management.Automation.RuntimeException' {
      write-host 'RuntimeException'
    }
    'System.SystemException' {
      write-host 'SystemException'
    }
    'System.Exception' {
      write-host 'Exception'
    }
    default {'well, darn'}
  }
}

This writes 'ItemNotFound', as it should.

Search for "does-not-contain" on a DataFrame in pandas

I was having trouble with the not (~) symbol as well, so here's another way from another StackOverflow thread:

df[df["col"].str.contains('this|that')==False]

Best way to do Version Control for MS Excel

It depends whether you are talking about data, or the code contained within a spreadsheet. While I have a strong dislike of Microsoft's Visual Sourcesafe and normally would not recommended it, it does integrate easily with both Access and Excel, and provides source control of modules.

[In fact the integration with Access, includes queries, reports and modules as individual objects that can be versioned]

The MSDN link is here.

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

This worked for me.

<table>
  <tr>
    <td *ngFor="#group of groups">
       <h1>{{group.name}}</h1>
   </td>
  </tr>
</table>

Create a new file in git bash

Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.

git add does not create any files. See also http://gitref.org/basic/#add

Github probably creates the file with touch and adds the file for tracking automatically. You can do this on the bash as well.

Example JavaScript code to parse CSV data

Here's an extremely simple CSV parser that handles quoted fields with commas, new lines, and escaped double quotation marks. There's no splitting or regular expression. It scans the input string 1-2 characters at a time and builds an array.

Test it at http://jsfiddle.net/vHKYH/.

function parseCSV(str) {
    var arr = [];
    var quote = false;  // 'true' means we're inside a quoted field

    // Iterate over each character, keep track of current row and column (of the returned array)
    for (var row = 0, col = 0, c = 0; c < str.length; c++) {
        var cc = str[c], nc = str[c+1];        // Current character, next character
        arr[row] = arr[row] || [];             // Create a new row if necessary
        arr[row][col] = arr[row][col] || '';   // Create a new column (start with empty string) if necessary

        // If the current character is a quotation mark, and we're inside a
        // quoted field, and the next character is also a quotation mark,
        // add a quotation mark to the current column and skip the next character
        if (cc == '"' && quote && nc == '"') { arr[row][col] += cc; ++c; continue; }

        // If it's just one quotation mark, begin/end quoted field
        if (cc == '"') { quote = !quote; continue; }

        // If it's a comma and we're not in a quoted field, move on to the next column
        if (cc == ',' && !quote) { ++col; continue; }

        // If it's a newline (CRLF) and we're not in a quoted field, skip the next character
        // and move on to the next row and move to column 0 of that new row
        if (cc == '\r' && nc == '\n' && !quote) { ++row; col = 0; ++c; continue; }

        // If it's a newline (LF or CR) and we're not in a quoted field,
        // move on to the next row and move to column 0 of that new row
        if (cc == '\n' && !quote) { ++row; col = 0; continue; }
        if (cc == '\r' && !quote) { ++row; col = 0; continue; }

        // Otherwise, append the current character to the current column
        arr[row][col] += cc;
    }
    return arr;
}

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

This error was occurring for me in Firefox but not Chrome while developing locally, and it turned out to be caused by Firefox not trusting my local API's ssl certificate (which is not valid, but I had added it to my local cert store, which let chrome trust it but not ff). Navigating to the API directly and adding an exception in Firefox fixed the issue.

Get most recent file in a directory on Linux

I personally prefer to use as few not built-in bash commands as I can (to reduce the number of expensive fork and exec syscalls). To sort by date the ls needed to be called. But using of head is not really necessary. I use the following one-liner (works only on systems supporting name pipes):

read newest < <(ls -t *.log)

or to get the name of the oldest file

read oldest < <(ls -rt *.log)

(Mind the space between the two '<' marks!)

If the hidden files are also needed -A arg could be added.

I hope this could help.

Modifying a subset of rows in a pandas dataframe

For a massive speed increase, use NumPy's where function.

Setup

Create a two-column DataFrame with 100,000 rows with some zeros.

df = pd.DataFrame(np.random.randint(0,3, (100000,2)), columns=list('ab'))

Fast solution with numpy.where

df['b'] = np.where(df.a.values == 0, np.nan, df.b.values)

Timings

%timeit df['b'] = np.where(df.a.values == 0, np.nan, df.b.values)
685 µs ± 6.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit df.loc[df['a'] == 0, 'b'] = np.nan
3.11 ms ± 17.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Numpy's where is about 4x faster

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

How do I list the symbols in a .so file

Try adding -l to the nm flags in order to get the source of each symbol. If the library is compiled with debugging info (gcc -g) this should be the source file and line number. As Konrad said, the object file / static library is probably unknown at this point.

How to close a JavaFX application on window close?

Instead of playing around with onCloseRequest handlers or window events, I prefer calling Platform.setImplicitExit(true) the beginning of the application.

According to JavaDocs:

"If this attribute is true, the JavaFX runtime will implicitly shutdown when the last window is closed; the JavaFX launcher will call the Application.stop() method and terminate the JavaFX application thread."

Example:

@Override
void start(Stage primaryStage) {
    Platform.setImplicitExit(true)
    ...
    // create stage and scene
}

Android: resizing imageview in XML

for example:

<ImageView android:id="@+id/image_view"     
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:adjustViewBounds="true"  
  android:maxWidth="42dp"  
  android:maxHeight="42dp"  
  android:scaleType="fitCenter"  
  android:layout_marginLeft="3dp"  
  android:src="@drawable/icon"  
  /> 

Add property android:scaleType="fitCenter" and android:adjustViewBounds="true".

How to Display Selected Item in Bootstrap Button Dropdown Title

Updated for Bootstrap 3.3.4:

This will allow you to have different display text and data value for each element. It will also persist the caret on selection.

JS:

$(".dropdown-menu li a").click(function(){
  $(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>');
  $(this).parents(".dropdown").find('.btn').val($(this).data('value'));
});

HTML:

<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
    <li><a href="#" data-value="action">Action</a></li>
    <li><a href="#" data-value="another action">Another action</a></li>
    <li><a href="#" data-value="something else here">Something else here</a></li>
    <li><a href="#" data-value="separated link">Separated link</a></li>
  </ul>
</div>

JS Fiddle Example

How do I remove/delete a virtualenv?

You can remove all the dependencies by recursively uninstalling all of them and then delete the venv.

Edit including Isaac Turner commentary

source venv/bin/activate
pip freeze > requirements.txt
pip uninstall -r requirements.txt -y
deactivate
rm -r venv/

How can I prevent a window from being resized with tkinter?

Traceback (most recent call last):
  File "tkwindowwithlabel5.py", line 23, in <module>
    main()
  File "tkwindowwithlabel5.py", line 16, in main
    window.resizeable(width = True, height =True)
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1935, in                
  __getattr__
    return getattr(self.tk, attr)
AttributeError: 'tkapp' object has no attribute 'resizeable'

is what you will get with the first answer. tk does support min and max size

window.minsize(width = X, height = x)
window.maxsize(width = X, height = x)

i figured it out but just trying the first one. using python3 with tk.

React navigation goBack() and update parent state

First screen

updateData=(data)=>{
    console.log('Selected data',data)
}   

this.props.navigation.navigate('FirstScreen',{updateData:this.updateData.bind(this)})

Second screen

// use this method to call FirstScreen method 
execBack(param) {
    this.props.navigation.state.params.updateData(param);
    this.props.navigation.goBack();
}

Convert a CERT/PEM certificate to a PFX certificate

openssl pkcs12 -inkey bob_key.pem -in bob_cert.cert -export -out bob_pfx.pfx

Global variables in R

What about .GlobalEnv$a <- "new" ? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign() function.

How do I use a custom Serializer with Jackson?

Use @JsonValue:

public class User {
    int id;
    String name;

    @JsonValue
    public int getId() {
        return id;
    }
}

@JsonValue only works on methods so you must add the getId method. You should be able to skip your custom serializer altogether.

How to set up Automapper in ASP.NET Core

services.AddAutoMapper(); didn't work for me. (I am using Asp.Net Core 2.0)

After configuring as below

   var config = new AutoMapper.MapperConfiguration(cfg =>
   {                 
       cfg.CreateMap<ClientCustomer, Models.Customer>();
   });

initialize the mapper IMapper mapper = config.CreateMapper();

and add the mapper object to services as a singleton services.AddSingleton(mapper);

this way I am able to add a DI to controller

  private IMapper autoMapper = null;

  public VerifyController(IMapper mapper)
  {              
   autoMapper = mapper;  
  }

and I have used as below in my action methods

  ClientCustomer customerObj = autoMapper.Map<ClientCustomer>(customer);

How to know whether refresh button or browser back button is clicked in Firefox

For Back Button in jquery // http://code.jquery.com/jquery-latest.js

 jQuery(window).bind("unload", function() { //

and in html5 there is an event The event is called 'popstate'

window.onpopstate = function(event) {
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

and for refresh please check Check if page gets reloaded or refreshed in Javascript

In Mozilla Client-x and client-y is inside document area https://developer.mozilla.org/en-US/docs/Web/API/event.clientX

How to use the onClick event for Hyperlink using C# code?

this may help you.

In .cs page,

//Declare a string
   public string usertypeurl = "";
  //check who is the user
       //place your code to check who is the user
       //if it is admin
       usertypeurl = "help/AdminTutorial.html";
       //if it is other 
        usertypeurl = "help/UserTutorial.html";

In .aspx age pass this variabe

  <a href='<%=usertypeurl%>'>Tutorial</a>

Remove a JSON attribute

Simple:

delete myObj.test.key1;

Proper way to wait for one function to finish before continuing?

Use async/await :

async function firstFunction(){
  for(i=0;i<x;i++){
    // do something
  }
  return;
};

then use await in your other function to wait for it to return:

async function secondFunction(){
  await firstFunction();
  // now wait for firstFunction to finish...
  // do something else
};

Getting user input

In python 3.x, use input() instead of raw_input()

How do I center floated elements?

Set your container's width in px and add:

margin: 0 auto;

Reference.

How can I make Java print quotes, like "Hello"?

Adding the actual quote characters is only a tiny fraction of the problem; once you have done that, you are likely to face the real problem: what happens if the string already contains quotes, or line feeds, or other unprintable characters?

The following method will take care of everything:

public static String escapeForJava( String value, boolean quote )
{
    StringBuilder builder = new StringBuilder();
    if( quote )
        builder.append( "\"" );
    for( char c : value.toCharArray() )
    {
        if( c == '\'' )
            builder.append( "\\'" );
        else if ( c == '\"' )
            builder.append( "\\\"" );
        else if( c == '\r' )
            builder.append( "\\r" );
        else if( c == '\n' )
            builder.append( "\\n" );
        else if( c == '\t' )
            builder.append( "\\t" );
        else if( c < 32 || c >= 127 )
            builder.append( String.format( "\\u%04x", (int)c ) );
        else
            builder.append( c );
    }
    if( quote )
        builder.append( "\"" );
    return builder.toString();
}

ggplot2: sorting a plot

This seems to be what you're looking for:

g <- ggplot(x, aes(reorder(variable, value), value))
g + geom_bar() + scale_y_continuous(formatter="percent") + coord_flip()

The reorder() function will reorder your x axis items according to the value of variable.

Broadcast receiver for checking internet connection in android app

Answer to your first question: Your broadcast receiver is being called two times because

You have added two <intent-filter>

  1. Change in network connection :
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

  2. Change in WiFi state:
    <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />

Just use one:
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />.

It will respond to only one action instead of two. See here for more information.

Answer to your second question (you want receiver to call only one time if internet connection available):

Your code is perfect; you notify only when internet is available.

UPDATE

You can use this method to check your connectivity if you want just to check whether mobile is connected with the internet or not.

public boolean isOnline(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    //should check null because in airplane mode it will be null
    return (netInfo != null && netInfo.isConnected());
}

Convert Float to Int in Swift

Use a function style conversion (found in section labeled "Integer and Floating-Point Conversion" from "The Swift Programming Language."[iTunes link])

  1> Int(3.4)
$R1: Int = 3

How do I parallelize a simple Python loop?

This is the easiest way to do it!

You can use asyncio. (Documentation can be found here). It is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc. Plus it has both high-level and low-level APIs to accomodate any kind of problem.

import asyncio

def background(f):
    def wrapped(*args, **kwargs):
        return asyncio.get_event_loop().run_in_executor(None, f, *args, **kwargs)

    return wrapped

@background
def your_function(argument):
    #code

Now this function will be run in parallel whenever called without putting main program into wait state. You can use it to parallelize for loop as well. When called for a for loop, though loop is sequential but every iteration runs in parallel to the main program as soon as interpreter gets there. For instance:

@background
def your_function(argument):
    time.sleep(5)
    print('function finished for '+str(argument))


for i in range(10):
    your_function(i)


print('loop finished')

This produces following output:

loop finished
function finished for 4
function finished for 8
function finished for 0
function finished for 3
function finished for 6
function finished for 2
function finished for 5
function finished for 7
function finished for 9
function finished for 1

How to Force New Google Spreadsheets to refresh and recalculate?

None of the existing answers worked for me, but this approach did.

The problem

I was seeing lots of cells say #REF!. These are cells in a sheet that I copied from another Google Sheet doc using "Copy to > Existing Worksheet". If I press Enter in any cell, it recalculates correctly, But I don't want to do that for millions of cells.

My answer

I ran this recalcSheet() script. It takes almost 0.5 seconds per cell, which is very slow but is faster than manually fixing each cell.

function recalcSheet(){  
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  var sheet = spreadsheet.getSheetByName("put_your_sheet_name_here");  // https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getsheetbynamename
  // var range = sheet.getSelection().getActiveRange();
  // var range = sheet.getRange('A6:D6');
  var range = sheet.getDataRange();  
  recalcRange(range, spreadsheet);
}

function recalcRange(range, spreadsheet){
  // following structure of https://stackoverflow.com/a/52123839/470749
  Logger.log('Range: ' + range.getA1Notation());
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  var startRow = range.getRow();
  var startCol = range.getColumn();
  Logger.log('row: ' + startRow);
  Logger.log('col: ' + startCol);
  Logger.log('numRows: ' + numRows);
  Logger.log('numCols: ' + numCols);

  for (var r = 1; r <= numRows; r+=1) {
    for (var c = 1; c <= numCols; c+=1) {
      var originalFormula = range.getCell(r, c).getFormula(); // https://developers.google.com/apps-script/reference/spreadsheet/range#getFormula()
      Logger.log(`r,c ${r}, ${c}; originalFormula: ${originalFormula}`);
      if(originalFormula){
        range.getCell(r, c).setFormula('');
        //SpreadsheetApp.flush(); // https://webapps.stackexchange.com/a/35970/27487
        range.getCell(r, c).setFormula(originalFormula);
      }
    }
  }
  spreadsheet.toast('Each cell in the range has been recalculated.', "Finished!"); // https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#toast(String)
}

jQuery input button click event listener

More on gdoron's answer, it can also be done this way:

$(window).on("click", "#filter", function() {
    alert('clicked!');
});

without the need to place them all into $(function(){...})

Bootstrap table without stripe / borders

I know this is an old thread and that you've picked an answer, but I thought I'd post this as it is relevant for anyone else that is currently looking.

There is no reason to create new CSS rules, simply undo the current rules and the borders will disappear.


    .table>tbody>tr>th,
    .table>tbody>tr>td {
        border-top: 0;
    }

going forward, anything styled with

    .table

will show no borders.

XML Serialize generic list of serializable objects

I have an solution for a generic List<> with dynamic binded items.

class PersonalList it's the root element

[XmlRoot("PersonenListe")]
[XmlInclude(typeof(Person))] // include type class Person
public class PersonalList
{
    [XmlArray("PersonenArray")]
    [XmlArrayItem("PersonObjekt")]
    public List<Person> Persons = new List<Person>();

    [XmlElement("Listname")]
    public string Listname { get; set; }

    // Konstruktoren 
    public PersonalList() { }

    public PersonalList(string name)
    {
        this.Listname = name;
    }

    public void AddPerson(Person person)
    {
        Persons.Add(person);
    }
}

class Person it's an single list element

[XmlType("Person")] // define Type
[XmlInclude(typeof(SpecialPerson)), XmlInclude(typeof(SuperPerson))]  
        // include type class SpecialPerson and class SuperPerson
public class Person
{
    [XmlAttribute("PersID", DataType = "string")]
    public string ID { get; set; }

    [XmlElement("Name")]
    public string Name { get; set; }

    [XmlElement("City")]
    public string City { get; set; }

    [XmlElement("Age")]
    public int Age { get; set; }

    // Konstruktoren 
    public Person() { }

    public Person(string name, string city, int age, string id)
    {
        this.Name = name;
        this.City = city;
        this.Age = age;
        this.ID = id;
    }
}

class SpecialPerson inherits Person

[XmlType("SpecialPerson")] // define Type
public class SpecialPerson : Person
{
    [XmlElement("SpecialInterests")]
    public string Interests { get; set; }

    public SpecialPerson() { }

    public SpecialPerson(string name, string city, int age, string id, string interests)
    {
        this.Name = name;
        this.City = city;
        this.Age = age;
        this.ID = id;
        this.Interests = interests;
    }
}

class SuperPerson inherits Person

[XmlType("SuperPerson")] // define Type
public class SuperPerson : Person
{
    [XmlArray("Skills")]
    [XmlArrayItem("Skill")]
    public List<String> Skills { get; set; }

    [XmlElement("Alias")]
    public string Alias { get; set; }

    public SuperPerson() 
    {
        Skills = new List<String>();
    }

    public SuperPerson(string name, string city, int age, string id, string[] skills, string alias)
    {
        Skills = new List<String>();

        this.Name = name;
        this.City = city;
        this.Age = age;
        this.ID = id;
        foreach (string item in skills)
        {
            this.Skills.Add(item);   
        }
        this.Alias = alias;
    }
}

and the main test Source

static void Main(string[] args)
{
    PersonalList personen = new PersonalList(); 
    personen.Listname = "Friends";

    // normal person
    Person normPerson = new Person();
    normPerson.ID = "0";
    normPerson.Name = "Max Man";
    normPerson.City = "Capitol City";
    normPerson.Age = 33;

    // special person
    SpecialPerson specPerson = new SpecialPerson();
    specPerson.ID = "1";
    specPerson.Name = "Albert Einstein";
    specPerson.City = "Ulm";
    specPerson.Age = 36;
    specPerson.Interests = "Physics";

    // super person
    SuperPerson supPerson = new SuperPerson();
    supPerson.ID = "2";
    supPerson.Name = "Superman";
    supPerson.Alias = "Clark Kent";
    supPerson.City = "Metropolis";
    supPerson.Age = int.MaxValue;
    supPerson.Skills.Add("fly");
    supPerson.Skills.Add("strong");

    // Add Persons
    personen.AddPerson(normPerson);
    personen.AddPerson(specPerson);
    personen.AddPerson(supPerson);

    // Serialize 
    Type[] personTypes = { typeof(Person), typeof(SpecialPerson), typeof(SuperPerson) };
    XmlSerializer serializer = new XmlSerializer(typeof(PersonalList), personTypes); 
    FileStream fs = new FileStream("Personenliste.xml", FileMode.Create); 
    serializer.Serialize(fs, personen); 
    fs.Close(); 
    personen = null;

    // Deserialize 
    fs = new FileStream("Personenliste.xml", FileMode.Open); 
    personen = (PersonalList)serializer.Deserialize(fs); 
    serializer.Serialize(Console.Out, personen);
    Console.ReadLine();
}

Important is the definition and includes of the diffrent types.

What is the purpose of the single underscore "_" variable in Python?

As far as the Python languages is concerned, _ has no special meaning. It is a valid identifier just like _foo, foo_ or _f_o_o_.

Any special meaning of _ is purely by convention. Several cases are common:

  • A dummy name when a variable is not intended to be used, but a name is required by syntax/semantics.

    # iteration disregarding content
    sum(1 for _ in some_iterable)
    # unpacking disregarding specific elements
    head, *_ = values
    # function disregarding its argument
    def callback(_): return True
    
  • Many REPLs/shells store the result of the last top-level expression to builtins._.

    The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the builtins module. When not in interactive mode, _ has no special meaning and is not defined. [source]

    Due to the way names are looked up, unless shadowed by a global or local _ definition the bare _ refers to builtins._ .

    >>> 42
    42
    >>> f'the last answer is {_}'
    'the last answer is 42'
    >>> _
    'the last answer is 42'
    >>> _ = 4  # shadow ``builtins._`` with global ``_``
    >>> 23
    23
    >>> _
    4
    

    Note: Some shells such as ipython do not assign to builtins._ but special-case _.

  • In the context internationalization and localization, _ is used as an alias for the primary translation function.

    gettext.gettext(message)

    Return the localized translation of message, based on the current global domain, language, and locale directory. This function is usually aliased as _() in the local namespace (see examples below).

Inserting a text where cursor is using Javascript/jquery

Maybe a shorter version, would be easier to understand?

_x000D_
_x000D_
    jQuery("#btn").on('click', function() {_x000D_
        var $txt = jQuery("#txt");_x000D_
        var caretPos = $txt[0].selectionStart;_x000D_
        var textAreaTxt = $txt.val();_x000D_
        var txtToAdd = "stuff";_x000D_
        $txt.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<textarea id="txt" rows="15" cols="70">There is some text here.</textarea>_x000D_
<input type="button" id="btn" value="OK" />
_x000D_
_x000D_
_x000D_

I wrote this in response to How to add a text to a textbox from the current position of the pointer with jquery?

Could not load file or assembly '' or one of its dependencies

In my case in the bin folder was a non reference dll called Unity.MVC3 , i tried to search any reference to this in visual studio without success, so my solution was so easy as delete that dll from the bin folder.

Registry key Error: Java version has value '1.8', but '1.7' is required

First you should have Java 7. If you don't have, install it first (I don't know what you are using, Linux, Mac, yum, apt, homebrew, you should find out yourself.)

If you already have Java 7, run:

echo $JAVA_HOME

Output should be something like this:/usr/lib/jvm/java-8-oracle. Near this directory, you should see java-7 directory. After you found it, run

export JAVA_HOME=${java-7-dir}

Change {java-7-dir} with your directory path. Then you can run your command.

This is only a temporary solution. To change it permanently, put the above command to your ~/.bashrc file.

EDIT: If you are using Windows, change environment variable of JAVA_HOME to your Java 7 installation directory path.

Difference between document.addEventListener and window.addEventListener?

The window binding refers to a built-in object provided by the browser. It represents the browser window that contains the document. Calling its addEventListener method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.

<p>Some paragraph.</p>
<script>
  window.addEventListener("click", () => {
    console.log("Test");
  });
</script>

Following points should be noted before select window or document to addEventListners

  1. Most of the events are same for window or document but some events like resize, and other events related to loading, unloading, and opening/closing should all be set on the window.
  2. Since window has the document it is good practice to use document to handle (if it can handle) since event will hit document first.
  3. Internet Explorer doesn't respond to many events registered on the window,so you will need to use document for registering event.

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

How to program a fractal?

The mandelbrot set is generated by repeatedly evaluating a function until it overflows (some defined limit), then checking how long it took you to overflow.

Pseudocode:

MAX_COUNT = 64 // if we haven't escaped to infinity after 64 iterations, 
               // then we're inside the mandelbrot set!!!

foreach (x-pixel)
  foreach (y-pixel)
    calculate x,y as mathematical coordinates from your pixel coordinates
    value = (x, y)
    count = 0
    while value.absolutevalue < 1 billion and count < MAX_COUNT
        value = value * value + (x, y)
        count = count + 1

    // the following should really be one statement, but I split it for clarity
    if count == MAX_COUNT 
        pixel_at (x-pixel, y-pixel) = BLACK
    else 
        pixel_at (x-pixel, y-pixel) = colors[count] // some color map. 

Notes:

value is a complex number. a complex number (a+bi) is squared to give (aa-b*b+2*abi). You'll have to use a complex type, or include that calculation in your loop.

ERROR 1148: The used command is not allowed with this MySQL version

Just little addition.

Found another reincarnation in mysql.connector ver 8.0.16 It now requires allow_local_infile=True or you will see the above error. Worked in prior versions.

conn = mysql.connector.connect(host=host, user=user, passwd=passwd, database=database, allow_local_infile=True)

How do you build a Singleton in Dart?

I don't find it very intuitive reading new Singleton(). You have to read the docs to know that new isn't actually creating a new instance, as it normally would.

Here's another way to do singletons (Basically what Andrew said above).

lib/thing.dart

library thing;

final Thing thing = new Thing._private();

class Thing {
   Thing._private() { print('#2'); }
   foo() {
     print('#3');
   }
}

main.dart

import 'package:thing/thing.dart';

main() {
  print('#1');
  thing.foo();
}

Note that the singleton doesn't get created until the first time the getter is called due to Dart's lazy initialization.

If you prefer you can also implement singletons as static getter on the singleton class. i.e. Thing.singleton, instead of a top level getter.

Also read Bob Nystrom's take on singletons from his Game programming patterns book.

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

I like to do this witch i think is cleaner :

1 - Add the model to namespace:

use App\Employee;

2 - then you can do :

$employees = Employee::get();

or maybe somthing like this:

$employee = Employee::where('name', 'John')->first();

Read input numbers separated by spaces

int main() {
int sum = 0;
cout << "enter number" << endl;
int i = 0;
while (true) {
    cin >> i;
    sum += i;
    //cout << i << endl;
    if (cin.peek() == '\n') {
        break;
    }
    
}

cout << "result: " << sum << endl;
return 0;
}

I think this code works, you may enter any int numbers and spaces, it will calculate the sum of input ints

How to change JDK version for an Eclipse project

See the page Set Up JDK in Eclipse. From the add button you can add a different version of the JDK...

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

If the python version is 3.X, it's okay.

I think your python version is 2.X, the super would work when adding this code

__metaclass__ = type

so the code is

__metaclass__ = type
class B:
    def meth(self, arg):
        print arg
class C(B):
    def meth(self, arg):
        super(C, self).meth(arg)
print C().meth(1)

Equal height rows in CSS Grid Layout

The short answer is that setting grid-auto-rows: 1fr; on the grid container solves what was asked.

https://codepen.io/Hlsg/pen/EXKJba

How to automatically generate N "distinct" colors?

If N is big enough, you're going to get some similar-looking colors. There's only so many of them in the world.

Why not just evenly distribute them through the spectrum, like so:

IEnumerable<Color> CreateUniqueColors(int nColors)
{
    int subdivision = (int)Math.Floor(Math.Pow(nColors, 1/3d));
    for(int r = 0; r < 255; r += subdivision)
        for(int g = 0; g < 255; g += subdivision)
            for(int b = 0; b < 255; b += subdivision)
                yield return Color.FromArgb(r, g, b);
}

If you want to mix up the sequence so that similar colors aren't next to each other, you could maybe shuffle the resulting list.

Am I underthinking this?

visual c++: #include files from other projects in the same solution

You need to set the path to the headers in the project properties so the compiler looks there when trying to find the header file(s). I can't remember the exact location, but look though the Project properties and you should see it.

Array of an unknown length in C#

var yummy = new List<string>();
while(person.FeelsHappy()) {
    yummy.Add(person.GetNewFavoriteFood());
}
Console.WriteLine("Sweet! I have a list of size {0}.", list.Count);
Console.WriteLine("I didn't even need to know how big to make it " +
    "until I finished making it!");

How to loop an object in React?

I highly suggest you to use an array instead of an object if you're doing react itteration, this is a syntax I use it ofen.

const rooms = this.state.array.map((e, i) =>(<div key={i}>{e}</div>))

To use the element, just place {rooms} in your jsx.

Where e=elements of the arrays and i=index of the element. Read more here. If your looking for itteration, this is the way to do it.

How to order results with findBy() in Doctrine

$ens = $em->getRepository('AcmeBinBundle:Marks')
              ->findBy(
                 array(), 
                 array('id' => 'ASC')
               );

Contains method for a slice

It might be considered a bit 'hacky' but depending the size and contents of the slice, you can join the slice together and do a string search.

For example you have a slice containing single word values (e.g. "yes", "no", "maybe"). These results are appended to a slice. If you want to check if this slice contains any "maybe" results, you may use

exSlice := ["yes", "no", "yes", "maybe"]
if strings.Contains(strings.Join(exSlice, ","), "maybe") {
  fmt.Println("We have a maybe!")
}

How suitable this is really depends on the size of the slice and length of its members. There may be performance or suitability issues for large slices or long values, but for smaller slices of finite size and simple values it is a valid one-liner to achieve the desired result.

Using PowerShell to remove lines from a text file if it contains a string

Escape the | character using a backtick

get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt

Call a function with argument list in python

The literal answer to your question (to do exactly what you asked, changing only the wrapper, not the functions or the function calls) is simply to alter the line

func(args)

to read

func(*args)

This tells Python to take the list given (in this case, args) and pass its contents to the function as positional arguments.

This trick works on both "sides" of the function call, so a function defined like this:

def func2(*args):
    return sum(args)

would be able to accept as many positional arguments as you throw at it, and place them all into a list called args.

I hope this helps to clarify things a little. Note that this is all possible with dicts/keyword arguments as well, using ** instead of *.

how to put image in center of html page?

If:

X is image width,
Y is image height,

then:

img {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -(X/2)px;
    margin-top: -(Y/2)px;
}

But keep in mind this solution is valid only if the only element on your site will be this image. I suppose that's the case here.

Using this method gives you the benefit of fluidity. It won't matter how big (or small) someone's screen is. The image will always stay in the middle.

TypeError: 'str' object cannot be interpreted as an integer

I'm guessing you're running python3, in which input(prompt) returns a string. Try this.

x=int(input('prompt'))
y=int(input('prompt'))

Image size (Python, OpenCV)

I use numpy.size() to do the same:

import numpy as np
import cv2

image = cv2.imread('image.jpg')
height = np.size(image, 0)
width = np.size(image, 1)

How to roundup a number to the closest ten?

the second argument in ROUNDUP, eg =ROUNDUP(12345.6789,3) refers to the negative of the base-10 column with that power of 10, that you want rounded up. eg 1000 = 10^3, so to round up to the next highest 1000, use ,-3)

=ROUNDUP(12345.6789,-4) = 20,000
=ROUNDUP(12345.6789,-3) = 13,000
=ROUNDUP(12345.6789,-2) = 12,400
=ROUNDUP(12345.6789,-1) = 12,350
=ROUNDUP(12345.6789,0) = 12,346
=ROUNDUP(12345.6789,1) = 12,345.7
=ROUNDUP(12345.6789,2) = 12,345.68
=ROUNDUP(12345.6789,3) = 12,345.679

So, to answer your question: if your value is in A1, use =ROUNDUP(A1,-1)

What are the differences between a superkey and a candidate key?

Candidate key is a super key from which you cannot remove any fields.

For instance, a software release can be identified either by major/minor version, or by the build date (we assume nightly builds).

Storing date in three fields is not a good idea of course, but let's pretend it is for demonstration purposes:

year  month date  major  minor
2008  01    13     0      1
2008  04    23     0      2
2009  11    05     1      0
2010  04    05     1      1

So (year, major, minor) or (year, month, date, major) are super keys (since they are unique) but not candidate keys, since you can remove year or major and the remaining set of columns will still be a super key.

(year, month, date) and (major, minor) are candidate keys, since you cannot remove any of the fields from them without breaking uniqueness.

Global variables in AngularJS

// app.js or break it up into seperate files
// whatever structure is your flavor    
angular.module('myApp', [])    

.constant('CONFIG', {
    'APP_NAME' : 'My Awesome App',
    'APP_VERSION' : '0.0.0',
    'GOOGLE_ANALYTICS_ID' : '',
    'BASE_URL' : '',
    'SYSTEM_LANGUAGE' : ''
})

.controller('GlobalVarController', ['$scope', 'CONFIG', function($scope, CONFIG) {

    // If you wish to show the CONFIG vars in the console:
    console.log(CONFIG);

    // And your CONFIG vars in .constant will be passed to the HTML doc with this:
    $scope.config = CONFIG;
}]);

In your HTML:

<span ng-controller="GlobalVarController">{{config.APP_NAME}} | v{{config.APP_VERSION}}</span>

Editing specific line in text file in Python

This is the easiest way to do this.

fin = open("a.txt")
f = open("file.txt", "wt")
for line in fin:
    f.write( line.replace('foo', 'bar') )
fin.close()
f.close()

I hope it will work for you.

grep a tab in UNIX

These alternative binary identification methods are totally functional. And, I really like the one's using awk, as I couldn't quite remember the syntaxic use with single binary chars. However, it should also be possible to assign a shell variable a value in a POSIX portable fashion (i.e. TAB=echo "@" | tr "\100" "\011"), and then employ it from there everywhere, in a POSIX portable fashion; as well (i.e grep "$TAB" filename). While this solution works well with TAB, it will also work well other binary chars, when another desired binary value is used in the assignment (instead of the value for the TAB character to 'tr').

How to capture multiple repeated groups?

The key distinction is repeating a captured group instead of capturing a repeated group.

As you have already found out, the difference is that repeating a captured group captures only the last iteration. Capturing a repeated group captures all iterations.

In PCRE (PHP):

((?:\w+)+),?
Match 1, Group 1.    0-5      HELLO
Match 2, Group 1.    6-11     THERE
Match 3, Group 1.    12-20    BRUTALLY
Match 4, Group 1.    21-26    CRUEL
Match 5, Group 1.    27-32    WORLD

Since all captures are in Group 1, you only need $1 for substitution.

I used the following general form of this regular expression:

((?:{{RE}})+)

Example at regex101

Initialize a long in Java

To initialize long you need to append "L" to the end.
It can be either uppercase or lowercase.

All the numeric values are by default int. Even when you do any operation of byte with any integer, byte is first promoted to int and then any operations are performed.

Try this

byte a = 1; // declare a byte
a = a*2; //  you will get error here

You get error because 2 is by default int.
Hence you are trying to multiply byte with int. Hence result gets typecasted to int which can't be assigned back to byte.

Google Play app description formatting

Experimentally, I've discovered that you can provide:

  • Single line breaks are ignored; double line breaks open a new paragraph.
  • Single line breaks can be enforced by ending a line with two spaces (similar to Markdown).
  • A limited set of HTML tags (optionally nested), specifically:
    • <b>…</b> for boldface,
    • <i>…</i> for italics,
    • <u>…</u> for underline,
    • <br /> to enforce a single line break,
    • I could not find any way to get strikethrough working (neither HTML or Markdown style).
  • A fully-formatted URL such as http://google.com; this appears as a hyperlink.
    (Beware that trying to use an HTML <a> tag for a custom description does not work and breaks the formatting.)
  • HTML character entities are supported, such as &rarr; (→), &trade; (™) and &reg; (®); consult this W3 reference for the exhaustive list.
  • UTF-8 encoded characters are supported, such as é, €, £, ‘, ’, ? and ?.
  • Indentation isn't strictly possible, but using a bullet and em space character looks reasonable (&#8226;&#8195; yields "• ").
  • Emoji are also supported (though on the website depends on the user's OS & browser).

Special notes concerning only Google Play app:

  • Some HTML tags only work in the app:
    • <blockquote>…</blockquote> to indent a paragraph of text,
    • <small>…</small> for slightly smaller text,
    • <big>…</big> for slightly larger text,
    • <sup>…</sup> and <sub>…</sub> for super- and subscripts.
    • <font color="#a32345">…</font> for setting font colors in HEX code.
  • Some symbols do not appear correctly, such as ‣.
  • All these notes also apply to the app's "What's New" section.

Special notes concerning only Google Play website:

  • All HTML formatting appears as plain text in the website's "What's New" section (i.e. users will see the HTML source).

How to make join queries using Sequelize on Node.js

In my case i did following thing. In the UserMaster userId is PK and in UserAccess userId is FK of UserMaster

UserAccess.belongsTo(UserMaster,{foreignKey: 'userId'});
UserMaster.hasMany(UserAccess,{foreignKey : 'userId'});
var userData = await UserMaster.findAll({include: [UserAccess]});

Detect click outside element

Complete case for vue 3

This is a complete solution based on MadisonTrash answer, and benrwb and fredrivett tweaks for safari compatibility and vue 3 api changes.

Edit:

The solution proposed below is still useful, and the how to use is still valid, but I changed it to use document.elementsFromPoint instead of event.contains because it doesn't recognise as children some elements like the <path> tags inside svgs. So the right directive is this one:

export default {
    beforeMount: (el, binding) => {
        el.eventSetDrag = () => {
            el.setAttribute("data-dragging", "yes");
        };
        el.eventClearDrag = () => {
            el.removeAttribute("data-dragging");
        };
        el.eventOnClick = event => {
            const dragging = el.getAttribute("data-dragging");
            // Check that the click was outside the el and its children, and wasn't a drag
            console.log(document.elementsFromPoint(event.clientX, event.clientY))
            if (!document.elementsFromPoint(event.clientX, event.clientY).includes(el) && !dragging) {
                // call method provided in attribute value
                binding.value(event);
            }
        };
        document.addEventListener("touchstart", el.eventClearDrag);
        document.addEventListener("touchmove", el.eventSetDrag);
        document.addEventListener("click", el.eventOnClick);
        document.addEventListener("touchend", el.eventOnClick);
    },
    unmounted: el => {
        document.removeEventListener("touchstart", el.eventClearDrag);
        document.removeEventListener("touchmove", el.eventSetDrag);
        document.removeEventListener("click", el.eventOnClick);
        document.removeEventListener("touchend", el.eventOnClick);
        el.removeAttribute("data-dragging");
    },
};

Old answer:

Directive

const clickOutside = {
    beforeMount: (el, binding) => {
        el.eventSetDrag = () => {
            el.setAttribute("data-dragging", "yes");
        };
        el.eventClearDrag = () => {
            el.removeAttribute("data-dragging");
        };
        el.eventOnClick = event => {
            const dragging = el.getAttribute("data-dragging");  
            // Check that the click was outside the el and its children, and wasn't a drag
            if (!(el == event.target || el.contains(event.target)) && !dragging) {
                // call method provided in attribute value
                binding.value(event);
            }
        };
        document.addEventListener("touchstart", el.eventClearDrag);
        document.addEventListener("touchmove", el.eventSetDrag);
        document.addEventListener("click", el.eventOnClick);
        document.addEventListener("touchend", el.eventOnClick);
    },
    unmounted: el => {
        document.removeEventListener("touchstart", el.eventClearDrag);
        document.removeEventListener("touchmove", el.eventSetDrag);
        document.removeEventListener("click", el.eventOnClick);
        document.removeEventListener("touchend", el.eventOnClick);
        el.removeAttribute("data-dragging");
    },
}

createApp(App)
  .directive("click-outside", clickOutside)
  .mount("#app");

This solution watch the element and the element's children of the component where the directive is applied to check if the event.target element is also a child. If that's the case it will not trigger, because it's inside the component.

How to use it

You only have to use as any directive, with a method reference to handle the trigger:

<template>
    <div v-click-outside="myMethod">
        <div class="handle" @click="doAnotherThing($event)">
            <div>Any content</div>
        </div>
    </div>
</template>

Fastest way to zero out a 2d array in C?

memset(array, 0, sizeof(int [n][n]));

Can I dispatch an action in reducer?

redux-loop takes a cue from Elm and provides this pattern.

Make the console wait for a user input to close

I've put in what x4u said. Eclipse wanted a try catch block around it so I let it generate it for me.

try {
        System.in.read();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

It can probably have all sorts of bells and whistles on it but I think for beginners that want a command line window not quitting this should be fine.

Also I don't know how common this is (this is my first time making jar files), but it wouldn't run by itself, only via a bat file.

java.exe -jar mylibrary.jar

The above is what the bat file had in the same folder. Seems to be an install issue.

Eclipse tutorial came from: http://eclipsetutorial.sourceforge.net/index.html

Some of the answer also came from: Oracle Thread

Check/Uncheck a checkbox on datagridview

Simple code for you it will work

private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (dgv.CurrentRow.Cells["ColumnNumber"].Value != null && (bool)dgv.CurrentRow.Cells["ColumnNumber"].Value)
    {
        dgv.CurrentRow.Cells["ColumnNumber"].Value = false;
        dgv.CurrentRow.Cells["ColumnNumber"].Value = null;
    }
    else if (dgv.CurrentRow.Cells["ColumnNumber"].Value == null )
    {
        dgv.CurrentRow.Cells["ColumnNumber"].Value = true;
    }
}

How to markdown nested list items in Bitbucket?

This worked for me in Bitbucket Cloud.

Entering this:

* item a
* item b
** item b1
** item b2
* item3

I've got this:

enter image description here

CSS full screen div with text in the middle

text-align: center will center it horizontally as for vertically put it in a span and give it a css of margin:auto 0; (you will probably also have to give the span a display: block property)

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

You can use IN operator as below

select * from dbo.books where isbn IN
(select isbn from dbo.lending where lended_date between @fdate and @tdate)

og:type and valid values : constantly being parsed as og:type=website

I have moved into the world of namespace specific open graph data and therefore dont rely on the FB types. See "edit open graph" in the apps dev tool dashboard.

Insert a row to pandas dataframe

The simplest way add a row in a pandas data frame is:

DataFrame.loc[ location of insertion ]= list( )

Example :

DF.loc[ 9 ] = [ ´Pepe’ , 33, ´Japan’ ]

NB: the length of your list should match that of the data frame.

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

  1. mysql -u root -p
  2. UPDATE mysql.user SET Password=PASSWORD('mypass') WHERE User='root';
  3. Flush the privileges: FLUSH PRIVILEGES;
  4. Exit by typing: Exit
  5. Edited line in the file config.inc.php with the new root password: $cfg['Servers'][$i]['password'] = 'mypass'

  6. be succss

Compiling and Running Java Code in Sublime Text 2

By following the steps below, you will have 2 Build Systems in sublime - "JavaC" and "JavaC_Input".

"JavaC" would let you run code that doesn't require user input and display the results in sublime's terminal simulator, which is convenient and nice-looking. "JavaC_Input" lets you run code that requires user input in a separate terminal window, it's able to accept user input. You can also run non-input-requiring code in this build system, so if you don't mind the pop-up, you can just stick with this build system and don't switch. You switch between build systems from Tools -> Build System. And you compile&run code using ctrl+b.

Here are the steps to achieve this:

(note: Make sure you already have the basic setup of the java system: install JDK and set up correct CLASSPATH and PATH, I won't elaborate on this)

"JavaC" build system setup

1, Make a bat file with the following code, and save it under C:\Program Files\Java\jdk*\bin\ to keep everything together. Name the file "javacexec.bat".

@ECHO OFF
cd %~dp1
javac %~nx1
java %~n1

2, Then edit C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\JavaC.sublime-build (if there isn't any, create one), the contents will be

{
   "cmd": ["javacexec.bat", "$file"],
   "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
   "selector": "source.java"
}

"JavaC_Input" build system setup

1, Install Cygwin [http://www.cygwin.com/]

2, Go to C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\, then create a file called "JavaC_Input.sublime-build" with the following content

{
"cmd": ["javacexec_input.bat", "$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java"
}

3, Make a bat file with the following code, and save it under C:\Program Files\Java\jdk*\bin\ to keep everything together. Name the file "javacexec_input.bat".

@echo off
javac  -Xlint:unchecked %~n1.java 
start cmd /k java -ea %~n1

How to call external url in jquery?

JQuery and PHP

In PHP file "contenido.php":

<?php
$mURL = $_GET['url'];

echo file_get_contents($mURL);
?>

In html:

<script type="text/javascript" src="js/jquery/jquery.min.js"></script>
<script type="text/javascript">
    function getContent(pUrl, pDivDestino){
        var mDivDestino = $('#'+pDivDestino);

        $.ajax({
            type : 'GET',
            url : 'contenido.php',
            dataType : 'html',
            data: {
                url : pUrl
            },
            success : function(data){                                               
                mDivDestino.html(data);
            }   
        });
    }
</script>

<a href="#" onclick="javascript:getContent('http://www.google.com/', 'contenido')">Get Google</a>
<div id="contenido"></div>

CSS transition between left -> right and top -> bottom positions

In more modern browsers (including IE 10+) you can now use calc():

.moveto {
  top: 0px;
  left: calc(100% - 50px);
}

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

Remove a file from the list that will be committed

Most of these answers circulate around removing a file from the "staging area" pre-commit, but I often find myself looking here after I've already committed and I want to remove some sensitive information from the commit I just made.

An easy to remember trick for all of you git commit --amend folks out there like me is that you can:

  1. Delete the accidentally committed file.
  2. git add . to add the deletion to the "staging area"
  3. git commit --amend to remove the file from the previous commit.

You will notice in the commit message that the unwanted file is now missing. Hooray! (Commit SHA will have changed, so be careful if you already pushed your changes to the remote.)

How to use matplotlib tight layout with Figure?

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so 
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()

enter image description here

How can I programmatically determine if my app is running in the iphone simulator?

The previous answers are a little dated. I found that all you need to do is query the TARGET_IPHONE_SIMULATOR macro (no need to include any other header files [assuming you are coding for iOS]).

I attempted TARGET_OS_IPHONE but it returned the same value (1) when running on an actual device and simulator, that's why I recommend using TARGET_IPHONE_SIMULATOR instead.

Windows 7 environment variable not working in path

%M2% and %JAVA_HOME% need to be added to a PATH variable in the USER variables, not the SYSTEM variables.

How to convert a JSON string to a Map<String, String> with Jackson JSON

ObjectReader reader = new ObjectMapper().readerFor(Map.class);

Map<String, String> map = reader.readValue("{\"foo\":\"val\"}");

Note that reader instance is Thread Safe.

How to delete from a text file, all lines that contain a specific string?

cat filename | grep -v "pattern" > filename.1
mv filename.1 filename

How to give a pandas/matplotlib bar graph custom colors

For a more detailed answer on creating your own colormaps, I highly suggest visiting this page

If that answer is too much work, you can quickly make your own list of colors and pass them to the color parameter. All the colormaps are in the cm matplotlib module. Let's get a list of 30 RGB (plus alpha) color values from the reversed inferno colormap. To do so, first get the colormap and then pass it a sequence of values between 0 and 1. Here, we use np.linspace to create 30 equally-spaced values between .4 and .8 that represent that portion of the colormap.

from matplotlib import cm
color = cm.inferno_r(np.linspace(.4, .8, 30))
color

array([[ 0.865006,  0.316822,  0.226055,  1.      ],
       [ 0.851384,  0.30226 ,  0.239636,  1.      ],
       [ 0.832299,  0.283913,  0.257383,  1.      ],
       [ 0.817341,  0.270954,  0.27039 ,  1.      ],
       [ 0.796607,  0.254728,  0.287264,  1.      ],
       [ 0.775059,  0.239667,  0.303526,  1.      ],
       [ 0.758422,  0.229097,  0.315266,  1.      ],
       [ 0.735683,  0.215906,  0.330245,  1.      ],
       .....

Then we can use this to plot, using the data from the original post:

import random
x = [{i: random.randint(1, 5)} for i in range(30)]
df = pd.DataFrame(x)
df.plot(kind='bar', stacked=True, color=color, legend=False, figsize=(12, 4))

enter image description here

Create an application setup in visual studio 2013

Microsoft recommends to use the "InstallShield Limited Edition for Visual Studio" as replacement for the discontinued "Deployment and Setup Project" - but it is not so nice and nobody else recommends to use it. But for simple setups, and if it is not a problem to relay on commercial third party products, you can use it.

The alternative is to use Windows Installer XML (WiX), but you have to do many things manually that did the Setup-Project by itself.

Deleting a SQL row ignoring all foreign keys and constraints

Do not under any circumstances disable the constraints. This is an extremely stupid practice. You cannot maintain data integrity if you do things like this. Data integrity is the first consideration of a database because without it, you have nothing.

The correct method is to delete from the child tables before trying to delete the parent record. You are probably timing out because you have set up cascading deltes which is another bad practice in a large database.

PHP Warning: PHP Startup: ????????: Unable to initialize module

Looks like you haven't upgraded PHP modules, they are not compatible.

Check extension_dir directive in your php.ini. It should point to folder with 5.2 modules.

Create and open a phpinfo file and search for extension_dir to find the path.

Since you did upgrade, there is a chance that you are using old php.ini that is pointing to 5.1 modules

SonarQube Exclude a directory

Just to mention that once you excluded the files from Sonar, do the same for Jacoco plugin:

<configuration>
<excludes>     
<exclude>com/acme/model/persistence/entity/TransactionEntity*</exclude>
<exclude>com/acme/model/persistence/ModelConstants.class</exclude>
</excludes>
</configuration> 

SLF4J: Class path contains multiple SLF4J bindings

I just ignored/removed that jar file.

enter image description here

Make a bucket public in Amazon S3

Amazon provides a policy generator tool:

https://awspolicygen.s3.amazonaws.com/policygen.html

After that, you can enter the policy requirements for the bucket on the AWS console:

https://console.aws.amazon.com/s3/home

Show tables, describe tables equivalent in redshift

In the following post, I documented queries to retrieve TABLE and COLUMN comments from Redshift. https://sqlsylvia.wordpress.com/2017/04/29/redshift-comment-views-documenting-data/

Enjoy!

Table Comments

    SELECT n.nspname AS schema_name
     , pg_get_userbyid(c.relowner) AS table_owner
     , c.relname AS table_name
     , CASE WHEN c.relkind = 'v' THEN 'view' ELSE 'table' END 
       AS table_type
     , d.description AS table_description
     FROM pg_class As c
     LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
     LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
     LEFT JOIN pg_description As d 
          ON (d.objoid = c.oid AND d.objsubid = 0)
     WHERE c.relkind IN('r', 'v') AND d.description > ''
     ORDER BY n.nspname, c.relname ;

Column Comments

    SELECT n.nspname AS schema_name
     , pg_get_userbyid(c.relowner) AS table_owner
     , c.relname AS table_name
     , a.attname AS column_name
     , d.description AS column_description
    FROM pg_class AS c
    INNER JOIN pg_attribute As a ON c.oid = a.attrelid
    INNER JOIN pg_namespace n ON n.oid = c.relnamespace
    LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
    LEFT JOIN pg_description As d 
     ON (d.objoid = c.oid AND d.objsubid = a.attnum)
    WHERE c.relkind IN('r', 'v')
     AND a.attname NOT         
     IN ('cmax', 'oid', 'cmin', 'deletexid', 'ctid', 'tableoid','xmax', 'xmin', 'insertxid')
    ORDER BY n.nspname, c.relname, a.attname;

What happened to Lodash _.pluck?

If you really want _.pluck support back, you can use a mixin:

const _ = require("lodash")

_.mixin({
    pluck: _.map
})

Because map now supports a string (the "iterator") as an argument instead of a function.

Why do some functions have underscores "__" before and after the function name?

This convention is used for special variables or methods (so-called “magic method”) such as __init__ and __len__. These methods provides special syntactic features or do special things.

For example, __file__ indicates the location of Python file, __eq__ is executed when a == b expression is executed.

A user of course can make a custom special method, which is a very rare case, but often might modify some of the built-in special methods (e.g. you should initialize the class with __init__ that will be executed at first when an instance of a class is created).

class A:
    def __init__(self, a):  # use special method '__init__' for initializing
        self.a = a
    def __custom__(self):  # custom special method. you might almost do not use it
        pass

Java FileReader encoding issue

FileReader uses Java's platform default encoding, which depends on the system settings of the computer it's running on and is generally the most popular encoding among users in that locale.

If this "best guess" is not correct then you have to specify the encoding explicitly. Unfortunately, FileReader does not allow this (major oversight in the API). Instead, you have to use new InputStreamReader(new FileInputStream(filePath), encoding) and ideally get the encoding from metadata about the file.

How to center cell contents of a LaTeX table whose columns have fixed widths?

You can use \centering with your parbox to do this.

More info here and here.

(Sorry for the Google cached link; the original one I had doesn't work anymore.)

Clear text in EditText when entered

If the use of EditText is not mandatory, you can implement this behavior easily with the new material components:

<com.google.android.material.textfield.TextInputLayout
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_field"
            app:endIconDrawable="@drawable/ic_close_black_24dp"
            app:endIconMode="clear_text"
            app:endIconTint="@color/black">

            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/hint_value"
                android:maxLines="1"
                android:text="@{itemModel.value}" />

        </com.google.android.material.textfield.TextInputLayout>

You only have to specify the drawable you want for the button that will clear the text and the action that it will execute. To clear the text, you can use iconMode="clear_text", but also "password_toggle" is available.

How to sort findAll Doctrine's method?

You can sort an existing ArrayCollection using an array iterator.

assuming $collection is your ArrayCollection returned by findAll()

$iterator = $collection->getIterator();
$iterator->uasort(function ($a, $b) {
    return ($a->getPropery() < $b->getProperty()) ? -1 : 1;
});
$collection = new ArrayCollection(iterator_to_array($iterator));

This can easily be turned into a function you can put into your repository in order to create findAllOrderBy() method.

Reading *.wav files in Python

u can also use simple import wavio library u also need have some basic knowledge of the sound.

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

Your hosts file does not include a valid FQDN, nor is localhost an FQDN. An FQDN must include a hostname part, as well as a domain name part. For example, the following is a valid FQDN:

host.server4-245.com

Choose an FQDN and include it both in your /etc/hosts file on both the IPv4 and IPv6 addresses you are using (in your case, localhost or 127.0.0.1), and change your ServerName in your httpd configuration to match.

/etc/hosts:

127.0.0.1    localhost.localdomain localhost host.server4-245.com
::1          localhost.localdomain localhost host.server4-245.com

httpd.conf:

ServerName host.server4-245.com

jQuery loop over JSON result from AJAX Success?

Try jQuery.map function, works pretty well with maps.

_x000D_
_x000D_
var mapArray = {_x000D_
  "lastName": "Last Name cannot be null!",_x000D_
  "email": "Email cannot be null!",_x000D_
  "firstName": "First Name cannot be null!"_x000D_
};_x000D_
_x000D_
$.map(mapArray, function(val, key) {_x000D_
  alert("Value is :" + val);_x000D_
  alert("key is :" + key);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How to write and read java serialized objects into a file

I think you have to write each object to an own File or you have to split the one when reading it. You may also try to serialize your list and retrieve that when deserializing.

Can't install any package with node npm

This worked for me (not using proxy):

  1. set registry mirror for npm..

    npm config set registry http://skimdb.npmjs.com/registry

found mirror from docs:https://docs.npmjs.com/misc/registry

  1. after this try npm install if it works then try to install whatever you want otherwise follow below steps as well

3.npm install -g handlebar //i did because it was showing error in npm log but you can skip

4.after that try to set again official registry

npm config set registry http://registry.npmjs.org

5.now try to install whatever package you want :-)

iOS: how to perform a HTTP POST request?

I thought I would update this post a bit and say that alot of the iOS community has moved over to AFNetworking after ASIHTTPRequest was abandoned. I highly recommend it. It's a great wrapper around NSURLConnection and allows for asynchronous calls, and basically anything you might need.

How to output loop.counter in python jinja template?

if you are using django use forloop.counter instead of loop.counter

<ul>
{% for user in userlist %}
  <li>
      {{ user }} {{forloop.counter}}
  </li>
      {% if forloop.counter == 1 %}
          This is the First user
      {% endif %}
{% endfor %}
</ul>

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

All good answers. To put it in simple language [BCNF] No partial key can depend on a key.

i.e No partial subset ( i.e any non trivial subset except the full set ) of a candidate key can be functionally dependent on some candidate key.

How can I get the first two digits of a number?

You can convert your number to string and use list slicing like this:

int(str(number)[:2])

Output:

>>> number = 1520
>>> int(str(number)[:2])
15

What are the obj and bin folders (created by Visual Studio) used for?

One interesting fact about the obj directory: If you have publishing set up in a web project, the files that will be published are staged to obj\Release\Package\PackageTmp. If you want to publish the files yourself rather than use the integrated VS feature, you can grab the files that you actually need to deploy here, rather than pick through all the digital debris in the bin directory.

Get current time in hours and minutes

Provide a format string:

date +"%H:%M"

Running man date will give all the format options

%a     locale's abbreviated weekday name (e.g., Sun)
%A     locale's full weekday name (e.g., Sunday)
%b     locale's abbreviated month name (e.g., Jan)
%B     locale's full month name (e.g., January)
%c     locale's date and time (e.g., Thu Mar  3 23:05:25 2005)
%C     century; like %Y, except omit last two digits (e.g., 20)
%d     day of month (e.g., 01)
%D     date; same as %m/%d/%y
%e     day of month, space padded; same as %_d
%F     full date; same as %Y-%m-%d
%g     last two digits of year of ISO week number (see %G)
%G     year of ISO week number (see %V); normally useful only with %V
%h     same as %b
%H     hour (00..23)
%I     hour (01..12)
%j     day of year (001..366)
%k     hour, space padded ( 0..23); same as %_H
%l     hour, space padded ( 1..12); same as %_I
%m     month (01..12)
%M     minute (00..59)
%n     a newline
%N     nanoseconds (000000000..999999999)
%p     locale's equivalent of either AM or PM; blank if not known
%P     like %p, but lower case
%r     locale's 12-hour clock time (e.g., 11:11:04 PM)
%R     24-hour hour and minute; same as %H:%M
%s     seconds since 1970-01-01 00:00:00 UTC
%S     second (00..60)
%t     a tab
%T     time; same as %H:%M:%S
%u     day of week (1..7); 1 is Monday
%U     week number of year, with Sunday as first day of week (00..53)
%V     ISO week number, with Monday as first day of week (01..53)
%w     day of week (0..6); 0 is Sunday
%W     week number of year, with Monday as first day of week (00..53)
%x     locale's date representation (e.g., 12/31/99)
%X     locale's time representation (e.g., 23:13:48)
%y     last two digits of year (00..99)
%Y     year
%z     +hhmm numeric time zone (e.g., -0400)
%:z    +hh:mm numeric time zone (e.g., -04:00)
%::z   +hh:mm:ss numeric time zone (e.g., -04:00:00)
%:::z  numeric time zone with : to necessary precision (e.g., -04, +05:30)
%Z     alphabetic time zone abbreviation (e.g., EDT)

How do I make a textbox that only accepts numbers?

Both integers and floats need to be accepted, including the negative numbers.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // Text
    string text = ((Control) sender).Text;

    // Is Negative Number?
    if (e.KeyChar == '-' && text.Length == 0)
    {
        e.Handled = false;
        return;
    }

    // Is Float Number?
    if (e.KeyChar == '.' && text.Length > 0 && !text.Contains("."))
    {
        e.Handled = false;
        return;
    }

    // Is Digit?
    e.Handled = (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar));
}

Mailto links do nothing in Chrome but work in Firefox?

I solved the problem using this code:

_x000D_
_x000D_
    _x000D_
<button onclick="email()">Contact me !</button> _x000D_
_x000D_
<script>_x000D_
function email() {_x000D_
    var str = window.open('mailto:[email protected]', '_blank');_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

It worked for me like a charm !

PHP Email sending BCC

You have $headers .= '...'; followed by $headers = '...';; the second line is overwriting the first.

Just put the $headers .= "Bcc: $emailList\r\n"; say after the Content-type line and it should be fine.

On a side note, the To is generally required; mail servers might mark your message as spam otherwise.

$headers  = "From: [email protected]\r\n" .
  "X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";

How do I set the background color of my main screen in Flutter?

I think you can also use a scaffold to do the white background. Here's some piece of code that may help.

import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
  @override
    Widget build(BuildContext context) {

      return new MaterialApp(
        title: 'Testing',
        home: new Scaffold(
        //Here you can set what ever background color you need.
          backgroundColor: Colors.white,
        ),
      );
    }
}

Hope this helps .

What is (x & 1) and (x >>= 1)?

x & 1 is equivalent to x % 2.

x >> 1 is equivalent to x / 2

So, these things are basically the result and remainder of divide by two.

Batch file to copy files from one folder to another folder

Look at rsync based Windows tool NASBackup. It will be a bonus if you are acquainted with rsync commands.

CSS text-align not working

Change the rule on your <a> element from:

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
}?

to

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
    width:100%;
    text-align:center;
}?

Just add two new rules (width:100%; and text-align:center;). You need to make the anchor expand to take up the full width of the list item and then text-align center it.

jsFiddle example

Convert XML String to Object

You can use xsd.exe to create schema bound classes in .Net then XmlSerializer to Deserialize the string : http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx

android - setting LayoutParams programmatically

after creating the view we have to add layout parameters .

change like this

TextView tv = new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT));

llview.addView(tv);
tv.setTextColor(Color.WHITE);
tv.setTextSize(2,25);
tv.setText(chat);
if (mine) {
    leftMargin = 5;
    tv.setBackgroundColor(0x7C5B77);
}
else {
    leftMargin = 50;
    tv.setBackgroundColor(0x778F6E);
}
final ViewGroup.MarginLayoutParams lpt =(MarginLayoutParams)tv.getLayoutParams();
lpt.setMargins(leftMargin,lpt.topMargin,lpt.rightMargin,lpt.bottomMargin);

batch script - run command on each file in directory

you can run something like this (paste the code bellow in a .bat, or if you want it to run interractively replace the %% by % :

for %%i in (c:\directory\*.xls) do ssconvert %%i %%i.xlsx

If you can run powershell it will be :

Get-ChildItem -Path c:\directory -filter *.xls | foreach {ssconvert $($_.FullName) $($_.baseName).xlsx }

How to get the IP address of the docker host from inside a docker container

The standard best practice for most apps looking to do this automatically is: you don't. Instead you have the person running the container inject an external hostname/ip address as configuration, e.g. as an environment variable or config file. Allowing the user to inject this gives you the most portable design.

Why would this be so difficult? Because containers will, by design, isolate the application from the host environment. The network is namespaced to just that container by default, and details of the host are protected from the process running inside the container which may not be fully trusted.


There are different options depending on your specific situation:

If your container is running with host networking, then you can look at the routing table on the host directly to see the default route out. From this question the following works for me e.g.:

ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'

An example showing this with host networking in a container looks like:

docker run --rm --net host busybox /bin/sh -c \
  "ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'"

For current versions of Docker Desktop, they injected a DNS entry into the embedded VM:

getent hosts host.docker.internal | awk '{print $1}'

With the 20.10 release, the host.docker.internal alias can also work on Linux if you run your containers with an extra option:

docker run --add-host host.docker.internal:host-gateway ...

If you are running in a cloud environment, you can check the metadata service from the cloud provider, e.g. the AWS one:

curl http://169.254.169.254/latest/meta-data/local-ipv4

If you want your external/internet address, you can query a remote service like:

curl ifconfig.co

Each of these have limitations and only work in specific scenarios. The most portable option is still to run your container with the IP address injected as a configuration, e.g. here's an option running the earlier ip command on the host and injecting it as an environment variable:

export HOST_IP=$(ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p')
docker run --rm -e HOST_IP busybox printenv HOST_IP

How to refresh datagrid in WPF

Reload the datasource of your grid after the update

myGrid.ItemsSource = null;
myGrid.ItemsSource = myDataSource;

jquery - Click event not working for dynamically created button

You create buttons dynamically because of that you need to call them with .live() method if you use jquery 1.7

but this method is deprecated (you can see the list of all deprecated method here) in newer version. if you want to use jquery 1.10 or above you need to call your buttons in this way:

$(document).on('click', 'selector', function(){ 
     // Your Code
});

For Example

If your html is something like this

<div id="btn-list">
    <div class="btn12">MyButton</div>
</div>

You can write your jquery like this

$(document).on('click', '#btn-list .btn12', function(){ 
     // Your Code
});

Find string between two substrings

s = "123123STRINGabcabc"

def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
    except ValueError:
        return ""

def find_between_r( s, first, last ):
    try:
        start = s.rindex( first ) + len( first )
        end = s.rindex( last, start )
        return s[start:end]
    except ValueError:
        return ""


print find_between( s, "123", "abc" )
print find_between_r( s, "123", "abc" )

gives:

123STRING
STRINGabc

I thought it should be noted - depending on what behavior you need, you can mix index and rindex calls or go with one of the above versions (it's equivalent of regex (.*) and (.*?) groups).

Importing data from a JSON file into R

If the URL is https, like used for Amazon S3, then use getURL

json <- fromJSON(getURL('https://s3.amazonaws.com/bucket/my.json'))

SQL Sum Multiple rows into one

You should group by the field you want the SUM apply to, and not include in SELECT any field other than multiple rows values, like COUNT, SUM, AVE, etc, because if you include Bill field like in this case, only the first value in the set of rows will be displayed, being almost meaningless and confusing.

This will return the sum of bills per account number:

SELECT SUM(Bill) FROM Table1 GROUP BY AccountNumber

You could add more clauses like WHERE, ORDER BY etc as needed.

Removing duplicate values from a PowerShell array

This is how you get unique from an array with two or more properties. The sort is vital and the key to getting it to work correctly. Otherwise you just get one item returned.

PowerShell Script:

$objects = @(
    [PSCustomObject] @{ Message = "1"; MachineName = "1" }
    [PSCustomObject] @{ Message = "2"; MachineName = "1" }
    [PSCustomObject] @{ Message = "3"; MachineName = "1" }
    [PSCustomObject] @{ Message = "4"; MachineName = "1" }
    [PSCustomObject] @{ Message = "5"; MachineName = "1" }
    [PSCustomObject] @{ Message = "1"; MachineName = "2" }
    [PSCustomObject] @{ Message = "2"; MachineName = "2" }
    [PSCustomObject] @{ Message = "3"; MachineName = "2" }
    [PSCustomObject] @{ Message = "4"; MachineName = "2" }
    [PSCustomObject] @{ Message = "5"; MachineName = "2" }
    [PSCustomObject] @{ Message = "1"; MachineName = "1" }
    [PSCustomObject] @{ Message = "2"; MachineName = "1" }
    [PSCustomObject] @{ Message = "3"; MachineName = "1" }
    [PSCustomObject] @{ Message = "4"; MachineName = "1" }
    [PSCustomObject] @{ Message = "5"; MachineName = "1" }
    [PSCustomObject] @{ Message = "1"; MachineName = "2" }
    [PSCustomObject] @{ Message = "2"; MachineName = "2" }
    [PSCustomObject] @{ Message = "3"; MachineName = "2" }
    [PSCustomObject] @{ Message = "4"; MachineName = "2" }
    [PSCustomObject] @{ Message = "5"; MachineName = "2" }
)

Write-Host "Sorted on both properties with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property Message,MachineName -Unique | Out-Host

Write-Host "Sorted on just Message with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property Message -Unique | Out-Host

Write-Host "Sorted on just MachineName with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property MachineName -Unique | Out-Host

Output:

Sorted on both properties with -Unique

Message MachineName
------- -----------
1       1          
1       2          
2       1          
2       2          
3       1          
3       2          
4       1          
4       2          
5       1          
5       2          


Sorted on just Message with -Unique

Message MachineName
------- -----------
1       1          
2       1          
3       1          
4       1          
5       2          


Sorted on just MachineName with -Unique

Message MachineName
------- -----------
1       1          
3       2  

Source: https://powershell.org/forums/topic/need-to-unique-based-on-multiple-properties/

Cross domain POST request is not sending cookie Ajax Jquery

You cannot set or read cookies on CORS requests through JavaScript. Although CORS allows cross-origin requests, the cookies are still subject to the browser's same-origin policy, which means only pages from the same origin can read/write the cookie. withCredentials only means that any cookies set by the remote host are sent to that remote host. You will have to set the cookie from the remote server by using the Set-Cookie header.

How to delete all files from a specific folder?

System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(myDirPath);

foreach (FileInfo file in myDirInfo.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
{
    dir.Delete(true); 
}

RegEx - Match Numbers of Variable Length

What regex engine are you using? Most of them will support the following expression:

\{\d+:\d+\}

The \d is actually shorthand for [0-9], but the important part is the addition of + which means "one or more".