Programs & Examples On #Xaf

The DevExpress eXpressApp Framework (XAF) is a modern and flexible .NET application framework that allows you to create powerful line-of-business applications that simultaneously target Windows and the Web.

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

On a rather unrelated note: more performance hacks!

  • [the first «conjecture» has been finally debunked by @ShreevatsaR; removed]

  • When traversing the sequence, we can only get 3 possible cases in the 2-neighborhood of the current element N (shown first):

    1. [even] [odd]
    2. [odd] [even]
    3. [even] [even]

    To leap past these 2 elements means to compute (N >> 1) + N + 1, ((N << 1) + N + 1) >> 1 and N >> 2, respectively.

    Let`s prove that for both cases (1) and (2) it is possible to use the first formula, (N >> 1) + N + 1.

    Case (1) is obvious. Case (2) implies (N & 1) == 1, so if we assume (without loss of generality) that N is 2-bit long and its bits are ba from most- to least-significant, then a = 1, and the following holds:

    (N << 1) + N + 1:     (N >> 1) + N + 1:
    
            b10                    b1
             b1                     b
           +  1                   + 1
           ----                   ---
           bBb0                   bBb
    

    where B = !b. Right-shifting the first result gives us exactly what we want.

    Q.E.D.: (N & 1) == 1 ? (N >> 1) + N + 1 == ((N << 1) + N + 1) >> 1.

    As proven, we can traverse the sequence 2 elements at a time, using a single ternary operation. Another 2× time reduction.

The resulting algorithm looks like this:

uint64_t sequence(uint64_t size, uint64_t *path) {
    uint64_t n, i, c, maxi = 0, maxc = 0;

    for (n = i = (size - 1) | 1; i > 2; n = i -= 2) {
        c = 2;
        while ((n = ((n & 3)? (n >> 1) + n + 1 : (n >> 2))) > 2)
            c += 2;
        if (n == 2)
            c++;
        if (c > maxc) {
            maxi = i;
            maxc = c;
        }
    }
    *path = maxc;
    return maxi;
}

int main() {
    uint64_t maxi, maxc;

    maxi = sequence(1000000, &maxc);
    printf("%llu, %llu\n", maxi, maxc);
    return 0;
}

Here we compare n > 2 because the process may stop at 2 instead of 1 if the total length of the sequence is odd.

[EDIT:]

Let`s translate this into assembly!

MOV RCX, 1000000;



DEC RCX;
AND RCX, -2;
XOR RAX, RAX;
MOV RBX, RAX;

@main:
  XOR RSI, RSI;
  LEA RDI, [RCX + 1];

  @loop:
    ADD RSI, 2;
    LEA RDX, [RDI + RDI*2 + 2];
    SHR RDX, 1;
    SHRD RDI, RDI, 2;    ror rdi,2   would do the same thing
    CMOVL RDI, RDX;      Note that SHRD leaves OF = undefined with count>1, and this doesn't work on all CPUs.
    CMOVS RDI, RDX;
    CMP RDI, 2;
  JA @loop;

  LEA RDX, [RSI + 1];
  CMOVE RSI, RDX;

  CMP RAX, RSI;
  CMOVB RAX, RSI;
  CMOVB RBX, RCX;

  SUB RCX, 2;
JA @main;



MOV RDI, RCX;
ADD RCX, 10;
PUSH RDI;
PUSH RCX;

@itoa:
  XOR RDX, RDX;
  DIV RCX;
  ADD RDX, '0';
  PUSH RDX;
  TEST RAX, RAX;
JNE @itoa;

  PUSH RCX;
  LEA RAX, [RBX + 1];
  TEST RBX, RBX;
  MOV RBX, RDI;
JNE @itoa;

POP RCX;
INC RDI;
MOV RDX, RDI;

@outp:
  MOV RSI, RSP;
  MOV RAX, RDI;
  SYSCALL;
  POP RAX;
  TEST RAX, RAX;
JNE @outp;

LEA RAX, [RDI + 59];
DEC RDI;
SYSCALL;

Use these commands to compile:

nasm -f elf64 file.asm
ld -o file file.o

See the C and an improved/bugfixed version of the asm by Peter Cordes on Godbolt. (editor's note: Sorry for putting my stuff in your answer, but my answer hit the 30k char limit from Godbolt links + text!)

Saving binary data as file using JavaScript from a browser

Try

_x000D_
_x000D_
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
_x000D_
_x000D_

I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here

Python base64 data decode

Python 3 (and 2)

import base64
a = 'eW91ciB0ZXh0'
base64.b64decode(a)

Python 2

A quick way to decode it without importing anything:

'eW91ciB0ZXh0'.decode('base64')

or more descriptive

>>> a = 'eW91ciB0ZXh0'
>>> a.decode('base64')
'your text'

"No such file or directory" error when executing a binary

It is possible that the executable is statically linked and that is why ldd gzip does not see any links - because it isn't. I don't know much about things that far back so I don't know if there would be incompatibilities if libraries are linked in statically. I might expect there to be.

I know it's the most obvious thing going and I'm sure you've done it, but chmod +x ./gzip, yes? No such file or directory is a classic symptom of that not being done, that's why I mention it.

How many threads can a Java VM support?

I recall hearing a Clojure talk where he got to run one of his apps on some specialized machine at a trade show with thousands of cores (9000?), and it loaded them all. Unfortunately, I can't find the link right now (help?).

Based on that, I think it's safe to say that the hardware and your code are the limiting factors, not the JVM.

JavaScript property access: dot notation vs. brackets?

Generally speaking, they do the same job.
Nevertheless, the bracket notation gives you the opportunity to do stuff that you can't do with dot notation, like

var x = elem["foo[]"]; // can't do elem.foo[];

This can be extended to any property containing special characters.

What's the best way to get the current URL in Spring MVC?

If you need the URL till hostname and not the path use Apache's Common Lib StringUtil, and from URL extract the substring till third indexOf /.

public static String getURL(HttpServletRequest request){
   String fullURL = request.getRequestURL().toString();
   return fullURL.substring(0,StringUtils.ordinalIndexOf(fullURL, "/", 3)); 
}

Example: If fullURL is https://example.com/path/after/url/ then Output will be https://example.com

changing minDate option in JQuery DatePicker not working

Draco,

You can do it like this:

$("#datePickerId").datepicker(
    { dateFormat: 'DD, d MM yy',
      minDate: new Date(2009, 10 - 1, 25), // it will set minDate from 25 October 2009
      showOn: 'button',
      buttonImage: '../../images/calendar.gif',
      buttonImageOnly: true,
      hideIfNoPrevNext: true
    }
   );

remember to write -1 after month (ex. for june is -> 6 -1)

.substring error: "is not a function"

you can also quote string

''+document.location+''.substring(2,3);

How to change package name in flutter?

After trying all of the above. Simple work for me to rename package flutter with Android Studio:

Step 1:

Mac: Command + Shift + R

Linux/Windows: Ctrl + Shift + R

After change to new package and press Replace All and wait Android Studio run finish.

flutter rename package in Android Studio

Step 2:

Next, go to AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.name">

and copy package name and do the same Step 1 to rename package in AndroidManifest and build.gradle.

Finally, change the package in your MainActivity.java class (if the MainActivity.java is not available, check the MainActivity.kt)

package your.package.name;

import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {

Change the directory name. For details see the following link this:

From:

android\app\src\main\java\com\example\name

To:

android\app\src\main\java\your\new_package\name

How to connect to LocalDB in Visual Studio Server Explorer?

Visual Studio 2015 RC, has LocalDb 12 installed, similar instructions to before but still shouldn't be required to know 'magic', before hand to use this, the default instance should have been turned on ... Rant complete, no for solution:

cmd> sqllocaldb start

Which will display

LocalDB instance "MSSQLLocalDB" started.

Your instance name might differ. Either way pop over to VS and open Server Explorer, right click Data Connections, choose Add, choose SQL Server, in the server name type:

(localdb)\MSSQLLocalDB

Without entering in a DB name, click 'Test Connection'.

How to get the previous URL in JavaScript?

document.referrer is not the same as the actual URL in all situations.

I have an application where I need to establish a frameset with 2 frames. One frame is known, the other is the page I am linking from. It would seem that document.referrer would be ideal because you would not have to pass the actual file name to the frameset document.

However, if you later change the bottom frame page and then use history.back() it does not load the original page into the bottom frame, instead it reloads document.referrer and as a result the frameset is gone and you are back to the original starting window.

Took me a little while to understand this. So in the history array, document.referrer is not only a URL, it is apparently the referrer window specification as well. At least, that is the best way I can understand it at this time.

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

If the other answers don't work you can check if something else is using the port with netstat:

netstat -ano | findstr <your port number>

If nothing is already using it, the port might be excluded, try this command to see if the range is blocked by something else:

netsh interface ipv4 show excludedportrange protocol=tcp

How to get "GET" request parameters in JavaScript?

You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href.

Datagridview: How to set a cell in editing mode?

I know this is an old question, but none of the answers worked for me, because I wanted to reliably (always be able to) set the cell into edit mode when possibly executing other events like Toolbar Button clicks, menu selections, etc. that may affect the default focus after those events return. I ended up needing a timer and invoke. The following code is in a new component derived from DataGridView. This code allows me to simply make a call to myXDataGridView.CurrentRow_SelectCellFocus(myDataPropertyName); anytime I want to arbitrarily set a databound cell to edit mode (assuming the cell is Not in ReadOnly mode).

// If the DGV does not have Focus prior to a toolbar button Click, 
// then the toolbar button will have focus after its Click event handler returns.
// To reliably set focus to the DGV, we need to time it to happen After event handler procedure returns.

private string m_SelectCellFocus_DataPropertyName = "";
private System.Timers.Timer timer_CellFocus = null;

public void CurrentRow_SelectCellFocus(string sDataPropertyName)
{
  // This procedure is called by a Toolbar Button's Click Event to select and set focus to a Cell in the DGV's Current Row.
  m_SelectCellFocus_DataPropertyName = sDataPropertyName;
  timer_CellFocus = new System.Timers.Timer(10);
  timer_CellFocus.Elapsed += TimerElapsed_CurrentRowSelectCellFocus;
  timer_CellFocus.Start();
}


void TimerElapsed_CurrentRowSelectCellFocus(object sender, System.Timers.ElapsedEventArgs e)
{
  timer_CellFocus.Stop();
  timer_CellFocus.Elapsed -= TimerElapsed_CurrentRowSelectCellFocus;
  timer_CellFocus.Dispose();
  // We have to Invoke the method to avoid raising a threading error
  this.Invoke((MethodInvoker)delegate
  {
    Select_Cell(m_SelectCellFocus_DataPropertyName);
  });
}


private void Select_Cell(string sDataPropertyName)
{
  /// When the Edit Mode is Enabled, set the initial cell to the Description
  foreach (DataGridViewCell dgvc in this.SelectedCells) 
  {
    // Clear previously selected cells
    dgvc.Selected = false; 
  }
  foreach (DataGridViewCell dgvc in this.CurrentRow.Cells)
  {
    // Select the Cell by its DataPropertyName
    if (dgvc.OwningColumn.DataPropertyName == sDataPropertyName)
    {
      this.CurrentCell = dgvc;
      dgvc.Selected = true;
      this.Focus();
      return;
    }
  }
}

'React' must be in scope when using JSX react/react-in-jsx-scope?

The error is very straight forward, you imported react instead of React.

TechView.jsx

import React , { Component} from 'react';

class TechView extends Component {

    constructor(props){
       super(props);
       this.state = {
           name:'Gopinath'
       }
    }

    render(){
        return(
            <span>hello Tech View</span>
        );
    }
}

export default TechView;

Also you don't need to import render in the above code unless it's the root level index.js.

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import TechView from './TechView';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <TechView />
  </React.StrictMode>,
  document.getElementById('root')
);

serviceWorker.unregister();

Note: You could have imported render the way you did in your original post and used it directly:

import React from 'react';
import { render } from 'react-dom';
import './index.css';
import TechView from './TechView';
import * as serviceWorker from './serviceWorker';

render(
  <React.StrictMode>
    <TechView />
  </React.StrictMode>,
  document.getElementById('root')
);

serviceWorker.unregister();

Here, TechView becomes the main react component, which is conventionally also known as App. So, in this context instead of naming the file as TechView.jsx I'd name it App.jsx and instead of naming the class as TechView I'd name it App.

Checking whether a String contains a number value in Java

Why don't you try to write a function based on Integer.parseInt(String obj) ? The function could accept as parameter your String object, and then tokenize the String and use Integer.parseInt(String obj) to extract the number from the "lucky" substring...

Javadoc of Integer.parseInt(String obj)

Where is shared_ptr?

There are at least three places where you may find shared_ptr:

  1. If your C++ implementation supports C++11 (or at least the C++11 shared_ptr), then std::shared_ptr will be defined in <memory>.

  2. If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr will likely be in <memory> (Microsoft Visual C++) or <tr1/memory> (g++'s libstdc++). Boost also provides a TR1 implementation that you can use.

  3. Otherwise, you can obtain the Boost libraries and use boost::shared_ptr, which can be found in <boost/shared_ptr.hpp>.

Strip out HTML and Special Characters

preg_replace('/[^a-zA-Z0-9\s]/', '',$string) this is using for removing special character only rather than space between the strings.

Capture event onclose browser

You're looking for the onclose event.

see: https://developer.mozilla.org/en/DOM/window.onclose

note that not all browsers support this (for example firefox 2)

How to clear radio button in Javascript?

Simple, no jQuery required:

<a href="javascript:clearChecks('group1')">clear</a>

<script type="text/javascript">
function clearChecks(radioName) {
    var radio = document.form1[radioName]
    for(x=0;x<radio.length;x++) {
        document.form1[radioName][x].checked = false
    }
}

</script>

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

@Dinh Nhat, your setter method looks wrong because you put a primitive type there again and it should be:

public void setClient_os_id(Integer clientOsId) {
client_os_id = clientOsId;
}

Split array into chunks

I created the following JSFiddle to demonstrate my approach to your question.

_x000D_
_x000D_
(function() {_x000D_
  // Sample arrays_x000D_
  var //elements = ["0", "1", "2", "3", "4", "5", "6", "7"],_x000D_
      elements = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43"];_x000D_
_x000D_
  var splitElements = [],_x000D_
      delimiter = 10; // Change this value as needed_x000D_
      _x000D_
  // parameters: array, number of elements to split the array by_x000D_
  if(elements.length > delimiter){_x000D_
   splitElements = splitArray(elements, delimiter);_x000D_
  }_x000D_
  else {_x000D_
   // No need to do anything if the array's length is less than the delimiter_x000D_
   splitElements = elements;_x000D_
  }_x000D_
  _x000D_
  //Displaying result in console_x000D_
  for(element in splitElements){_x000D_
   if(splitElements.hasOwnProperty(element)){_x000D_
     console.log(element + " | " + splitElements[element]);_x000D_
    }_x000D_
  }_x000D_
})();_x000D_
_x000D_
function splitArray(elements, delimiter) {_x000D_
  var elements_length = elements.length;_x000D_
_x000D_
  if (elements_length > delimiter) {_x000D_
    var myArrays = [], // parent array, used to store each sub array_x000D_
      first = 0, // used to capture the first element in each sub array_x000D_
      index = 0; // used to set the index of each sub array_x000D_
_x000D_
    for (var i = 0; i < elements_length; ++i) {_x000D_
      if (i % delimiter === 0) {_x000D_
       // Capture the first element of each sub array from the original array, when i is a modulus factor of the delimiter._x000D_
        first = i;_x000D_
      } else if (delimiter - (i % delimiter) === 1) {_x000D_
      // Build each sub array, from the original array, sliced every time the i one minus the modulus factor of the delimiter._x000D_
        index = (i + 1) / delimiter - 1;_x000D_
        myArrays[index] = elements.slice(first, i + 1);_x000D_
      }_x000D_
      else if(i + 1 === elements_length){_x000D_
       // Build the last sub array which contain delimiter number or less elements_x000D_
       myArrays[index + 1] = elements.slice(first, i + 1);_x000D_
      }_x000D_
    }_x000D_
    // Returned is an array of arrays_x000D_
    return myArrays;_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

First of all, I have two examples: an array with less than eight elements, another with an array with more than eight elements (comment whichever one you do not want to use).

I then check for the size of the array, simple but essential to avoid extra computation. From here if the array meets the criteria (array size > delimiter) we move into the splitArray function.

The splitArray function takes in the delimiter (meaning 8, since that is what you want to split by), and the array itself. Since we are re-using the array length a lot, I am caching it in a variable, as well as the first and last.

first represents the position of the first element in an array. This array is an array made of 8 elements. So in order to determine the first element we use the modulus operator.

myArrays is the array of arrays. In it we will store at each index, any sub array of size 8 or below. This is the key strategy in the algorithm below.

index represents the index for the myArrays variable. Every time a sub array of 8 elements or less is to be stored, it needs to be stored in the corresponding index. So if we have 27 elements, that means 4 arrays. The first, second and third array will have 8 elements each. The last will have 3 elements only. So index will be 0, 1, 2, and 3 respectively.

The tricky part is simply figuring out the math and optimizing it as best as possible. For example else if (delimiter - (i % delimiter) === 1) this is to find the last element that should go in the array, when an array will be full (example: contain 10 elements).

This code works for every single scenario, you can even change the delimiter to match any array size you'd like to get. Pretty sweet right :-)

Any questions? Feel free to ask in the comments below.

How do I get the path to the current script with Node.js?

Use the basename method of the path module:

var path = require('path');
var filename = path.basename(__filename);
console.log(filename);

Here is the documentation the above example is taken from.

As Dan pointed out, Node is working on ECMAScript modules with the "--experimental-modules" flag. Node 12 still supports __dirname and __filename as above.


If you are using the --experimental-modules flag, there is an alternative approach.

The alternative is to get the path to the current ES module:

const __filename = new URL(import.meta.url).pathname;

And for the directory containing the current module:

import path from 'path';

const __dirname = path.dirname(new URL(import.meta.url).pathname);

How do I redirect with JavaScript?

window.location.replace('http://sidanmor.com');

It's better than using window.location.href = 'http://sidanmor.com';

Using replace() is better because it does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.

If you want to simulate someone clicking on a link, use window.location.href

If you want to simulate an HTTP redirect, use window.location.replace

For example:

// similar behavior as an HTTP redirect
window.location.replace("http://sidanmor.com");

// similar behavior as clicking on a link
window.location.href = "http://sidanmor.com";

Taken from here: How to redirect to another page in jQuery?

Sequence contains more than one element

As @Mehmet is pointing out, if your result is returning more then 1 elerment then you need to look into you data as i suspect that its not by design that you have customers sharing a customernumber.

But to the point i wanted to give you a quick overview.

//success on 0 or 1 in the list, returns dafault() of whats in the list if 0
list.SingleOrDefault();
//success on 1 and only 1 in the list
list.Single();

//success on 0-n, returns first element in the list or default() if 0 
list.FirstOrDefault();
//success 1-n, returns the first element in the list
list.First();

//success on 0-n, returns first element in the list or default() if 0 
list.LastOrDefault();
//success 1-n, returns the last element in the list
list.Last();

for more Linq expressions have a look at System.Linq.Expressions

download a file from Spring boot rest service

    @GetMapping("/downloadfile/{productId}/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable(value = "productId") String productId,
        @PathVariable String fileName, HttpServletRequest request) {
    // Load file as Resource
    Resource resource;

    String fileBasePath = "C:\\Users\\v_fzhang\\mobileid\\src\\main\\resources\\data\\Filesdown\\" + productId
            + "\\";
    Path path = Paths.get(fileBasePath + fileName);
    try {
        resource = new UrlResource(path.toUri());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }

    // Try to determine file's content type
    String contentType = null;
    try {
        contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
    } catch (IOException ex) {
        System.out.println("Could not determine file type.");
    }

    // Fallback to the default content type if type could not be determined
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
            .body(resource);
}

To test it, use postman

http://localhost:8080/api/downloadfile/GDD/1.zip

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I found a faster way of embedding:

  • Just copy the link.
  • Paste the link and remove the "?s=19" part and add "/video/1"
  • That's it.

window.onload vs <body onload=""/>

I prefer, generally, to not use the <body onload=""> event. I think it's cleaner to keep behavior separated from content as much as possible.

That said, there are occasions (usually pretty rare for me) where using body onload can give a slight speed boost.

I like to use Prototype so I generally put something like this in the <head> of my page:

document.observe("dom:loaded", function(){
  alert('The DOM is loaded!');
});

or

Event.observe(window, 'load', function(){
  alert('Window onload');
});

The above are tricks I learned here. I'm very fond of the concept of attach event handlers outside of the HTML.

(Edit to correct spelling mistake in code.)

How can we run a test method with multiple parameters in MSTest?

This feature is in pre-release now and works with Visual Studio 2015.

For example:

[TestClass]
public class UnitTest1
{
    [TestMethod]
    [DataRow(1, 2, 2)]
    [DataRow(2, 3, 5)]
    [DataRow(3, 5, 8)]
    public void AdditionTest(int a, int b, int result)
    {
        Assert.AreEqual(result, a + b);
    }
}

[] and {} vs list() and dict(), which is better?

The dict literal might be a tiny bit faster as its bytecode is shorter:

In [1]: import dis
In [2]: a = lambda: {}
In [3]: b = lambda: dict()

In [4]: dis.dis(a)
  1           0 BUILD_MAP                0
              3 RETURN_VALUE

In [5]: dis.dis(b)
  1           0 LOAD_GLOBAL              0 (dict)
              3 CALL_FUNCTION            0
              6 RETURN_VALUE

Same applies to the list vs []

Check if a variable exists in a list in Bash

The shell built-in compgen can help here. It can take a list with the -W flag and return any of the potential matches it finds.

# My list can contain spaces so I want to set the internal
# file separator to newline to preserve the original strings.
IFS=$'\n'

# Create a list of acceptable strings.
accept=( 'foo' 'bar' 'foo bar' )

# The string we will check
word='foo'

# compgen will return a list of possible matches of the 
# variable 'word' with the best match being first.
compgen -W "${accept[*]}" "$word"

# Returns:
# foo
# foo bar

We can write a function to test if a string equals the best match of acceptable strings. This allows you to return a 0 or 1 for a pass or fail respectively.

function validate {
  local IFS=$'\n'
  local accept=( 'foo' 'bar' 'foo bar' )
  if [ "$1" == "$(compgen -W "${accept[*]}" "$1" | head -1)" ] ; then
    return 0
  else
    return 1
  fi
}

Now you can write very clean tests to validate if a string is acceptable.

validate "blah" || echo unacceptable

if validate "foo" ; then
  echo acceptable
else 
  echo unacceptable
fi

How do I find the last column with data?

Try using the code after you active the sheet:

Dim J as integer
J = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

If you use Cells.SpecialCells(xlCellTypeLastCell).Row only, the problem will be that the xlCellTypeLastCell information will not be updated unless one do a "Save file" action. But use UsedRange will always update the information in realtime.

How do I truncate a .NET string?

There is nothing in .net for this that I am aware of - here is my version which adds "...":

public static string truncateString(string originalString, int length) {
  if (string.IsNullOrEmpty(originalString)) {
   return originalString;
  }
  if (originalString.Length > length) {
   return originalString.Substring(0, length) + "...";
  }
  else {
   return originalString;
  }
}

What is the difference between SAX and DOM?

In just a few words...

SAX (Simple API for XML): Is a stream-based processor. You only have a tiny part in memory at any time and you "sniff" the XML stream by implementing callback code for events like tagStarted() etc. It uses almost no memory, but you can't do "DOM" stuff, like use xpath or traverse trees.

DOM (Document Object Model): You load the whole thing into memory - it's a massive memory hog. You can blow memory with even medium sized documents. But you can use xpath and traverse the tree etc.

MYSQL order by both Ascending and Descending sorting

I don't understand what the meaning of ordering with the same column ASC and DESC in the same ORDER BY, but this how you can do it: naam DESC, naam ASC like so:

ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC

Sending data back to the Main Activity in Android

Just a small detail that I think is missing in above answers.

If your child activity can be opened from multiple parent activities then you can check if you need to do setResult or not, based on if your activity was opened by startActivity or startActivityForResult. You can achieve this by using getCallingActivity(). More info here.

UITableView Cell selected Color?

One more tip to Christian's way to show rounded corner background for grouped table.

If I use cornerRadius = 10 for cell, it shows four corner's rounded selection background. It's not the same with table view's default UI.

So, I think about easy way to resolve it with cornerRadius. As you can see from the below codes, check about cell's location (top, bottom, middle or topbottom) and add one more sub layers to hide top corner or bottom corner. This just shows exactly same look with default table view's selection background.

I tested this code with iPad splitterview. You can change patchLayer's frame position as you needed.

Please let me know if there is more easier way to achieve same result.

if (tableView.style == UITableViewStyleGrouped) 
{
    if (indexPath.row == 0) 
    {
        cellPosition = CellGroupPositionAtTop;
    }    
    else 
    {
        cellPosition = CellGroupPositionAtMiddle;
    }

    NSInteger numberOfRows = [tableView numberOfRowsInSection:indexPath.section];
    if (indexPath.row == numberOfRows - 1) 
    {
        if (cellPosition == CellGroupPositionAtTop) 
        {
            cellPosition = CellGroupPositionAtTopAndBottom;
        } 
        else 
        {
            cellPosition = CellGroupPositionAtBottom;
        }
    }

    if (cellPosition != CellGroupPositionAtMiddle) 
    {
        bgColorView.layer.cornerRadius = 10;
        CALayer *patchLayer;
        if (cellPosition == CellGroupPositionAtTop) 
        {
            patchLayer = [CALayer layer];
            patchLayer.frame = CGRectMake(0, 10, 302, 35);
            patchLayer.backgroundColor = YOUR_BACKGROUND_COLOR;
            [bgColorView.layer addSublayer:patchLayer];
        } 
        else if (cellPosition == CellGroupPositionAtBottom) 
        {
            patchLayer = [CALayer layer];
            patchLayer.frame = CGRectMake(0, 0, 302, 35);
            patchLayer.backgroundColor = YOUR_BACKGROUND_COLOR;
            [bgColorView.layer addSublayer:patchLayer];
        }
    }
}

How to run a PowerShell script

If you are on PowerShell 2.0, use PowerShell.exe's -File parameter to invoke a script from another environment, like cmd.exe. For example:

Powershell.exe -File C:\my_path\yada_yada\run_import_script.ps1

How to split a large text file into smaller files with equal number of lines?

HDFS getmerge small file and spilt into property size.

This method will cause line break

split -b 125m compact.file -d -a 3 compact_prefix

I try to getmerge and split into about 128MB every file.

# split into 128m ,judge sizeunit is M or G ,please test before use.

begainsize=`hdfs dfs -du -s -h /externaldata/$table_name/$date/ | awk '{ print $1}' `
sizeunit=`hdfs dfs -du -s -h /externaldata/$table_name/$date/ | awk '{ print $2}' `
if [ $sizeunit = "G" ];then
    res=$(printf "%.f" `echo "scale=5;$begainsize*8 "|bc`)
else
    res=$(printf "%.f" `echo "scale=5;$begainsize/128 "|bc`)  # celling ref http://blog.csdn.net/naiveloafer/article/details/8783518
fi
echo $res
# split into $res files with number suffix.  ref  http://blog.csdn.net/microzone/article/details/52839598
compact_file_name=$compact_file"_"
echo "compact_file_name :"$compact_file_name
split -n l/$res $basedir/$compact_file -d -a 3 $basedir/${compact_file_name}

What is the difference between npm install and npm run build?

The main difference is ::

npm install is a npm cli-command which does the predefined thing i.e, as written by Churro, to install dependencies specified inside package.json

npm run command-name or npm run-script command-name ( ex. npm run build ) is also a cli-command predefined to run your custom scripts with the name specified in place of "command-name". So, in this case npm run build is a custom script command with the name "build" and will do anything specified inside it (for instance echo 'hello world' given in below example package.json).

Ponits to note::

  1. One more thing, npm build and npm run build are two different things, npm run build will do custom work written inside package.json and npm build is a pre-defined script (not available to use directly)

  2. You cannot specify some thing inside custom build script (npm run build) script and expect npm build to do the same. Try following thing to verify in your package.json:

    { "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build":"echo 'hello build'" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": {}, "dependencies": {} }

and run npm run build and npm build one by one and you will see the difference. For more about commands kindly follow npm documentation.

Cheers!!

Is it possible to get element from HashMap by its position?

I'm assuming by 'position' you're referring to the order in which you've inserted the elements into the HashMap. In that case you want to be using a LinkedHashMap. The LinkedHashMap doesn't offer an accessor method however; you will need to write one like

public Object getElementAt(LinkedHashMap map, int index) {
    for (Map.Entry entry : map.entrySet()) {
        if (index-- == 0) {
            return entry.value();
        }
    }
    return null;
}

Job for mysqld.service failed See "systemctl status mysqld.service"

I met this problem today, and fix it with bellowed steps.

1, Check the log file /var/log/mysqld.log

tail -f /var/log/mysqld.log

 2017-03-14T07:06:53.374603Z 0 [ERROR] /usr/sbin/mysqld: Can't create/write to file '/var/run/mysqld/mysqld.pid' (Errcode: 2 - No such file or directory)
 2017-03-14T07:06:53.374614Z 0 [ERROR] Can't start server: can't create PID file: No such file or directory

The log says that there isn't a file or directory /var/run/mysqld/mysqld.pid

2, Create the directory /var/run/mysqld

mkdir -p /var/run/mysqld/

3, Start the mysqld again service mysqld start, but still fail, check the log again /var/log/mysqld.log

2017-03-14T07:14:22.967667Z 0 [ERROR] /usr/sbin/mysqld: Can't create/write to file '/var/run/mysqld/mysqld.pid' (Errcode: 13 - Permission denied)
2017-03-14T07:14:22.967678Z 0 [ERROR] Can't start server: can't create PID file: Permission denied

It saids permission denied.

4, Grant the permission to mysql chown mysql.mysql /var/run/mysqld/

5, Restart the mysqld

# service mysqld restart
Restarting mysqld (via systemctl):                         [  OK  ]

How do I scroll to an element using JavaScript?

After looking around a lot, this is what finally worked for me:

  1. Find/locate div in your dom which has scroll bar. For me, it looked like this : "div class="table_body table_body_div" scroll_top="0" scroll_left="0" style="width: 1263px; height: 499px;"

  2. I located it with this xpath : //div[@class='table_body table_body_div']

  3. Used JavaScript to execute scrolling like this : (JavascriptExecutor) driver).executeScript("arguments[0].scrollLeft = arguments[1];",element,2000);

2000 is the no of pixels I wanted to scroll towards the right. Use scrollTop instead of scrollLeft if you want to scroll your div down.

Note : I tried using scrollIntoView but it didn't work properly because my webpage had multiple divs. It will work if you have only one main window where focus lies. This is the best solution I have come across if you don't want to use jQuery which I didn't want to.

Loading another html page from javascript

You can include a .js file which has the script to set the

window.location.href = url;

Where url would be the url you wish to load.

How do I turn a C# object into a JSON string in .NET?

If they are not very big, what's probably your case export it as JSON.

Also this makes it portable among all platforms.

using Newtonsoft.Json;

[TestMethod]
public void ExportJson()
{
    double[,] b = new double[,]
        {
            { 110,  120,  130,  140, 150 },
            {1110, 1120, 1130, 1140, 1150},
            {1000,    1,   5,     9, 1000},
            {1110,    2,   6,    10, 1110},
            {1220,    3,   7,    11, 1220},
            {1330,    4,   8,    12, 1330}
        };

    string jsonStr = JsonConvert.SerializeObject(b);

    Console.WriteLine(jsonStr);

    string path = "X:\\Programming\\workspaceEclipse\\PyTutorials\\src\\tensorflow_tutorials\\export.txt";

    File.WriteAllText(path, jsonStr);
}

How to solve time out in phpmyadmin?

None of the above answers solved it for me.

I cant even find the 'libraries' folder in my xampp - ubuntu also.

So, I simply restarted using the following commands:

sudo service apache2 restart

and

sudo service mysql restart
  • Just restarted apache and mysql. Logged in phpmyadmin again and it worked as usual.

Thanks me..!!

Best way to encode Degree Celsius symbol into web page?

Using sup on the letter "o" and a capital "C"

_x000D_
_x000D_
<sup>o</sup>C
_x000D_
_x000D_
_x000D_

Should work in all browsers and IE6+

SET NAMES utf8 in MySQL?

Thanks @all!

don't use: query("SET NAMES utf8"); this is setup stuff and not a query. put it right afte a connection start with setCharset() (or similar method)

some little thing in parctice:

status:

  • mysql server by default talks latin1
  • your hole app is in utf8
  • connection is made without any extra (so: latin1) (no SET NAMES utf8 ..., no set_charset() method/function)

Store and read data is no problem as long mysql can handle the characters. if you look in the db you will already see there is crap in it (e.g.using phpmyadmin).

until now this is not a problem! (wrong but works often (in europe)) ..

..unless another client/programm or a changed library, which works correct, will read/save data. then you are in big trouble!

Usage of $broadcast(), $emit() And $on() in AngularJS

This little example shows how the $rootScope emit a event that will be listen by a children scope in another controller.

(function(){


angular
  .module('ExampleApp',[]);

angular
  .module('ExampleApp')
  .controller('ExampleController1', Controller1);

Controller1.$inject = ['$rootScope'];

function Controller1($rootScope) {
  var vm = this, 
      message = 'Hi my children scope boy';

  vm.sayHi = sayHi;

  function sayHi(){
    $rootScope.$broadcast('greeting', message);
  }

}

angular
  .module('ExampleApp')
  .controller('ExampleController2', Controller2);

Controller2.$inject = ['$scope'];

function Controller2($scope) {
  var vm = this;

  $scope.$on('greeting', listenGreeting)

  function listenGreeting($event, message){
    alert(['Message received',message].join(' : '));
  }

}


})();

http://codepen.io/gpincheiraa/pen/xOZwqa

The answer of @gayathri bottom explain technically the differences of all those methods in the scope angular concept and their implementations $scope and $rootScope.

No line-break after a hyphen

You could also wrap the relevant text with

<span style="white-space: nowrap;"></span>

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

Creating folders inside a GitHub repository without using Git

After searching a lot I find out that it is possible to create a new folder from the web interface, but it would require you to have at least one file within the folder when creating it.

When using the normal way of creating new files through the web interface, you can type in the folder into the file name to create the file within that new directory.

For example, if I would like to create the file filename.md in a series of sub-folders, I can do this (taken from the GitHub blog):

Enter image description here

Write variable to a file in Ansible

Unless you are writing very small files, you should probably use templates.

Example:

- name: copy upstart script
  template: 
    src: myCompany-service.conf.j2 
    dest: "/etc/init/myCompany-service.conf"

How can I create a small color box using html and css?

You can create these easily using the floating ability of CSS, for example. I have created a small example on Jsfiddle over here, all the related css and html is also provided there.

_x000D_
_x000D_
.foo {_x000D_
  float: left;_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  margin: 5px;_x000D_
  border: 1px solid rgba(0, 0, 0, .2);_x000D_
}_x000D_
_x000D_
.blue {_x000D_
  background: #13b4ff;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
  background: #ab3fdd;_x000D_
}_x000D_
_x000D_
.wine {_x000D_
  background: #ae163e;_x000D_
}
_x000D_
<div class="foo blue"></div>_x000D_
<div class="foo purple"></div>_x000D_
<div class="foo wine"></div>
_x000D_
_x000D_
_x000D_

Access localhost from the internet

You go into your router configuration and forward port 80 to the LAN IP of the computer running the web server.

Then anyone outside your network (but not you inside the network) can access your site using your WAN IP address (whatismyipcom).

Split string in C every white space

You should be malloc'ing strlen(ptr), not strlen(buf). Also, your count2 should be limited to the number of words. When you get to the end of your string, you continue going over the zeros in your buffer and adding zero size strings to your array.

How to extract week number in sql

Use 'dd-mon-yyyy' if you are using the 2nd date format specified in your answer. Ex:

to_date(<column name>,'dd-mon-yyyy')

Find out who is locking a file on a network share

sounds like you have the same problem i tried to solve here. in my case, it's a Linux fileserver (running samba, of course), so i can log in and see what process is locking the file; unfortunately, i haven't found how to close it without killing the responsible session. AFAICT, the windows client 'thinks' it's closed; but didn't bother telling the fileserver.

extract month from date in python

>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'

How to center a button within a div?

You could just make:

_x000D_
_x000D_
<div style="text-align: center; border: 1px solid">_x000D_
  <input type="button" value="button">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or you could do it like this instead:

_x000D_
_x000D_
<div style="border: 1px solid">_x000D_
  <input type="button" value="button" style="display: block; margin: 0 auto;">_x000D_
</div>
_x000D_
_x000D_
_x000D_

The first one will center align everything inside the div. The other one will center align just the button.

How to find a value in an array of objects in JavaScript?

You can find the object in array with Alasql library:

var data = [ { name : "bob" , dinner : "pizza" }, { name : "john" , dinner : "sushi" },
     { name : "larry", dinner : "hummus" } ];

var res = alasql('SELECT * FROM ? WHERE dinner="sushi"',[data]);

Try this example in jsFiddle.

Bootstrap4 adding scrollbar to div

      <div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
        <strong>Column 0 </strong><br>
        <strong>Column 1</strong><br>
        <strong>Column 2</strong><br>
        <strong>Column 3</strong><br>
        <strong>Column 4</strong><br>
        <strong>Column 5</strong><br>
        <strong>Column 6</strong><br>
        <strong>Column 7</strong><br>
        <strong>Column 8</strong><br>
        <strong>Column 9</strong><br>
        <strong>Column 10</strong><br>
        <strong>Column 11</strong><br>
        <strong>Column 12</strong><br>
        <strong>Column 13</strong><br>
      </div>
    </div>

CSS :selected pseudo class similar to :checked, but for <select> elements

Actually you can only style few CSS properties on :modified option elements. color does not work, background-color either, but you can set a background-image.

You can couple this with gradients to do the trick.

_x000D_
_x000D_
option:hover,_x000D_
option:focus,_x000D_
option:active,_x000D_
option:checked {_x000D_
  background: linear-gradient(#5A2569, #5A2569);_x000D_
}
_x000D_
<select>_x000D_
  <option>A</option>_x000D_
  <option>B</option>_x000D_
  <option>C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Works on gecko/webkit.

Position absolute and overflow hidden

What about position: relative for the outer div? In the example that hides the inner one. It also won't move it in its layout since you don't specify a top or left.

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

You're not passing any credentials to sqlcmd.exe

So it's trying to authenticate you using the Windows Login credentials, but you mustn't have your SQL Server setup to accept those credentials...

When you were installing it, you would have had to supply a Server Admin password (for the sa account)

Try...

sqlcmd.exe -U sa -P YOUR_PASSWORD -S ".\SQL2008"

for reference, theres more details here...

React PropTypes : Allow different types of PropTypes for one prop

Here is pro example of using multi proptypes and single proptype.

import React, { Component } from 'react';
import { string, shape, array, oneOfType } from 'prop-types';

class MyComponent extends Component {
  /**
   * Render
   */
  render() {
    const { title, data } = this.props;

    return (
      <>
        {title}
        <br />
        {data}
      </>
    );
  }
}

/**
 * Define component props
 */
MyComponent.propTypes = {
  data: oneOfType([array, string, shape({})]),
  title: string,
};

export default MyComponent;

simple HTTP server in Java using only Java SE API

Check out NanoHttpd

NanoHTTPD is a light-weight HTTP server designed for embedding in other applications, released under a Modified BSD licence.

It is being developed at Github and uses Apache Maven for builds & unit testing"

Adjusting HttpWebRequest Connection Timeout in C#

Something I found later which helped, is the .ReadWriteTimeout property. This, in addition to the .Timeout property seemed to finally cut down on the time threads would spend trying to download from a problematic server. The default time for .ReadWriteTimeout is 5 minutes, which for my application was far too long.

So, it seems to me:

.Timeout = time spent trying to establish a connection (not including lookup time) .ReadWriteTimeout = time spent trying to read or write data after connection established

More info: HttpWebRequest.ReadWriteTimeout Property

Edit:

Per @KyleM's comment, the Timeout property is for the entire connection attempt, and reading up on it at MSDN shows:

Timeout is the number of milliseconds that a subsequent synchronous request made with the GetResponse method waits for a response, and the GetRequestStream method waits for a stream. The Timeout applies to the entire request and response, not individually to the GetRequestStream and GetResponse method calls. If the resource is not returned within the time-out period, the request throws a WebException with the Status property set to WebExceptionStatus.Timeout.

(Emphasis mine.)

Get index of current item in a PowerShell loop

.NET has some handy utility methods for this sort of thing in System.Array:

PS> $a = 'a','b','c'
PS> [array]::IndexOf($a, 'b')
1
PS> [array]::IndexOf($a, 'c')
2

Good points on the above approach in the comments. Besides "just" finding an index of an item in an array, given the context of the problem, this is probably more suitable:

$letters = { 'A', 'B', 'C' }
$letters | % {$i=0} {"Value:$_ Index:$i"; $i++}

Foreach (%) can have a Begin sciptblock that executes once. We set an index variable there and then we can reference it in the process scripblock where it gets incremented before exiting the scriptblock.

No suitable records were found verify your bundle identifier is correct

What did the fix for me is to allow app access to all users:

  1. Go to AppStore Connect
  2. Go to My App
  3. Under Additional Information, click on 'Edit User Access'
  4. Select 'Full Access'
  5. This allowed me to upload the app the first time (via Xcode & Application Loader)

After the initial upload, i can switch back to 'Limited Access' and upload just fine.

DataGridView - how to set column width?

Use the Columns Property and set the Auto Size Mode to All Cells, Resizable to True, Frozen to False and visible to True.

The column will automatically resize based on the data inserted.

Make an html number input always display 2 decimal places

So if someone else stumbles upon this here is a JavaScript solution to this problem:

Step 1: Hook your HTML number input box to an onchange event

myHTMLNumberInput.onchange = setTwoNumberDecimal;

or in the html code if you so prefer

<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />

Step 2: Write the setTwoDecimalPlace method

function setTwoNumberDecimal(event) {
    this.value = parseFloat(this.value).toFixed(2);
}

By changing the '2' in toFixed you can get more or less decimal places if you so prefer.

php resize image on upload

Here is another nice and easy solution:

$maxDim = 800;
$file_name = $_FILES['myFile']['tmp_name'];
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
    $target_filename = $file_name;
    $ratio = $width/$height;
    if( $ratio > 1) {
        $new_width = $maxDim;
        $new_height = $maxDim/$ratio;
    } else {
        $new_width = $maxDim*$ratio;
        $new_height = $maxDim;
    }
    $src = imagecreatefromstring( file_get_contents( $file_name ) );
    $dst = imagecreatetruecolor( $new_width, $new_height );
    imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
    imagedestroy( $src );
    imagepng( $dst, $target_filename ); // adjust format as needed
    imagedestroy( $dst );
}

Reference: PHP resize image proportionally with max width or weight

Edit: Cleaned up and simplified the code a bit. Thanks @jan-mirus for your comment.

ERROR 2003 (HY000): Can't connect to MySQL server on localhost (10061)

Check Mysqld.exe file is in your bin folder. if it is not there , just copy that file from any other computer and paste it on your bin folder.Just double click. Then run mysql.its solved

How can I find the location of origin/master in git, and how do I change it?

[ Solution ]

$ git push origin

^ this solved it for me. What it did, it synchronized my master (on laptop) with "origin" that's on the remote server.

Duplicate headers received from server

Just put a pair of double quotes around your file name like this:

this.Response.AddHeader("Content-disposition", $"attachment; filename=\"{outputFileName}\"");

removing new line character from incoming stream using sed

This might work for you:

printf "{new\nto\nlinux}" | paste -sd' '            
{new to linux}

or:

printf "{new\nto\nlinux}" | tr '\n' ' '            
{new to linux}

or:

printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}

Toggle visibility property of div

Using jQuery:

$('#play-pause').click(function(){
  if ( $('#video-over').css('visibility') == 'hidden' )
    $('#video-over').css('visibility','visible');
  else
    $('#video-over').css('visibility','hidden');
});

String comparison technique used by Python

From the docs:

The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.

Also:

Lexicographical ordering for strings uses the Unicode code point number to order individual characters.

or on Python 2:

Lexicographical ordering for strings uses the ASCII ordering for individual characters.

As an example:

>>> 'abc' > 'bac'
False
>>> ord('a'), ord('b')
(97, 98)

The result False is returned as soon as a is found to be less than b. The further items are not compared (as you can see for the second items: b > a is True).

Be aware of lower and uppercase:

>>> [(x, ord(x)) for x in abc]
[('a', 97), ('b', 98), ('c', 99), ('d', 100), ('e', 101), ('f', 102), ('g', 103), ('h', 104), ('i', 105), ('j', 106), ('k', 107), ('l', 108), ('m', 109), ('n', 110), ('o', 111), ('p', 112), ('q', 113), ('r', 114), ('s', 115), ('t', 116), ('u', 117), ('v', 118), ('w', 119), ('x', 120), ('y', 121), ('z', 122)]
>>> [(x, ord(x)) for x in abc.upper()]
[('A', 65), ('B', 66), ('C', 67), ('D', 68), ('E', 69), ('F', 70), ('G', 71), ('H', 72), ('I', 73), ('J', 74), ('K', 75), ('L', 76), ('M', 77), ('N', 78), ('O', 79), ('P', 80), ('Q', 81), ('R', 82), ('S', 83), ('T', 84), ('U', 85), ('V', 86), ('W', 87), ('X', 88), ('Y', 89), ('Z', 90)]

How to find out the number of CPUs using python

len(os.sched_getaffinity(0)) is what you usually want

https://docs.python.org/3/library/os.html#os.sched_getaffinity

os.sched_getaffinity(0) (added in Python 3) returns the set of CPUs available considering the sched_setaffinity Linux system call, which limits which CPUs a process and its children can run on.

0 means to get the value for the current process. The function returns a set() of allowed CPUs, thus the need for len().

multiprocessing.cpu_count() and os.cpu_count() on the other hand just returns the total number of physical CPUs.

The difference is especially important because certain cluster management systems such as Platform LSF limit job CPU usage with sched_getaffinity.

Therefore, if you use multiprocessing.cpu_count(), your script might try to use way more cores than it has available, which may lead to overload and timeouts.

We can see the difference concretely by restricting the affinity with the taskset utility, which allows us to control the affinity of a process.

Minimal taskset example

For example, if I restrict Python to just 1 core (core 0) in my 16 core system:

taskset -c 0 ./main.py

with the test script:

main.py

#!/usr/bin/env python3

import multiprocessing
import os

print(multiprocessing.cpu_count())
print(os.cpu_count())
print(len(os.sched_getaffinity(0)))

then the output is:

16
16
1

Vs nproc

nproc does respect the affinity by default and:

taskset -c 0 nproc

outputs:

1

and man nproc makes that quite explicit:

print the number of processing units available

Therefore, len(os.sched_getaffinity(0)) behaves like nproc by default.

nproc has the --all flag for the less common case that you want to get the physical CPU count without considering taskset:

taskset -c 0 nproc --all

os.cpu_count documentation

The documentation of os.cpu_count also briefly mentions this https://docs.python.org/3.8/library/os.html#os.cpu_count

This number is not equivalent to the number of CPUs the current process can use. The number of usable CPUs can be obtained with len(os.sched_getaffinity(0))

The same comment is also copied on the documentation of multiprocessing.cpu_count: https://docs.python.org/3/library/multiprocessing.html#multiprocessing.cpu_count

From the 3.8 source under Lib/multiprocessing/context.py we also see that multiprocessing.cpu_count just forwards to os.cpu_count, except that the multiprocessing one throws an exception instead of returning None if os.cpu_count fails:

    def cpu_count(self):
        '''Returns the number of CPUs in the system'''
        num = os.cpu_count()
        if num is None:
            raise NotImplementedError('cannot determine number of cpus')
        else:
            return num

3.8 availability: systems with a native sched_getaffinity function

The only downside of this os.sched_getaffinity is that this appears to be UNIX only as of Python 3.8.

cpython 3.8 seems to just try to compile a small C hello world with a sched_setaffinity function call during configuration time, and if not present HAVE_SCHED_SETAFFINITY is not set and the function will likely be missing:

psutil.Process().cpu_affinity(): third-party version with a Windows port

The third-party psutil package (pip install psutil) had been mentioned at: https://stackoverflow.com/a/14840102/895245 but not the cpu_affinity function: https://psutil.readthedocs.io/en/latest/#psutil.Process.cpu_affinity

Usage:

import psutil
print(len(psutil.Process().cpu_affinity()))

This function does the same as the standard library os.sched_getaffinity on Linux, but they have also implemented it for Windows by making a call to the GetProcessAffinityMask Windows API function:

So in other words: those Windows users have to stop being lazy and send a patch to the upstream stdlib :-)

Tested in Ubuntu 16.04, Python 3.5.2.

Git undo local branch delete

If you just deleted the branch, you will see something like this in your terminal:

Deleted branch branch_name(was e562d13)
  • where e562d13 is a unique ID (a.k.a. the "SHA" or "hash"), with this you can restore the deleted branch.

To restore the branch, use:

git checkout -b <branch_name> <sha>

for example:

git checkout -b branch_name e562d13 

Tkinter scrollbar for frame

"Am i doing it right?Is there better/smarter way to achieve the output this code gave me?"

Generally speaking, yes, you're doing it right. Tkinter has no native scrollable container other than the canvas. As you can see, it's really not that difficult to set up. As your example shows, it only takes 5 or 6 lines of code to make it work -- depending on how you count lines.

"Why must i use grid method?(i tried place method, but none of the labels appear on the canvas?)"

You ask about why you must use grid. There is no requirement to use grid. Place, grid and pack can all be used. It's simply that some are more naturally suited to particular types of problems. In this case it looks like you're creating an actual grid -- rows and columns of labels -- so grid is the natural choice.

"What so special about using anchor='nw' when creating window on canvas?"

The anchor tells you what part of the window is positioned at the coordinates you give. By default, the center of the window will be placed at the coordinate. In the case of your code above, you want the upper left ("northwest") corner to be at the coordinate.

Bind class toggle to window scroll event

Thanks to Flek for answering my question in his comment:

http://jsfiddle.net/eTTZj/30/

<div ng-app="myApp" scroll id="page" ng-class="{min:boolChangeClass}">

    <header></header>
    <section></section>

</div>

app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
             if (this.pageYOffset >= 100) {
                 scope.boolChangeClass = true;
             } else {
                 scope.boolChangeClass = false;
             }
            scope.$apply();
        });
    };
});

Fatal error: Cannot use object of type stdClass as array in

Controller (Example: User.php)

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Users extends CI_controller
{

    // Table
    protected  $table = 'users';

    function index()
    {
        $data['users'] = $this->model->ra_object($this->table);
        $this->load->view('users_list', $data);
    }
}

View (Example: users_list.php)

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Surname</th>
        </tr>
    </thead>

    <tbody>
        <?php foreach($users as $user) : ?>
            <tr>
            <td><?php echo $user->name; ?></td>
            <td><?php echo $user->surname; ?></th>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>
<!-- // User table -->

WAMP 403 Forbidden message on Windows 7

make sure that, the name of the file in the directory c:/wamp/apps/phpmyadmin3.1.3.1/, match the name (or version) in the phpMyAdmin.conf (Alias /phpmyadmin "c:/wamp/apps/phpmyadmin3.1.3.1/" )

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

PostgreSQL: insert from another table

Just supply literal values in the SELECT:

INSERT INTO TABLE1 (id, col_1, col_2, col_3)
SELECT id, 'data1', 'data2', 'data3'
FROM TABLE2
WHERE col_a = 'something';

A select list can contain any value expression:

But the expressions in the select list do not have to reference any columns in the table expression of the FROM clause; they can be constant arithmetic expressions, for instance.

And a string literal is certainly a value expression.

Problems with entering Git commit message with Vim

Typically, git commit brings up an interactive editor (on Linux, and possibly Cygwin, determined by the contents of your $EDITOR environment variable) for you to edit your commit message in. When you save and exit, the commit completes.

You should make sure that the changes you are trying to commit have been added to the Git index; this determines what is committed. See http://gitref.org/basic/ for details on this.

Iterating through directories with Python

From python >= 3.5 onward, you can use **, glob.iglob(path/**, recursive=True) and it seems the most pythonic solution, i.e.:

import glob, os

for filename in glob.iglob('/pardadox-music/**', recursive=True):
    if os.path.isfile(filename): # filter dirs
        print(filename)

Output:

/pardadox-music/modules/her1.mod
/pardadox-music/modules/her2.mod
...

Notes:
1 - glob.iglob

glob.iglob(pathname, recursive=False)

Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

2 - If recursive is True, the pattern '**' will match any files and zero or more directories and subdirectories.

3 - If the directory contains files starting with . they won’t be matched by default. For example, consider a directory containing card.gif and .card.gif:

>>> import glob
>>> glob.glob('*.gif') ['card.gif'] 
>>> glob.glob('.c*')['.card.gif']

4 - You can also use rglob(pattern), which is the same as calling glob() with **/ added in front of the given relative pattern.

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

For nodejs use the below code

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

How to list files using dos commands?

Try dir /b, for bare format.

dir /? will show you documentation of what you can do with the dir command. Here is the output from my Windows 7 machine:

C:\>dir /?
Displays a list of files and subdirectories in a directory.

DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

  [drive:][path][filename]
              Specifies drive, directory, and/or files to list.

  /A          Displays files with specified attributes.
  attributes   D  Directories                R  Read-only files
               H  Hidden files               A  Files ready for archiving
               S  System files               I  Not content indexed files
               L  Reparse Points             -  Prefix meaning not
  /B          Uses bare format (no heading information or summary).
  /C          Display the thousand separator in file sizes.  This is the
              default.  Use /-C to disable display of separator.
  /D          Same as wide but files are list sorted by column.
  /L          Uses lowercase.
  /N          New long list format where filenames are on the far right.
  /O          List by files in sorted order.
  sortorder    N  By name (alphabetic)       S  By size (smallest first)
               E  By extension (alphabetic)  D  By date/time (oldest first)
               G  Group directories first    -  Prefix to reverse order
  /P          Pauses after each screenful of information.
  /Q          Display the owner of the file.
  /R          Display alternate data streams of the file.
  /S          Displays files in specified directory and all subdirectories.
  /T          Controls which time field displayed or used for sorting
  timefield   C  Creation
              A  Last Access
              W  Last Written
  /W          Uses wide list format.
  /X          This displays the short names generated for non-8dot3 file
              names.  The format is that of /N with the short name inserted
              before the long name. If no short name is present, blanks are
              displayed in its place.
  /4          Displays four-digit years

Switches may be preset in the DIRCMD environment variable.  Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.

Best JavaScript compressor

I recently released UglifyJS, a JavaScript compressor which is written in JavaScript (runs on the NodeJS Node.js platform, but it can be easily modified to run on any JavaScript engine, since it doesn't need any Node.js internals). It's a lot faster than both YUI Compressor and Google Closure, it compresses better than YUI on all scripts I tested it on, and it's safer than Closure (knows to deal with "eval" or "with").

Other than whitespace removal, UglifyJS also does the following:

  • changes local variable names (usually to single characters)
  • joins consecutive var declarations
  • avoids inserting any unneeded brackets, parens and semicolons
  • optimizes IFs (removes "else" when it detects that it's not needed, transforms IFs into the &&, || or ?/: operators when possible, etc.).
  • transforms foo["bar"] into foo.bar where possible
  • removes quotes from keys in object literals, where possible
  • resolves simple expressions when this leads to smaller code (1+3*4 ==> 13)

PS: Oh, it can "beautify" as well. ;-)

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

I had the same problem as OP, and the accepted answer did not work for me. In the comments of the accepted answer, @Rathish posted a solution which worked for me, I wanted to call attention to it.

Here's the link:

https://www.rathishkumar.in/2018/10/Error-1396-HY000-Operation-CREATE-DROP-USER-failed-for-user-host.html

Rathish's solution is to revoke access for all users:

REVOKE ALL ON *.* FROM 'user'@'host';
DROP USER 'user'@'host';
FLUSH PRIVILEGES;

And he also helpfully points out that you can query the following tables by selecting "user" and "host" to determine whether you have a vestigial user left-over from a previous operation:

mysql.user: User accounts, global privileges, and other non-privilege columns
mysql.db: Database-level privileges
mysql.tables_priv: Table-level privileges
mysql.columns_priv: Column-level privileges
mysql.procs_priv: Stored procedure and function privileges
mysql.proxies_priv: Proxy-user privilege

Thank you!

How to get the current date and time of your timezone in Java?

Date in 24 hrs format

Output:14/02/2020 19:56:49 PM

 Date date = new Date();
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss aa");
 dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
 System.out.println("date is: "+dateFormat.format(date));

Date in 12 hrs format

Output:14/02/2020 07:57:11 PM

 Date date = new Date();`enter code here`
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
 dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
 System.out.println("date is: "+dateFormat.format(date));

Android Studio: Module won't show up in "Edit Configuration"

Add your module in your applications .iml file like:

orderEntry type="module" module-name="yourmoudlename" exported="" 

It works for me.

Setting POST variable without using form

You can do it using jQuery. Example:

<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>

<script>
    $.ajax({
        url : "next.php",
        type: "POST",
        data : "name=Denniss",
        success: function(data)
        {
            //data - response from server
            $('#response_div').html(data);
        }
    });
</script>

Check if ADODB connection is open

ADO Recordset has .State property, you can check if its value is adStateClosed or adStateOpen

If Not (rs Is Nothing) Then
  If (rs.State And adStateOpen) = adStateOpen Then rs.Close
  Set rs = Nothing
End If

MSDN about State property

Edit; The reason not to check .State against 1 or 0 is because even if it works 99.99% of the time, it is still possible to have other flags set which will cause the If statement fail the adStateOpen check.

Edit2:

For Late binding without the ActiveX Data Objects referenced, you have few options. Use the value of adStateOpen constant from ObjectStateEnum

If Not (rs Is Nothing) Then
  If (rs.State And 1) = 1 Then rs.Close
  Set rs = Nothing
End If

Or you can define the constant yourself to make your code more readable (defining them all for a good example.)

Const adStateClosed As Long = 0 'Indicates that the object is closed.
Const adStateOpen As Long = 1 'Indicates that the object is open.
Const adStateConnecting As Long = 2 'Indicates that the object is connecting.
Const adStateExecuting As Long = 4 'Indicates that the object is executing a command.
Const adStateFetching As Long = 8 'Indicates that the rows of the object are being retrieved.    

[...]

If Not (rs Is Nothing) Then

    ' ex. If (0001 And 0001) = 0001 (only open flag) -> true
    ' ex. If (1001 And 0001) = 0001 (open and retrieve) -> true
    '    This second example means it is open, but its value is not 1
    '    and If rs.State = 1 -> false, even though it is open
    If (rs.State And adStateOpen) = adStateOpen Then 
        rs.Close
    End If

    Set rs = Nothing
End If

Laravel Eloquent where field is X or null

Using coalesce() converts null to 0:

$query = Model::where('field1', 1)
    ->whereNull('field2')
    ->where(DB::raw('COALESCE(datefield_at,0)'), '<', $date)
;

PHP FPM - check if running

Assuming you are on Linux, check if php-fpm is running by searching through the process list:

ps aux | grep php-fpm

If running over IP (as opposed to over Unix socket) then you can also check for the port:

netstat -an | grep :9000

Or using nmap:

nmap localhost -p 9000

Lastly, I've read that you can request the status, but in my experience this has proven unreliable:

/etc/init.d/php5-fpm status

How do I see which checkbox is checked?

If the checkbox is checked, then the checkbox's value will be passed. Otherwise, the field is not passed in the HTTP post.

if (isset($_POST['mycheckbox'])) {
    echo "checked!";
}

Get List of connected USB Devices

This is a much simpler example for people only looking for removable usb drives.

using System.IO;

foreach (DriveInfo drive in DriveInfo.GetDrives())
{
    if (drive.DriveType == DriveType.Removable)
    {
        Console.WriteLine(string.Format("({0}) {1}", drive.Name.Replace("\\",""), drive.VolumeLabel));
    }
}

jquery: animate scrollLeft

First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate

$('.swipeRight').click(function()
{

    $('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});

$('.swipeLeft').click(function()
{
    $('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});

The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data.

Source: http://php.net/manual/en/wrappers.php.php.

Best practice to return errors in ASP.NET Web API

Use the built in "InternalServerError" method (available in ApiController):

return InternalServerError();
//or...
return InternalServerError(new YourException("your message"));

Playing Sound In Hidden Tag

That's how I achieved it, which is not visible (HORRIBLE SOUND....)

<!-- horrible is your mp3 file name any other supported format.-->
<audio controls autoplay hidden="" src="horrible.mp3" type ="audio/mp3"">your browser does not support Html5</audio>

How to display a list inline using Twitter's Bootstrap

According to the Bootstrap documentation, you need to add the class 'inline' to your list; like this:

<ul class="inline">
    <li>Item one</li>
    <li>Item two</li>
    <li>Item three</li>
</ul>

However, this does not work as there seems to be some CSS missing in the Bootstrap CSS file referring to the class 'inline'. So additionally, add the following lines to your CSS file to make it work:

ul.inline > li, ol.inline > li {
    display: inline-block;
    padding-right: 5px;
    padding-left: 5px;
}

Gson: How to exclude specific fields from Serialization without annotations

I have Kotlin version

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
internal annotation class JsonSkip

class SkipFieldsStrategy : ExclusionStrategy {

    override fun shouldSkipClass(clazz: Class<*>): Boolean {
        return false
    }

    override fun shouldSkipField(f: FieldAttributes): Boolean {
        return f.getAnnotation(JsonSkip::class.java) != null
    }
}

and how You can add this to Retrofit GSONConverterFactory:

val gson = GsonBuilder()
                .setExclusionStrategies(SkipFieldsStrategy())
                //.serializeNulls()
                //.setDateFormat(DateFormat.LONG)
                //.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                //.setPrettyPrinting()
                //.registerTypeAdapter(Id.class, IdTypeAdapter())
                .create()
        return GsonConverterFactory.create(gson)

How to write a cron that will run a script every day at midnight?

Put this sentence in a crontab file: 0 0 * * * /usr/local/bin/python /opt/ByAccount.py > /var/log/cron.log 2>&1

Find the number of columns in a table

db2 'describe table "SCHEMA_NAME"."TBL_NAME"'

Replace string in text file using PHP

Does this work:

$msgid = $_GET['msgid'];

$oldMessage = '';

$deletedFormat = '';

//read the entire string
$str=file_get_contents('msghistory.txt');

//replace something in the file string - this is a VERY simple example
$str=str_replace($oldMessage, $deletedFormat,$str);

//write the entire string
file_put_contents('msghistory.txt', $str);

Pass C# ASP.NET array to Javascript array

Simple

The array of integers is quite simple to pass. However this solution works for more complex data as well. In your model:

public int[] Numbers => new int[5];

In your view:

numbers = @(new HtmlString(JsonSerializer.Serialize(Model.Numbers)))

Optional

A tip for passing strings. You may want JSON encoder to not escape some symbols in your strings. In this example I want raw unescaped cyrillic letters. In your view:

strings = @(
new HtmlString(
    JsonSerializer.Serialize(Model.Strings, new JsonSerializerOptions
    {
        Encoder = JavaScriptEncoder.Create(
            UnicodeRanges.BasicLatin,
            UnicodeRanges.Cyrillic)
    })))

How to compare two tables column by column in oracle

select *
from 
(
( select * from TableInSchema1
  minus 
  select * from TableInSchema2)
union all
( select * from TableInSchema2
  minus
  select * from TableInSchema1)
)

should do the trick if you want to solve this with a query

How to center an element in the middle of the browser window?

To do this you need to know the size of the element you are centering. Any measurement will do (i.e. px, em, percent), but it has to have a fixed size.

The css will look as follows:

 // Replace X and Y with a number and u with a unit. do calculations
 // and remove parens
.centered_div {
   width: Xu;
   height: Yu;
   position: absolute;
   top: 50%;
   left: 50%;
   margin-left: -(X/2)u;
   margin-top: -(Y/2)u;
}

Edit: This centers in the viewport. You can only center in the browser window using JavaScript. But that might be good enough anyway, since you probably want to display a popup/modal box?

Simplest way to serve static data from outside the application server in a Java web application

Read the InputStream of a file and write it to ServletOutputStream for sending binary data to the client.

  • Local file You can read a file directly using FileInputStream('path/image.png').
  • Mongo DataBase file's you can get InputStream using GridFS.
@WebServlet("/files/URLStream")
public class URLStream extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public URLStream() {
        super();
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        File source = new File("D:\\SVN_Commit.PNG");
        long start = System.nanoTime();

        InputStream image = new FileInputStream(source);

        /*String fileID = request.getParameter("id");
        System.out.println("Requested File ID : "+fileID);
        // Mongo DB GridFS - https://stackoverflow.com/a/33544285/5081877
        image = outputImageFile.getInputStream();*/

        if( image != null ) {
            BufferedInputStream bin = null;
            BufferedOutputStream bout = null;
            ServletOutputStream sos = response.getOutputStream();
            try {
                bin = new BufferedInputStream( image );
                bout = new BufferedOutputStream( sos );
                int ch =0; ;
                while((ch=bin.read())!=-1) {
                    bout.write(ch);
                }
            } finally {
                bin.close();
                image.close();
                bout.close();
                sos.close();
            }

        } else {
            PrintWriter writer = response.getWriter();
            writer.append("Something went wrong with your request.");
            System.out.println("Image not available.");
        }
        System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start));
    }
}

Result the URL directly to the src attibute.

<img src='http://172.0.0.1:8080/ServletApp/files/URLStream?id=5a575be200c117cc2500003b' alt="mongodb File"/>
<img src='http://172.0.0.1:8080/ServletApp/files/URLStream' alt="local file"/>

<video controls="controls" src="http://172.0.0.1:8080/ServletApp/files/URLStream"></video>

"This SqlTransaction has completed; it is no longer usable."... configuration error?

I have recently ran across similar situation. To debug in any VS IDE version, open exceptions from Debug (Ctrl + D, E) - check all checkboxes against the column "Thrown", and run the application in debug mode. I have realized that one of the tables was not imported properly in the new database, so internal Sql Exception was killing the connection, thus results into this error.

Gist of the story is, If Previously working code returns this error on a new database, this could be database schema missing issue, realize by above debugging tip,

Hope It Helps, HydTechie

Print series of prime numbers in python

break ends the loop that it is currently in. So, you are only ever checking if it divisible by 2, giving you all odd numbers.

for num in range(2,101):
    for i in range(2,num):
        if (num%i==0):
            break
    else:
        print(num)

that being said, there are much better ways to find primes in python than this.

for num in range(2,101):
    if is_prime(num):
        print(num)

def is_prime(n):
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

How to prevent Screen Capture in Android

Just add this line:

getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);

Before your setContentView() method.

Add items to comboBox in WPF

Use this

string[] str = new string[] {"Foo", "Bar"};

myComboBox.ItemsSource = str;
myComboBox.SelectedIndex = 0;

OR

foreach (string s in str)
    myComboBox.Items.Add(s);

myComboBox.SelectedIndex = 0;      

How to jump to top of browser page

You can set the scrollTop, like this:

$('html,body').scrollTop(0);

Or if you want a little animation instead of a snap to the top:

$('html, body').animate({ scrollTop: 0 }, 'fast');

Nested Recycler view height doesn't wrap its content

Simply wrap the content using RecyclerView with the Grid Layout

Image: Recycler as GridView layout

Just use the GridLayoutManager like this:

RecyclerView.LayoutManager mRecyclerGrid=new GridLayoutManager(this,3,LinearLayoutManager.VERTICAL,false);
mRecyclerView.setLayoutManager(mRecyclerGrid);

You can set how many items should appear on a row (replace the 3).

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

Django Reverse with arguments '()' and keyword arguments '{}' not found

You have to specify project_id:

reverse('edit_project', kwargs={'project_id':4})

Doc here

How to compare files from two different branches?

More modern syntax:

git diff ..master path/to/file

The double-dot prefix means "from the current working directory to". You can also say:

  • master.., i.e. the reverse of above. This is the same as master.
  • mybranch..master, explicitly referencing a state other than the current working tree.
  • v2.0.1..master, i.e. referencing a tag.
  • [refspec]..[refspec], basically anything identifiable as a code state to git.

View HTTP headers in Google Chrome?

I loved the FireFox Header Spy extension so much that i built a HTTP Spy extension for Chrome. I used to use the developer tools too for debugging headers, but now my life is so much better.

Here is a Chrome extension that allows you to view request-, response headers and cookies without any extra clicks right after the page is loaded.

It also handles redirects. It comes with an unobtrusive micro-mode that only shows a hand picked selection of response headers and a normal mode that shows all the information.

https://chrome.google.com/webstore/detail/http-spy/agnoocojkneiphkobpcfoaenhpjnmifb

Enjoy!

Vertically aligning a checkbox

<div>
    <input type="checkbox">
    <img src="/image.png" />
</div>
input[type="checkbox"]
{
    margin-top: -50%;
    vertical-align: middle;
}

How to sort by Date with DataTables jquery plugin?

Date Sort - with a hidden element

Convert the date to the format YYYYMMDD and prepend to the actual value (MM/DD/YYYY) in the <td>, wrap it in an element, set style display:none; to the elements. Now the date sort will work as a normal sort. The same can be applied to date-time sort.

HTML

<table id="data-table">
   <tr>
     <td><span>YYYYMMDD</span>MM/DD/YYYY</td>
   </tr>
</table>

CSS

#data-table span {
    display:none; 
}

Create an array of integers property in Objective-C

This should work:

@interface MyClass
{
    int _doubleDigits[10]; 
}

@property(readonly) int *doubleDigits;

@end

@implementation MyClass

- (int *)doubleDigits
{
    return _doubleDigits;
}

@end

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

Try this (it's VB-Code :-):

Try

Catch exp As WebException
  Dim sResponse As String = New StreamReader(exp.Response.GetResponseStream()).ReadToEnd
End Try

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

This doesn't necessarily maximize your window, but it does resize your window in proportion to the size of the figure:

from matplotlib import pyplot as plt
F = gcf()
Size = F.get_size_inches()
F.set_size_inches(Size[0]*2, Size[1]*2, forward=True)#Set forward to True to resize window along with plot in figure.
plt.show() #or plt.imshow(z_array) if using an animation, where z_array is a matrix or numpy array

This might also help: http://matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html

Convert Pixels to Points

Height lines converted into points and pixel (my own formula). Here is an example with a manual entry of 213.67 points in the Row Height field:

213.67  Manual Entry    
  0.45  Add 0.45    
214.12  Subtotal    
213.75  Round to a multiple of 0.75 
213.00  Subtract 0.75 provides manual entry converted by Excel  
284.00  Divide by 0.75 gives the number of pixels of height

Here the manual entry of 213.67 points gives 284 pixels.
Here the manual entry of 213.68 points gives 285 pixels.

(Why 0.45? I do not know but it works.)

CodeIgniter Active Record not equal

According to the manual this should work:

Custom key/value method:

You can include an operator in the first parameter in order to control the comparison:

$this->db->where('name !=', $name);
$this->db->where('id <', $id);
Produces: WHERE name != 'Joe' AND id < 45

Search for $this->db->where(); and look at item #2.

How do I reset the scale/zoom of a web app on an orientation change on the iPhone?

I've been using this function in my project.

function changeViewPort(key, val) {
    var reg = new RegExp(key, "i"), oldval = document.querySelector('meta[name="viewport"]').content;
    var newval = reg.test(oldval) ? oldval.split(/,\s*/).map(function(v){ return reg.test(v) ? key+"="+val : v; }).join(", ") : oldval+= ", "+key+"="+val ;
    document.querySelector('meta[name="viewport"]').content = newval;
}

so just addEventListener:

if( /iPad|iPhone|iPod|Android/i.test(navigator.userAgent) ){
    window.addEventListener("orientationchange", function() { 
        changeViewPort("maximum-scale", 1);
        changeViewPort("maximum-scale", 10);
    }
}

How can I easily convert DataReader to List<T>?

I know this question is old, and already answered, but...

Since SqlDataReader already implements IEnumerable, why is there a need to create a loop over the records?

I've been using the method below without any issues, nor without any performance issues: So far I have tested with IList, List(Of T), IEnumerable, IEnumerable(Of T), IQueryable, and IQueryable(Of T)

Imports System.Data.SqlClient
Imports System.Data
Imports System.Threading.Tasks

Public Class DataAccess
Implements IDisposable

#Region "   Properties  "

''' <summary>
''' Set the Query Type
''' </summary>
''' <value></value>
''' <remarks></remarks>
Public WriteOnly Property QueryType() As CmdType
    Set(ByVal value As CmdType)
        _QT = value
    End Set
End Property
Private _QT As CmdType

''' <summary>
''' Set the query to run
''' </summary>
''' <value></value>
''' <remarks></remarks>
Public WriteOnly Property Query() As String
    Set(ByVal value As String)
        _Qry = value
    End Set
End Property
Private _Qry As String

''' <summary>
''' Set the parameter names
''' </summary>
''' <value></value>
''' <remarks></remarks>
Public WriteOnly Property ParameterNames() As Object
    Set(ByVal value As Object)
        _PNs = value
    End Set
End Property
Private _PNs As Object

''' <summary>
''' Set the parameter values
''' </summary>
''' <value></value>
''' <remarks></remarks>
Public WriteOnly Property ParameterValues() As Object
    Set(ByVal value As Object)
        _PVs = value
    End Set
End Property
Private _PVs As Object

''' <summary>
''' Set the parameter data type
''' </summary>
''' <value></value>
''' <remarks></remarks>
Public WriteOnly Property ParameterDataTypes() As DataType()
    Set(ByVal value As DataType())
        _DTs = value
    End Set
End Property
Private _DTs As DataType()

''' <summary>
''' Check if there are parameters, before setting them
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Private ReadOnly Property AreParams() As Boolean
    Get
        If (IsArray(_PVs) And IsArray(_PNs)) Then
            If (_PVs.GetUpperBound(0) = _PNs.GetUpperBound(0)) Then
                Return True
            Else
                Return False
            End If
        Else
            Return False
        End If
    End Get
End Property

''' <summary>
''' Set our dynamic connection string
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Private ReadOnly Property _ConnString() As String
    Get
        If System.Diagnostics.Debugger.IsAttached OrElse My.Settings.AttachToBeta OrElse Not (Common.CheckPaid) Then
            Return My.Settings.DevConnString
        Else
            Return My.Settings.TurboKitsv2ConnectionString
        End If
    End Get
End Property

Private _Rdr As SqlDataReader
Private _Conn As SqlConnection
Private _Cmd As SqlCommand

#End Region

#Region "   Methods "

''' <summary>
''' Fire us up!
''' </summary>
''' <remarks></remarks>
Public Sub New()
    Parallel.Invoke(Sub()
                        _Conn = New SqlConnection(_ConnString)
                    End Sub,
                    Sub()
                        _Cmd = New SqlCommand
                    End Sub)
End Sub

''' <summary>
''' Get our results
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function GetResults() As SqlDataReader
    Try
        Parallel.Invoke(Sub()
                            If AreParams Then
                                PrepareParams(_Cmd)
                            End If
                            _Cmd.Connection = _Conn
                            _Cmd.CommandType = _QT
                            _Cmd.CommandText = _Qry
                            _Cmd.Connection.Open()
                            _Rdr = _Cmd.ExecuteReader(CommandBehavior.CloseConnection)
                        End Sub)
        If _Rdr.HasRows Then
            Return _Rdr
        Else
            Return Nothing
        End If
    Catch sEx As SqlException
        Return Nothing
    Catch ex As Exception
        Return Nothing
    End Try
End Function

''' <summary>
''' Prepare our parameters
''' </summary>
''' <param name="objCmd"></param>
''' <remarks></remarks>
Private Sub PrepareParams(ByVal objCmd As Object)
    Try
        Dim _DataSize As Long
        Dim _PCt As Integer = _PVs.GetUpperBound(0)

        For i As Long = 0 To _PCt
            If IsArray(_DTs) Then
                Select Case _DTs(i)
                    Case 0, 33, 6, 9, 13, 19
                        _DataSize = 8
                    Case 1, 3, 7, 10, 12, 21, 22, 23, 25
                        _DataSize = Len(_PVs(i))
                    Case 2, 20
                        _DataSize = 1
                    Case 5
                        _DataSize = 17
                    Case 8, 17, 15
                        _DataSize = 4
                    Case 14
                        _DataSize = 16
                    Case 31
                        _DataSize = 3
                    Case 32
                        _DataSize = 5
                    Case 16
                        _DataSize = 2
                    Case 15
                End Select
                objCmd.Parameters.Add(_PNs(i), _DTs(i), _DataSize).Value = _PVs(i)
            Else
                objCmd.Parameters.AddWithValue(_PNs(i), _PVs(i))
            End If
        Next
    Catch ex As Exception
    End Try
End Sub

#End Region

#Region "IDisposable Support"

Private disposedValue As Boolean ' To detect redundant calls

' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
    If Not Me.disposedValue Then
        If disposing Then
        End If
        Try
            Erase _PNs : Erase _PVs : Erase _DTs
            _Qry = String.Empty
            _Rdr.Close()
            _Rdr.Dispose()
            _Cmd.Parameters.Clear()
            _Cmd.Connection.Close()
            _Conn.Close()
            _Cmd.Dispose()
            _Conn.Dispose()
        Catch ex As Exception

        End Try
    End If
    Me.disposedValue = True
End Sub

' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
Protected Overrides Sub Finalize()
    ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
    Dispose(False)
    MyBase.Finalize()
End Sub

' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
    ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
    Dispose(True)
    GC.SuppressFinalize(Me)
End Sub

#End Region

End Class

Strong Typing Class

Public Class OrderDCTyping
    Public Property OrderID As Long = 0
    Public Property OrderTrackingNumber As String = String.Empty
    Public Property OrderShipped As Boolean = False
    Public Property OrderShippedOn As Date = Nothing
    Public Property OrderPaid As Boolean = False
    Public Property OrderPaidOn As Date = Nothing
    Public Property TransactionID As String
End Class

Usage

Public Function GetCurrentOrders() As IEnumerable(Of OrderDCTyping)
    Try
        Using db As New DataAccess
            With db
                .QueryType = CmdType.StoredProcedure
                .Query = "[Desktop].[CurrentOrders]"
                Using _Results = .GetResults()
                    If _Results IsNot Nothing Then
                        _Qry = (From row In _Results.Cast(Of DbDataRecord)()
                                    Select New OrderDCTyping() With {
                                        .OrderID = Common.IsNull(Of Long)(row, 0, 0),
                                        .OrderTrackingNumber = Common.IsNull(Of String)(row, 1, String.Empty),
                                        .OrderShipped = Common.IsNull(Of Boolean)(row, 2, False),
                                        .OrderShippedOn = Common.IsNull(Of Date)(row, 3, Nothing),
                                        .OrderPaid = Common.IsNull(Of Boolean)(row, 4, False),
                                        .OrderPaidOn = Common.IsNull(Of Date)(row, 5, Nothing),
                                        .TransactionID = Common.IsNull(Of String)(row, 6, String.Empty)
                                    }).ToList()
                    Else
                        _Qry = Nothing
                    End If
                End Using
                Return _Qry
            End With
        End Using
    Catch ex As Exception
        Return Nothing
    End Try
End Function

PHP - Redirect and send data via POST

You have to open a socket to the site with fsockopen and simulate a HTTP-Post-Request. Google will show you many snippets how to simulate the request.

Plot multiple columns on the same graph in R

Using tidyverse

df %>% tidyr::gather("id", "value", 1:4) %>% 
  ggplot(., aes(Xax, value))+
  geom_point()+
  geom_smooth(method = "lm", se=FALSE, color="black")+
  facet_wrap(~id)

DATA

df<- read.table(text =c("
A       B       C       G       Xax
0.451   0.333   0.034   0.173   0.22        
0.491   0.270   0.033   0.207   0.34    
0.389   0.249   0.084   0.271   0.54    
0.425   0.819   0.077   0.281   0.34
0.457   0.429   0.053   0.386   0.53    
0.436   0.524   0.049   0.249   0.12    
0.423   0.270   0.093   0.279   0.61    
0.463   0.315   0.019   0.204   0.23"), header = T)

Inserting data into a MySQL table using VB.NET

  • First, You missed this one: sqlCommand.CommandType = CommandType.Text
  • Second, Your MySQL Parameter Declaration is wrong. It should be @ and not ?

try this:

Public Function InsertCar() As Boolean

    Dim iReturn as boolean
    Using SQLConnection As New MySqlConnection(connectionString)
        Using sqlCommand As New MySqlCommand()
            With sqlCommand
                .CommandText = "INSERT INTO members_car (`car_id`, `member_id`, `model`, `color`, `chassis_id`, `plate_number`, `code`) values (@xid,@m_id,@imodel,@icolor,@ch_id,@pt_num,@icode)"
                .Connection = SQLConnection
                .CommandType = CommandType.Text // You missed this line
                .Parameters.AddWithValue("@xid", TextBox20.Text)
                .Parameters.AddWithValue("@m_id", TextBox20.Text)
                .Parameters.AddWithValue("@imodel", TextBox23.Text)
                .Parameters.AddWithValue("@icolor", TextBox24.Text)
                .Parameters.AddWithValue("@ch_id", TextBox22.Text)
                .Parameters.AddWithValue("@pt_num", TextBox21.Text)
                .Parameters.AddWithValue("@icode", ComboBox1.SelectedItem)
            End With
            Try
                SQLConnection.Open()
                sqlCommand.ExecuteNonQuery()
                iReturn = TRUE
            Catch ex As MySqlException
                MsgBox ex.Message.ToString
                iReturn = False
            Finally
                SQLConnection.Close()
            End Try
        End Using
    End Using

   Return iReturn

End Function

Refresh a page using JavaScript or HTML

Here are 535 ways to reload a page using javascript, very cool:

Here are the first 20:

location = location
location = location.href
location = window.location
location = self.location
location = window.location.href
location = self.location.href
location = location['href']
location = window['location']
location = window['location'].href
location = window['location']['href']
location = window.location['href']
location = self['location']
location = self['location'].href
location = self['location']['href']
location = self.location['href']
location.assign(location)
location.replace(location)
window.location.assign(location)
window.location.replace(location)
self.location.assign(location)

and the last 10:

self['location']['replace'](self.location['href'])
location.reload()
location['reload']()
window.location.reload()
window['location'].reload()
window.location['reload']()
window['location']['reload']()
self.location.reload()
self['location'].reload()
self.location['reload']()
self['location']['reload']()

Original Article

Declaring array of objects

You can instantiate an array of "object type" in one line like this (just replace new Object() with your object):

var elements = 1000;
var MyArray = Array.apply(null, Array(elements)).map(function () { return new Object(); });

Unable to access JSON property with "-" dash

For ansible, and using hyphen, this worked for me:

    - name: free-ud-ssd-space-in-percent
      debug:
        var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]

How do I use a Boolean in Python?

Boolean types are defined in documentation:
http://docs.python.org/library/stdtypes.html#boolean-values

Quoted from doc:

Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to cast any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).

They are written as False and True, respectively.

So in java code remove braces, change true to True and you will be ok :)

log4j configuration via JVM argument(s)?

Relative Path is also ok:

java -Dlog4j.configuration=file:".\log4j.properties" -jar com.your-1.0-SNAPSHOT.jar

or

java -Dlog4j.configuration=file:".\log4j.xml" -jar com.your-1.0-SNAPSHOT.jar

phpmailer: Reply using only "Reply To" address

I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:

$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');

Looking at the phpmailer code in more detail this is the offending line:

public function SetFrom($address, $name = '',$auto=1) {
   $address = trim($address);
   $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
   if (!self::ValidateAddress($address)) {
     $this->SetError($this->Lang('invalid_address').': '. $address);
     if ($this->exceptions) {
       throw new phpmailerException($this->Lang('invalid_address').': '.$address);
     }
     echo $this->Lang('invalid_address').': '.$address;
     return false;
   }
   $this->From = $address;
   $this->FromName = $name;
   if ($auto) {
      if (empty($this->ReplyTo)) {
         $this->AddAnAddress('ReplyTo', $address, $name);
      }
      if (empty($this->Sender)) {
         $this->Sender = $address;
      }
   }
   return true;
}

Specifically this line:

if (empty($this->ReplyTo)) {
   $this->AddAnAddress('ReplyTo', $address, $name);
}

Thanks for your help everyone!

How to edit log message already committed in Subversion?

svnadmin setlog /path/to/repository -r revision_number --bypass-hooks message_file.txt

Visual Studio move project to a different folder

I had the same problem. I solved with move the references and in less than 15 minutes, without change the references.

For me the solution was simple:

  1. Move your files where you need.
  2. Delete the folder with name .vs. Must be as not visible folder.
  3. Open the solution file (.sln) using a simple editor like note or notepad++.
  4. Change the reference where your file is, using the following structure: if you put your project in the same folder remove the previous folder or the reference "..\"; if you put in a above folder add the reference "..\" or the name of the folder.
  5. Save the file with the changes.
  6. Open the project file (.csproj) and do the same, remove or add the reference.
  7. Save the changes.
  8. Open the solution file.

Examples:

In solution file (.sln)

  • Original: Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PATH1.UI", "ScannerPDF\PATH1.UI\PATH1.UI.csproj", "{A26438AD-E428-4AE4-8AB8-A5D6933E2D7B}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PATH1.DataService", "ScannerPDF\PATH1.DataService\PATH1.DataService.csproj", "{ED5A561B-3674-4613-ADE5-B13661146E2E}"

    New: Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PATH1.MX.UI", "PATH1.MX.UI\PATH1.UI.csproj", "{A26438AD-E428-4AE4-8AB8-A5D6933E2D7B}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PATH1.DataService", "PATH1.DataService\PATH1.DataService.csproj", "{ED5A561B-3674-4613-ADE5-B13661146E2E}"

In project file:

  • Original:

    New:

    Original reference: ....\lib\RCWF\2018.1.220.40\TelerikCommon.dll

    New reference: ..\lib\RCWF\2018.1.220.40\TelerikCommon.dll

How do I mock a service that returns promise in AngularJS Jasmine unit test?

Honestly.. you are going about this the wrong way by relying on inject to mock a service instead of module. Also, calling inject in a beforeEach is an anti-pattern as it makes mocking difficult on a per test basis.

Here is how I would do this...

module(function ($provide) {
  // By using a decorator we can access $q and stub our method with a promise.
  $provide.decorator('myOtherService', function ($delegate, $q) {

    $delegate.makeRemoteCallReturningPromise = function () {
      var dfd = $q.defer();
      dfd.resolve('some value');
      return dfd.promise;
    };
  });
});

Now when you inject your service it will have a properly mocked method for usage.

How to get javax.comm API?

Oracle Java Communications API Reference - http://www.oracle.com/technetwork/java/index-jsp-141752.html

Official 3.0 Download (Solarix, Linux) - http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-misc-419423.html

Unofficial 2.0 Download (All): http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm

Unofficial 2.0 Download (Windows installer) - http://kishor15389.blogspot.hk/2011/05/how-to-install-java-communications.html

In order to ensure there is no compilation error, place the file on your classpath when compiling (-cp command-line option, or check your IDE documentation).

Console app arguments, how arguments are passed to Main method

How is main called?

When you are using the console application template the code will be compiled requiring a method called Main in the startup object as Main is market as entry point to the application.

By default no startup object is specified in the project propery settings and the Program class will be used by default. You can change this in the project property under the "Build" tab if you wish.

Keep in mind that which ever object you assign to be the startup object must have a method named Main in it.

How are args passed to main method

The accepted format is MyConsoleApp.exe value01 value02 etc...

The application assigns each value after each space into a separate element of the parameter array.

Thus, MyConsoleApp.exe value01 value02 will mean your args paramter has 2 elements:

[0] = "value01"

[1] = "value02"

How you parse the input values and use them is up to you.

Hope this helped.

Additional Reading:

Creating Console Applications (Visual C#)

Command-Line Arguments (C# Programming Guide)

How do I wait for an asynchronously dispatched block to finish?

Very primitive solution to the problem:

void (^nextOperationAfterLongOperationBlock)(void) = ^{

};

[object runSomeLongOperationAndDo:^{
    STAssert…
    nextOperationAfterLongOperationBlock();
}];

Remove new lines from string and replace with one empty space

Many of these solutions didn't work for me. This did the trick though:-

$svgxml = preg_replace("/(*BSR_ANYCRLF)\R/",'',$svgxml);

Here is the reference:- PCRE and New Lines

IsNullOrEmpty with Object

I found that DataGridViewTextBox values and some JSON objects don't equal Null but instead are "{}" values. Comparing them to Null doesn't work but using these do the trick:

if (cell.Value is System.DBNull)

if (cell.Value == System.DBNull.Value)

A good excerpt I found concerning the difference between Null and DBNull:

Do not confuse the notion of null in an object-oriented programming language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.

You can learn more about the DBNull class here.

Convert varchar into datetime in SQL Server

OP wants mmddyy and a plain convert will not work for that:

select convert(datetime,'12312009')

Msg 242, Level 16, State 3, Line 1 
The conversion of a char data type to a datetime data type resulted in 
an out-of-range datetime value

so try this:

DECLARE @Date char(8)
set @Date='12312009'
SELECT CONVERT(datetime,RIGHT(@Date,4)+LEFT(@Date,2)+SUBSTRING(@Date,3,2))

OUTPUT:

-----------------------
2009-12-31 00:00:00.000

(1 row(s) affected)

Write to text file without overwriting in Java

Here is a simple example of how it works, best practice to put a try\catch into it but for basic use this should do the trick. For this you have a string and file path and apply thus to the FileWriter and the BufferedWriter. This will write "Hello World"(Data variable) and then make a new line. each time this is run it will add the Data variable to the next line.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;


String Data = "Hello World";
File file = new File("C:/Users/stuff.txt");
FileWriter fw = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(Data);
bw.newLine();
bw.close();

Array vs. Object efficiency in JavaScript

I had a similar problem that I am facing where I need to store live candlesticks from an event source limited to x items. I could have them stored in an object where the timestamp of each candle would act as the key and the candle itself would act as the value. Another possibility was that I could store it in an array where each item was the candle itself. One problem about live candles is that they keep sending updates on the same timestamp where the latest update holds the most recent data therefore you either update an existing item or add a new one. So here is a nice benchmark that attempts to combine all 3 possibilities. Arrays in the solution below are atleast 4x faster on average. Feel free to play

"use strict";

const EventEmitter = require("events");
let candleEmitter = new EventEmitter();

//Change this to set how fast the setInterval should run
const frequency = 1;

setInterval(() => {
    // Take the current timestamp and round it down to the nearest second
    let time = Math.floor(Date.now() / 1000) * 1000;
    let open = Math.random();
    let high = Math.random();
    let low = Math.random();
    let close = Math.random();
    let baseVolume = Math.random();
    let quoteVolume = Math.random();

    //Clear the console everytime before printing fresh values
    console.clear()

    candleEmitter.emit("candle", {
        symbol: "ABC:DEF",
        time: time,
        open: open,
        high: high,
        low: low,
        close: close,
        baseVolume: baseVolume,
        quoteVolume: quoteVolume
    });



}, frequency)

// Test 1 would involve storing the candle in an object
candleEmitter.on('candle', storeAsObject)

// Test 2 would involve storing the candle in an array
candleEmitter.on('candle', storeAsArray)

//Container for the object version of candles
let objectOhlc = {}

//Container for the array version of candles
let arrayOhlc = {}

//Store a max 30 candles and delete older ones
let limit = 30

function storeAsObject(candle) {

    //measure the start time in nanoseconds
    const hrtime1 = process.hrtime()
    const start = hrtime1[0] * 1e9 + hrtime1[1]

    const { symbol, time } = candle;

    // Create the object structure to store the current symbol
    if (typeof objectOhlc[symbol] === 'undefined') objectOhlc[symbol] = {}

    // The timestamp of the latest candle is used as key with the pair to store this symbol
    objectOhlc[symbol][time] = candle;

    // Remove entries if we exceed the limit
    const keys = Object.keys(objectOhlc[symbol]);
    if (keys.length > limit) {
        for (let i = 0; i < (keys.length - limit); i++) {
            delete objectOhlc[symbol][keys[i]];
        }
    }

    //measure the end time in nano seocnds
    const hrtime2 = process.hrtime()
    const end = hrtime2[0] * 1e9 + hrtime2[1]

    console.log("Storing as objects", end - start, Object.keys(objectOhlc[symbol]).length)
}

function storeAsArray(candle) {

    //measure the start time in nanoseconds
    const hrtime1 = process.hrtime()
    const start = hrtime1[0] * 1e9 + hrtime1[1]

    const { symbol, time } = candle;
    if (typeof arrayOhlc[symbol] === 'undefined') arrayOhlc[symbol] = []

    //Get the bunch of candles currently stored
    const candles = arrayOhlc[symbol];

    //Get the last candle if available
    const lastCandle = candles[candles.length - 1] || {};

    // Add a new entry for the newly arrived candle if it has a different timestamp from the latest one we storeds
    if (time !== lastCandle.time) {
        candles.push(candle);
    }

    //If our newly arrived candle has the same timestamp as the last stored candle, update the last stored candle
    else {
        candles[candles.length - 1] = candle
    }

    if (candles.length > limit) {
        candles.splice(0, candles.length - limit);
    }

    //measure the end time in nano seocnds
    const hrtime2 = process.hrtime()
    const end = hrtime2[0] * 1e9 + hrtime2[1]


    console.log("Storing as array", end - start, arrayOhlc[symbol].length)
}

Conclusion 10 is the limit here

Storing as objects 4183 nanoseconds 10
Storing as array 373 nanoseconds 10

Get program path in VB.NET?

For a console application you can use System.Reflection.Assembly.GetExecutingAssembly().Location as long as the call is made within the code of the console app itself, if you call this from within another dll or plugin this will return the location of that DLL and not the executable.

What is the Git equivalent for revision number?

This is what I did in my makefile based on others solutions. Note not only does this give your code a revision number, it also appends the hash which allows you to recreate the release.

# Set the source control revision similar to subversion to use in 'c'
# files as a define.
# You must build in the master branch otherwise the build branch will
# be prepended to the revision and/or "dirty" appended. This is to
# clearly ID developer builds.
REPO_REVISION_:=$(shell git rev-list HEAD --count)
BUILD_BRANCH:=$(shell git rev-parse --abbrev-ref HEAD)
BUILD_REV_ID:=$(shell git rev-parse HEAD)
BUILD_REV_ID_SHORT:=$(shell git describe --long --tags --dirty --always)
ifeq ($(BUILD_BRANCH), master)
REPO_REVISION:=$(REPO_REVISION_)_g$(BUILD_REV_ID_SHORT)
else
REPO_REVISION:=$(BUILD_BRANCH)_$(REPO_REVISION_)_r$(BUILD_REV_ID_SHORT)
endif
export REPO_REVISION
export BUILD_BRANCH
export BUILD_REV_ID

how to increase the limit for max.print in R

set the function options(max.print=10000) in top of your program. since you want intialize this before it works. It is working for me.

How can I split a text file using PowerShell?

Sounds like a job for the UNIX command split:

split MyBigFile.csv

Just split my 55 GB csv file in 21k chunks in less than 10 minutes.

It's not native to PowerShell though, but comes with, for instance, the git for windows package https://git-scm.com/download/win

How to save CSS changes of Styles panel of Chrome Developer Tools?

UPDATE 2019: As other answers are bit outdated, I'll add updated one here. In latest version there's no need to map the chrome folder to filesystem.

enter image description here

So, suppose I have a web folder containing HTML,CSS,JS files in desktop which i want to be updated when I make changes in chrome:=

1) You'd need a running local server like node etc, alternatively this vscode extension creates the server for you: live server VSCode extension, install it, run the server.

2) load the html page in chrome from running local server.

3) Open devTools->Sources->Filesystem->Add folder to workspace

enter image description here

4) Add the folder which is used in running local server. No additional mapping is required in latest chrome! Ta-da!

More on it Edit Files With Workspaces

Note that the changes made on the styles tab will NOT reflect on the filesystem files.
enter image description here
Instead you need to go to devtools->source->your_folder and then make your changes there and reload the page to see the effect.

OSError: [Errno 8] Exec format error

Have you tried this?

Out = subprocess.Popen('/usr/local/bin/script hostname = actual_server_name -p LONGLIST'.split(), shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 

Edited per the apt comment from @J.F.Sebastian

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

Instead of

return new ResponseEntity<JSONObject>(entities, HttpStatus.OK);

try

return new ResponseEntity<List<JSONObject>>(entities, HttpStatus.OK);

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

you can try writing the command using 'sudo':

sudo mkdir DirName

Comparing two vectors in an if statement

Are they identical?

> identical(A,C)
[1] FALSE

Which elements disagree:

> which(A != C)
[1] 2 4

How to set breakpoints in inline Javascript in Google Chrome?

If you cannot see the "Scripts" tab, make sure you are launching Chrome with the right arguments. I had this problem when I launched Chrome for debugging server-side JavaScript with the argument --remote-shell-port=9222. I have no problem if I launch Chrome with no argument.

CSS table column autowidth

The following will solve your problem:

td.last {
    width: 1px;
    white-space: nowrap;
}

Flexible, Class-Based Solution

And a more flexible solution is creating a .fitwidth class and applying that to any columns you want to ensure their contents are fit on one line:

td.fitwidth {
    width: 1px;
    white-space: nowrap;
}

And then in your HTML:

<tr>
    <td class="fitwidth">ID</td>
    <td>Description</td>
    <td class="fitwidth">Status</td>
    <td>Notes</td>
</tr>

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

I read all answers that said: No, Swift does not work with less than iOS 7. But I said YES, I just created a Swift project that does run in Xcode 5 with 6.0 deployment target.

  • I just create a demo project in Xcode 6 BETA with the Swift programming language selected.
  • Close Xcode 6 beta, and I open this demo project in Xcode 5 with deployment target 6.0
  • And also select simulator 6.1.

Then that project runs well in simulator 6.1. My MacOS X is 10.9.3, so I said yes, that runs in lower than iOS 7. with 10.9.3 Mac OS X.

Here it is a screenshot of the simulator:

Enter image description here

Here is a demo as well

Angularjs $http post file and form data

I had similar problem when had to upload file and send user token info at the same time. transformRequest along with forming FormData helped:

        $http({
            method: 'POST',
            url: '/upload-file',
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            data: {
                email: Utils.getUserInfo().email,
                token: Utils.getUserInfo().token,
                upload: $scope.file
            },
            transformRequest: function (data, headersGetter) {
                var formData = new FormData();
                angular.forEach(data, function (value, key) {
                    formData.append(key, value);
                });

                var headers = headersGetter();
                delete headers['Content-Type'];

                return formData;
            }
        })
        .success(function (data) {

        })
        .error(function (data, status) {

        });

For getting file $scope.file I used custom directive:

app.directive('file', function () {
    return {
        scope: {
            file: '='
        },
        link: function (scope, el, attrs) {
            el.bind('change', function (event) {
                var file = event.target.files[0];
                scope.file = file ? file : undefined;
                scope.$apply();
            });
        }
    };
});

Html:

<input type="file" file="file" required />

How to get changes from another branch

You are almost there :)

All that is left is to

git checkout featurex
git merge our-team

This will merge our-team into featurex.

The above assumes you have already committed/stashed your changes in featurex, if that is not the case you will need to do this first.

Should I use int or Int32

You should not care in most programming languages, unless you need to write very specific mathematical functions, or code optimized for one specific architecture... Just make sure the size of the type is enough for you (use something bigger than an Int if you know you'll need more than 32-bits for example)

Activity has leaked window that was originally added

This is not the answer to the question but it's relevant to the topic.

If the activity has defined an attribute in the Manifest

 android:noHistory="true"

then after executing onPause(), the context of activity is lost. So all the view's using this context might give this error.

jquery $(window).height() is returning the document height

I had the same problem, and using this solved it.

var w = window.innerWidth;
var h = window.innerHeight;

How do I build an import library (.lib) AND a DLL in Visual C++?

OK, so I found the answer from http://binglongx.wordpress.com/2009/01/26/visual-c-does-not-generate-lib-file-for-a-dll-project/ says that this problem was caused by not exporting any symbols and further instructs on how to export symbols to create the lib file. To do so, add the following code to your .h file for your DLL.

#ifdef BARNABY_EXPORTS
#define BARNABY_API __declspec(dllexport)
#else
#define BARNABY_API __declspec(dllimport)
#endif

Where BARNABY_EXPORTS and BARNABY_API are unique definitions for your project. Then, each function you export you simply precede by:

BARNABY_API int add(){
}

This problem could have been prevented either by clicking the Export Symbols box on the new project DLL Wizard or by voting yes for lobotomies for computer programmers.

How is length implemented in Java Arrays?

If you have an array of a known type or is a subclass of Object[] you can cast the array first.

Object array = new ????[n];
Object[] array2 = (Object[]) array;
System.out.println(array2.length);

or

Object array = new char[n];
char[] array2 = (char[]) array;
System.out.println(array2.length);

However if you have no idea what type of array it is you can use Array.getLength(Object);

System.out.println(Array.getLength(new boolean[4]);
System.out.println(Array.getLength(new int[5]);
System.out.println(Array.getLength(new String[6]);

Can you append strings to variables in PHP?

In PHP use .= to append strings, and not +=.

Why does this output 0? [...] Does PHP not like += with strings?

+= is an arithmetic operator to add a number to another number. Using that operator with strings leads to an automatic type conversion. In the OP's case the strings have been converted to integers of the value 0.


More about operators in PHP:

Change User Agent in UIWebView

I faced the same question. I want to add some info to the user-agent, also need to keep the original user-agent of webview. I solved it by using the code below:

    //get the original user-agent of webview
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSLog(@"old agent :%@", oldAgent);

//add my info to the new agent
NSString *newAgent = [oldAgent stringByAppendingString:@" Jiecao/2.4.7 ch_appstore"];
NSLog(@"new agent :%@", newAgent);

//regist the new agent
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

Use it before you instancing webview.

HTTP get with headers using RestTemplate

The RestTemplate getForObject() method does not support setting headers. The solution is to use the exchange() method.

So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use

HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...

HttpEntity entity = new HttpEntity(headers);

ResponseEntity<String> response = restTemplate.exchange(
    url, HttpMethod.GET, entity, String.class, param);

Finally, use response.getBody() to get your result.

This question is similar to this question.

How can I read and manipulate CSV file data in C++?

I found this interesting approach:

CSV to C structure utility

Quote: CSVtoC is a program that takes a CSV or comma-separated values file as input and dumps it as a C structure.

Naturally, you can't make changes to the CSV file, but if you just need in-memory read-only access to the data, it could work.

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

SQL use CASE statement in WHERE IN clause

According to my Scenario, I did "use CASE statement in WHERE IN clause" like following

@AdjType varchar(20) = 'Value', 
@Base varchar(20) = 'Common'
where 
(select CASE WHEN SA.IsPersentage = 0 THEN 'Value' 
       WHEN SA.IsPersentage = 1 THEN 'Presentage' END) Like @AdjType
and (Select CASE WHEN SA.IsDependOnBasicSalary = 0 THEN 'Common' 
        WHEN SA.IsDependOnBasicSalary = 1 THEN 'Basic Salary' END) like @Base

How to check if anonymous object has a method?

typeof myObj.prop2 === 'function'; will let you know if the function is defined.

if(typeof myObj.prop2 === 'function') {
    alert("It's a function");
} else if (typeof myObj.prop2 === 'undefined') {
    alert("It's undefined");
} else {
    alert("It's neither undefined nor a function. It's a " + typeof myObj.prop2);
}

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

Updating a date in Oracle SQL table

This is based on the assumption that you're getting an error about the date format, such as an invalid month value or non-numeric character when numeric expected.

Dates stored in the database do not have formats. When you query the date your client is formatting the date for display, as 4/16/2011. Normally the same date format is used for selecting and updating dates, but in this case they appear to be different - so your client is apparently doing something more complicated that SQL*Plus, for example.

When you try to update it it's using a default date format model. Because of how it's displayed you're assuming that is MM/DD/YYYY, but it seems not to be. You could find out what it is, but it's better not to rely on the default or any implicit format models at all.

Whether that is the problem or not, you should always specify the date model:

UPDATE PASOFDATE SET ASOFDATE = TO_DATE('11/21/2012', 'MM/DD/YYYY');

Since you aren't specifying a time component - all Oracle DATE columns include a time, even if it's midnight - you could also use a date literal:

UPDATE PASOFDATE SET ASOFDATE = DATE '2012-11-21';

You should maybe check that the current value doesn't include a time, though the column name suggests it doesn't.

How Can I Override Style Info from a CSS Class in the Body of a Page?

if you can access the head add <style> /*...some style */ </style> the way Hussein showed you
and the ultra hacky <style> </style> in the html it will work but its ugly. or javascript it the best way if you can use it in you case

How to center images on a web page for all screen sizes

Try something like this...

<div id="wrapper" style="width:100%; text-align:center">
<img id="yourimage"/>
</div>

_csv.Error: field larger than field limit (131072)

.csv field sizes are controlled via [Python 3.Docs]: csv.field_size_limit([new_limit]) (emphasis is mine):

Returns the current maximum field size allowed by the parser. If new_limit is given, this becomes the new limit.

It is set by default to 131072 or 0x20000 (128k), which should be enough for any decent .csv:

>>> import csv
>>>
>>>
>>> limit0 = csv.field_size_limit()
>>> limit0
131072
>>> "0x{0:016X}".format(limit0)
'0x0000000000020000'

However, when dealing with a .csv file (with the correct quoting and delimiter) having (at least) one field longer than this size, the error pops up.
To get rid of the error, the size limit should be increased (to avoid any worries, the maximum possible value is attempted).

Behind the scenes (check [GitHub]: python/cpython - (master) cpython/Modules/_csv.c for implementation details), the variable that holds this value is a C long ([Wikipedia]: C data types), whose size varies depending on CPU architecture and OS (ILP). The classical difference: for a 64bit OS (and Python build), the long type size (in bits) is:

  • Nix: 64
  • Win: 32

When attempting to set it, the new value is checked to be in the long boundaries, that's why in some cases another exception pops up (because sys.maxsize is typically 64bit wide - encountered on Win):

>>> import sys, ctypes as ct
>>>
>>>
>>> sys.platform, sys.maxsize, ct.sizeof(ct.c_void_p) * 8, ct.sizeof(ct.c_long) * 8
('win32', 9223372036854775807, 64, 32)
>>>
>>> csv.field_size_limit(sys.maxsize)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long

To avoid running into this problem, set the (maximum possible) limit (LONG_MAX), using an artifice (thanks to [Python 3.Docs]: ctypes - A foreign function library for Python). It should work on Python 3 and Python 2, on any CPU / OS.

>>> csv.field_size_limit(int(ct.c_ulong(-1).value // 2))
131072
>>> limit1 = csv.field_size_limit()
>>> limit1
2147483647
>>> "0x{0:016X}".format(limit1)
'0x000000007FFFFFFF'

64bit Python on a Nix like OS:

>>> import sys, csv, ctypes as ct
>>>
>>>
>>> sys.platform, sys.maxsize, ct.sizeof(ct.c_void_p) * 8, ct.sizeof(ct.c_long) * 8
('linux', 9223372036854775807, 64, 64)
>>>
>>> csv.field_size_limit()
131072
>>>
>>> csv.field_size_limit(int(ct.c_ulong(-1).value // 2))
131072
>>> limit1 = csv.field_size_limit()
>>> limit1
9223372036854775807
>>> "0x{0:016X}".format(limit1)
'0x7FFFFFFFFFFFFFFF'

For 32bit Python, things should run smoothly without the artifice (as both sys.maxsize and LONG_MAX are 32bit wide).
If this maximum value is still not enough, then the .csv would need manual intervention in order to be processed from Python.

Check the following resources for more details on:

How to pass ArrayList<CustomeObject> from one activity to another?

In First activity:

ArrayList<ContactBean> fileList = new ArrayList<ContactBean>();
Intent intent = new Intent(MainActivity.this, secondActivity.class);
intent.putExtra("FILES_TO_SEND", fileList);
startActivity(intent);

In receiver activity:

ArrayList<ContactBean> filelist =  (ArrayList<ContactBean>)getIntent().getSerializableExtra("FILES_TO_SEND");`

Can you break from a Groovy "each" closure?

You can't break from a Groovy each loop, but you can break from a java "enhanced" for loop.

def a = [1, 2, 3, 4, 5, 6, 7]

for (def i : a) {
    if (i < 2)
        continue
    if (i > 5)
        break
    println i
}

Output:

2
3
4
5

This might not fit for absolutely every situation but it's helped for me :)

How to convert a Title to a URL slug in jQuery?

More powerful slug generation method on pure JavaScript. It's basically support transliteration for all Cyrillic characters and many Umlauts (German, Danish, France, Turkish, Ukrainian and etc.) but can be easily extended.

_x000D_
_x000D_
function makeSlug(str)_x000D_
{_x000D_
  var from="? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? a a ä á à â å c c e e e é è ê æ g g ö ó ø ? ô o ? ? n ? r s ü ß r l d þ h ? i ï í î j k l n n n r š s t u ú û ? ù ü u u ý ÿ ž z z ç ? ?".split(' ');_x000D_
  var to=  "a b v g d e e zh z i y k l m n o p r s t u f h ts ch sh shch # y # e yu ya a a ae a a a a c c e e e e e e e g g oe o o o o o m n n p r s ue ss r l d th h h i i i i j k l n n n r s s t u u u u u u u u y y z z z c ye g".split(' ');_x000D_
 _x000D_
  str = str.toLowerCase();_x000D_
  _x000D_
  // remove simple HTML tags_x000D_
  str = str.replace(/(<[a-z0-9\-]{1,15}[\s]*>)/gi, '');_x000D_
  str = str.replace(/(<\/[a-z0-9\-]{1,15}[\s]*>)/gi, '');_x000D_
  str = str.replace(/(<[a-z0-9\-]{1,15}[\s]*\/>)/gi, '');_x000D_
  _x000D_
  str = str.replace(/^\s+|\s+$/gm,''); // trim spaces_x000D_
  _x000D_
  for(i=0; i<from.length; ++i)_x000D_
    str = str.split(from[i]).join(to[i]);_x000D_
  _x000D_
  // Replace different kind of spaces with dashes_x000D_
  var spaces = [/(&nbsp;|&#160;|&#32;)/gi, /(&mdash;|&ndash;|&#8209;)/gi,_x000D_
     /[(_|=|\\|\,|\.|!)]+/gi, /\s/gi];_x000D_
_x000D_
  for(i=0; i<from.length; ++i)_x000D_
   str = str.replace(spaces[i], '-');_x000D_
  str = str.replace(/-{2,}/g, "-");_x000D_
_x000D_
  // remove special chars like &amp;_x000D_
  str = str.replace(/&[a-z]{2,7};/gi, '');_x000D_
  str = str.replace(/&#[0-9]{1,6};/gi, '');_x000D_
  str = str.replace(/&#x[0-9a-f]{1,6};/gi, '');_x000D_
  _x000D_
  str = str.replace(/[^a-z0-9\-]+/gmi, ""); // remove all other stuff_x000D_
  str = str.replace(/^\-+|\-+$/gm,''); // trim edges_x000D_
  _x000D_
  return str;_x000D_
};_x000D_
_x000D_
_x000D_
document.getElementsByTagName('pre')[0].innerHTML = makeSlug(" <br/> &#x202A;???&amp;???<strong>??_????</strong>?…???????????\r???\n?&ndash;??????&nbsp;??????\t \n?\t??????&#180;?&nbsp;??\\?????&ndash;????????\t????.Danke schön!ich heiße=?áÞÿá-Skånske,København çagatay rí gé tor zöldülésetekrol - . ");
_x000D_
<div>_x000D_
  <pre>Hello world!</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make sure docker's time syncs with that of the host?

This is what worked for me with a Fedora 20 host. I ran a container using:

docker run -v /etc/localtime:/etc/localtime:ro -i -t mattdm/fedora /bin/bash

Initially /etc/localtime was a soft link to /usr/share/zoneinfo/Asia/Kolkata which Indian Standard Time. Executing date inside the container showed me same time as that on the host. I exited from the shell and stopped the container using docker stop <container-id>.

Next, I removed this file and made it link to /usr/share/zoneinfo/Singapore for testing purpose. Host time was set to Singapore time zone. And then did docker start <container-id>. Then accessed its shell again using nsenter and found that time was now set to Singapore time zone.

docker start <container-id>
docker inspect -f {{.State.Pid}} <container-id>
nsenter -m -u -i -n -p -t <PID> /bin/bash

So the key here is to use -v /etc/localtime:/etc/localtime:ro when you run the container first time. I found it on this link.

Hope it helps.

#1292 - Incorrect date value: '0000-00-00'

The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.

For more information read this.

Hope it helps.

How to display activity indicator in middle of the iphone screen?

For Swift 3 you can use the following:

 func setupSpinner(){
    spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height:40))
    spinner.color = UIColor(Colors.Accent)
    self.spinner.center = CGPoint(x:UIScreen.main.bounds.size.width / 2, y:UIScreen.main.bounds.size.height / 2)
    self.view.addSubview(spinner)
    spinner.hidesWhenStopped = true
}

Django optional url parameters

Even simpler is to use:

(?P<project_id>\w+|)

The "(a|b)" means a or b, so in your case it would be one or more word characters (\w+) or nothing.

So it would look like:

url(
    r'^project_config/(?P<product>\w+)/(?P<project_id>\w+|)/$',
    'tool.views.ProjectConfig',
    name='project_config'
),

Where is web.xml in Eclipse Dynamic Web Project

When you open Eclipse you should click File ? New ? Dynamic Web Project, and make sure you checked Generate web.xml, as described above.

If you have already created the project, you should go to the WebContent/WEB-INF folder, open web.xml, and put the following lines:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>Application Name </display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

How to Initialize char array from a string

const char S[] = "ABCD";

This should work. i use this notation only and it works perfectly fine for me. I don't know how you are using.

What is the yield keyword used for in C#?

yield return is used with enumerators. On each call of yield statement, control is returned to the caller but it ensures that the callee's state is maintained. Due to this, when the caller enumerates the next element, it continues execution in the callee method from statement immediately after the yield statement.

Let us try to understand this with an example. In this example, corresponding to each line I have mentioned the order in which execution flows.

static void Main(string[] args)
{
    foreach (int fib in Fibs(6))//1, 5
    {
        Console.WriteLine(fib + " ");//4, 10
    }            
}

static IEnumerable<int> Fibs(int fibCount)
{
    for (int i = 0, prevFib = 0, currFib = 1; i < fibCount; i++)//2
    {
        yield return prevFib;//3, 9
        int newFib = prevFib + currFib;//6
        prevFib = currFib;//7
        currFib = newFib;//8
    }
}

Also, the state is maintained for each enumeration. Suppose, I have another call to Fibs() method then the state will be reset for it.