Programs & Examples On #Linqdatasource

LinqDataSource is a Web Control which enables the use of Language-Integrated Query (LINQ) in an ASP.NET Web page through markup text to retrieve and modify data from a data object.

Check if a key is down?

I scanned the above answers and the proposed keydown/keyup approach works only under special circumstances. If the user alt-tabs away, or uses a key gesture to open a new browser window or tab, then a keydown will be registered, which is fine, because at that point it's impossible to tell if the key is something the web app is monitoring, or is a standard browser or OS shortcut. Coming back to the browser page, it'll still think the key is held, though it was released in the meantime. Or some key is simply kept held, while the user is switching to another tab or application with the mouse, then released outside our page.

Modifier keys (Shift etc.) can be monitored via mousemove etc. assuming that there is at least one mouse interaction expected when tabbing back, which is frequently the case.

For most all other keys (except modifiers, Tab, Delete, but including Space, Enter), monitoring keypress would work for most applications - a key held down will continue to fire. There's some latency in resetting the key though, due to the periodicity of keypress firing. Basically, if keypress doesn't keep firing, then it's possible to rule out most of the keys. This, combined with the modifiers is pretty airtight, though I haven't explored what to do with Tab and Backspace.

I'm sure there's some library out there that abstracts over this DOM weakness, or maybe some DOM standard change took care of it, since it's a rather old question.

MySQL Trigger after update only if row has changed

BUT imagine a large table with changing columns. You have to compare every column and if the database changes you have to adjust the trigger. AND it doesn't "feel" good to compare every row hardcoded :)

Yeah, but that's the way to proceed.

As a side note, it's also good practice to pre-emptively check before updating:

UPDATE foo SET b = 3 WHERE a=3 and b <> 3;

In your example this would make it update (and thus overwrite) two rows instead of three.

Create a new file in git bash

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

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

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

Why does sed not replace all occurrences?

You have to put a g at the end, it stands for "global":

echo dog dog dos | sed -r 's:dog:log:g'
                                     ^

Entity Framework. Delete all rows in table

if

      using(var db = new MyDbContext())
            {
               await db.Database.ExecuteSqlCommandAsync(@"TRUNCATE TABLE MyTable"););
            }

causes

Cannot truncate table 'MyTable' because it is being referenced by a FOREIGN KEY constraint.

I use this :

      using(var db = new MyDbContext())
               {
                   await db.Database.ExecuteSqlCommandAsync(@"DELETE FROM MyTable WHERE ID != -1");
               }

Run react-native on android emulator

On macOs I manage to fix this by adding:

export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools

to ~/.zsh_profile file.

and than type to your terminal

source $HOME/.zsh_profile

The issue was caused by using iTerm2 shell so it's required to edit its own config instead of default $HOME/.bash_profile as described in the official documentation https://reactnative.dev/docs/environment-setup

How to get an Android WakeLock to work?

To achieve the same programmatic you can use following

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

or adding following in layout also will perform the above task

 android:keepScreenOn="true"

The details you can get from following url http://developer.android.com/training/scheduling/wakelock.html

I have used combination of following to wake my screen when keyguard locked and keep my screen on

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

ASP.NET Core 1.0 on IIS error 502.5

Here is what I figured, and this happened recently on Windows 10 after an update was installed. From what I gathered, a Windows Defender update was installed which assumed my "Project.dll"(an asp.net core project) behaved like a virus so it was deleted.

So, one of the first things I suggest you do before you start installing/uninstalling stuffs is to check to confirm your "Project.dll" is where it should be.

Copy it back to the location if it is no longer there.

If you are having difficulty copying the file back add an exclusion to your project folder in windows defender. ( Learn how to do that here. )

This worked for me instantly, and I repeated it across application multiple servers.

Combine two integer arrays

use ArrayUtils.addAll(T[], T...):

import org.apache.commons.lang3.ArrayUtils;

AnyObject[] array1 = ...;
AnyObject[] array2 = ...;
AnyObject[] mergedArray = ArrayUtils.addAll(array1, array2);

Iterate over elements of List and Map using JSTL <c:forEach> tag

Mark, this is already answered in your previous topic. But OK, here it is again:

Suppose ${list} points to a List<Object>, then the following

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

does basically the same as as following in "normal Java":

for (Object item : list) {
    System.out.println(item);
}

If you have a List<Map<K, V>> instead, then the following

<c:forEach items="${list}" var="map">
    <c:forEach items="${map}" var="entry">
        ${entry.key}<br>
        ${entry.value}<br>
    </c:forEach>
</c:forEach>

does basically the same as as following in "normal Java":

for (Map<K, V> map : list) {
    for (Entry<K, V> entry : map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
}

The key and value are here not special methods or so. They are actually getter methods of Map.Entry object (click at the blue Map.Entry link to see the API doc). In EL (Expression Language) you can use the . dot operator to access getter methods using "property name" (the getter method name without the get prefix), all just according the Javabean specification.

That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".

How to redirect on another page and pass parameter in url from table?

Do this :

<script type="text/javascript">
function showDetails(username)
{
   window.location = '/player_detail?username='+username;
}
</script>

<input type="button" name="theButton" value="Detail" onclick="showDetails('username');">

Styling Google Maps InfoWindow

You can modify the whole InfoWindow using jquery alone...

var popup = new google.maps.InfoWindow({
    content:'<p id="hook">Hello World!</p>'
});

Here the <p> element will act as a hook into the actual InfoWindow. Once the domready fires, the element will become active and accessible using javascript/jquery, like $('#hook').parent().parent().parent().parent().

The below code just sets a 2 pixel border around the InfoWindow.

google.maps.event.addListener(popup, 'domready', function() {
    var l = $('#hook').parent().parent().parent().siblings();
    for (var i = 0; i < l.length; i++) {
        if($(l[i]).css('z-index') == 'auto') {
            $(l[i]).css('border-radius', '16px 16px 16px 16px');
            $(l[i]).css('border', '2px solid red');
        }
    }
});

You can do anything like setting a new CSS class or just adding a new element.

Play around with the elements to get what you need...

What is the difference between Scala's case class and class?

To have the ultimate understanding of what is a case class:

let's assume the following case class definition:

case class Foo(foo:String, bar: Int)

and then do the following in the terminal:

$ scalac -print src/main/scala/Foo.scala

Scala 2.12.8 will output:

...
case class Foo extends Object with Product with Serializable {

  <caseaccessor> <paramaccessor> private[this] val foo: String = _;

  <stable> <caseaccessor> <accessor> <paramaccessor> def foo(): String = Foo.this.foo;

  <caseaccessor> <paramaccessor> private[this] val bar: Int = _;

  <stable> <caseaccessor> <accessor> <paramaccessor> def bar(): Int = Foo.this.bar;

  <synthetic> def copy(foo: String, bar: Int): Foo = new Foo(foo, bar);

  <synthetic> def copy$default$1(): String = Foo.this.foo();

  <synthetic> def copy$default$2(): Int = Foo.this.bar();

  override <synthetic> def productPrefix(): String = "Foo";

  <synthetic> def productArity(): Int = 2;

  <synthetic> def productElement(x$1: Int): Object = {
    case <synthetic> val x1: Int = x$1;
        (x1: Int) match {
            case 0 => Foo.this.foo()
            case 1 => scala.Int.box(Foo.this.bar())
            case _ => throw new IndexOutOfBoundsException(scala.Int.box(x$1).toString())
        }
  };

  override <synthetic> def productIterator(): Iterator = scala.runtime.ScalaRunTime.typedProductIterator(Foo.this);

  <synthetic> def canEqual(x$1: Object): Boolean = x$1.$isInstanceOf[Foo]();

  override <synthetic> def hashCode(): Int = {
     <synthetic> var acc: Int = -889275714;
     acc = scala.runtime.Statics.mix(acc, scala.runtime.Statics.anyHash(Foo.this.foo()));
     acc = scala.runtime.Statics.mix(acc, Foo.this.bar());
     scala.runtime.Statics.finalizeHash(acc, 2)
  };

  override <synthetic> def toString(): String = scala.runtime.ScalaRunTime._toString(Foo.this);

  override <synthetic> def equals(x$1: Object): Boolean = Foo.this.eq(x$1).||({
      case <synthetic> val x1: Object = x$1;
        case5(){
          if (x1.$isInstanceOf[Foo]())
            matchEnd4(true)
          else
            case6()
        };
        case6(){
          matchEnd4(false)
        };
        matchEnd4(x: Boolean){
          x
        }
    }.&&({
      <synthetic> val Foo$1: Foo = x$1.$asInstanceOf[Foo]();
      Foo.this.foo().==(Foo$1.foo()).&&(Foo.this.bar().==(Foo$1.bar())).&&(Foo$1.canEqual(Foo.this))
  }));

  def <init>(foo: String, bar: Int): Foo = {
    Foo.this.foo = foo;
    Foo.this.bar = bar;
    Foo.super.<init>();
    Foo.super./*Product*/$init$();
    ()
  }
};

<synthetic> object Foo extends scala.runtime.AbstractFunction2 with Serializable {

  final override <synthetic> def toString(): String = "Foo";

  case <synthetic> def apply(foo: String, bar: Int): Foo = new Foo(foo, bar);

  case <synthetic> def unapply(x$0: Foo): Option =
     if (x$0.==(null))
        scala.None
     else
        new Some(new Tuple2(x$0.foo(), scala.Int.box(x$0.bar())));

  <synthetic> private def readResolve(): Object = Foo;

  case <synthetic> <bridge> <artifact> def apply(v1: Object, v2: Object): Object = Foo.this.apply(v1.$asInstanceOf[String](), scala.Int.unbox(v2));

  def <init>(): Foo.type = {
    Foo.super.<init>();
    ()
  }
}
...

As we can see Scala compiler produces a regular class Foo and companion-object Foo.

Let's go through the compiled class and comment on what we have got:

  • the internal state of the Foo class, immutable:
val foo: String
val bar: Int
  • getters:
def foo(): String
def bar(): Int
  • copy methods:
def copy(foo: String, bar: Int): Foo
def copy$default$1(): String
def copy$default$2(): Int
  • implementing scala.Product trait:
override def productPrefix(): String
def productArity(): Int
def productElement(x$1: Int): Object
override def productIterator(): Iterator
  • implementing scala.Equals trait for make case class instances comparable for equality by ==:
def canEqual(x$1: Object): Boolean
override def equals(x$1: Object): Boolean
  • overriding java.lang.Object.hashCode for obeying the equals-hashcode contract:
override <synthetic> def hashCode(): Int
  • overriding java.lang.Object.toString :
override def toString(): String
  • constructor for instantiation by new keyword:
def <init>(foo: String, bar: Int): Foo 

Object Foo: - method apply for instantiation without new keyword:

case <synthetic> def apply(foo: String, bar: Int): Foo = new Foo(foo, bar);
  • extractor method unupply for using case class Foo in pattern matching:
case <synthetic> def unapply(x$0: Foo): Option
  • method to protect object as singleton from deserialization for not letting produce one more instance:
<synthetic> private def readResolve(): Object = Foo;
  • object Foo extends scala.runtime.AbstractFunction2 for doing such trick:
scala> case class Foo(foo:String, bar: Int)
defined class Foo

scala> Foo.tupled
res1: ((String, Int)) => Foo = scala.Function2$$Lambda$224/1935637221@9ab310b

tupled from object returns a funtion to create a new Foo by applying a tuple of 2 elements.

So case class is just syntactic sugar.

Scroll to bottom of Div on page load (jQuery)

None of these worked for me, I have a message system inside a web app that's similar to Facebook messenger and wanted the messages to appear at the bottom of a div.

This worked a treat, basic Javascript.

window.onload=function () {
     var objDiv = document.getElementById("MyDivElement");
     objDiv.scrollTop = objDiv.scrollHeight;
}

How to ftp with a batch file?

Using the Windows FTP client you would want to use the -s:filename option to specify a script for the FTP client to run. The documentation specifically points out that you should not try to pipe input into the FTP client with a < character.

Execution of the script will start immediately, so it does work for username/password.

However, the security of this setup is questionable since you now have a username and password for the FTP server visible to anyone who decides to look at your batch file.

Either way, you can generate the script file on the fly from the batch file and then pass it to the FTP client like so:

@echo off

REM Generate the script. Will overwrite any existing temp.txt
echo open servername> temp.txt
echo username>> temp.txt
echo password>> temp.txt
echo get %1>> temp.txt
echo quit>> temp.txt

REM Launch FTP and pass it the script
ftp -s:temp.txt

REM Clean up.
del temp.txt

Replace servername, username, and password with your details and the batch file will generate the script as temp.txt launch ftp with the script and then delete the script.

If you are always getting the same file you can replace the %1 with the file name. If not you just launch the batchfile and provide the name of the file to get as an argument.

ORA-01653: unable to extend table by in tablespace ORA-06512

You could also turn on autoextend for the whole database using this command:

ALTER DATABASE DATAFILE 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\SYSTEM.DBF'
AUTOEXTEND ON NEXT 1M MAXSIZE 1024M;

Just change the filepath to point to your system.dbf file.

Credit Here

Multiple line comment in Python

Try this

'''
This is a multiline
comment. I can type here whatever I want.
'''

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.

How do I validate a date string format in python?

From mere curiosity, I timed the two rivalling answers posted above.
And I had the following results:

dateutil.parser (valid str): 4.6732222699938575
dateutil.parser (invalid str): 1.7270505399937974
datetime.strptime (valid): 0.7822393209935399
datetime.strptime (invalid): 0.4394566189876059

And here's the code I used (Python 3.6)


from dateutil import parser as date_parser
from datetime import datetime
from timeit import timeit


def is_date_parsing(date_str):
    try:
        return bool(date_parser.parse(date_str))
    except ValueError:
        return False


def is_date_matching(date_str):
    try:
        return bool(datetime.strptime(date_str, '%Y-%m-%d'))
    except ValueError:
        return False



if __name__ == '__main__':
    print("dateutil.parser (valid date):", end=' ')
    print(timeit("is_date_parsing('2021-01-26')",
                 setup="from __main__ import is_date_parsing",
                 number=100000))

    print("dateutil.parser (invalid date):", end=' ')
    print(timeit("is_date_parsing('meh')",
                 setup="from __main__ import is_date_parsing",
                 number=100000))

    print("datetime.strptime (valid date):", end=' ')
    print(timeit("is_date_matching('2021-01-26')",
                 setup="from __main__ import is_date_matching",
                 number=100000))

    print("datetime.strptime (invalid date):", end=' ')
    print(timeit("is_date_matching('meh')",
                 setup="from __main__ import is_date_matching",
                 number=100000))

SSL cert "err_cert_authority_invalid" on mobile chrome only

The report from SSLabs says:

  This server's certificate chain is incomplete. Grade capped to B.
  ....
  Chain Issues                  Incomplete

Desktop browsers often have chain certificates cached from previous connections or download them from the URL specified in the certificate. Mobile browsers and other applications usually don't.

Fix your chain by including the missing certificates and everything should be right.

Getting a list of values from a list of dicts

Get key values from list of dictionaries in python?

  1. Get key values from list of dictionaries in python?

Ex:

data = 
[{'obj1':[{'cpu_percentage':'15%','ram':3,'memory_percentage':'66%'}]},
{'obj2': [{'cpu_percentage':'0','ram':4,'memory_percentage':'35%'}]}]

for d in data:

  for key,value in d.items(): 

      z ={key: {'cpu_percentage': d['cpu_percentage'],'memory_percentage': d['memory_percentage']} for d in value} 
      print(z)

Output:

{'obj1': {'cpu_percentage': '15%', 'memory_percentage': '66%'}}
{'obj2': {'cpu_percentage': '0', 'memory_percentage': '35%'}}

How do I get the name of the rows from the index of a data frame?

if you want to get the index values, you can simply do:

dataframe.index

this will output a pandas.core.index

Getting The ASCII Value of a character in a C# string

Here is another alternative. It will of course give you a bad result if the input char is not ascii. I've not perf tested it but I think it would be pretty fast:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(string s, int index) {
    return GetAsciiVal(s[index]);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(char c) {
    return unchecked(c & 0xFF);
}

Reading file from Workspace in Jenkins with Groovy script

I realize this question was about creating a plugin, but since the new Jenkins 2 Pipeline builds use Groovy, I found myself here while trying to figure out how to read a file from a workspace in a Pipeline build. So maybe I can help someone like me out in the future.

Turns out it's very easy, there is a readfile step, and I should have rtfm:

env.WORKSPACE = pwd()
def version = readFile "${env.WORKSPACE}/version.txt"

path.join vs path.resolve with __dirname

From the doc for path.resolve:

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

But path.join keeps trailing slashes

So

__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'

Font Awesome & Unicode

By using css you can add your icon via Unicode

content: '\f144';
font-family: FontAwesome;

This will work

Error: "an object reference is required for the non-static field, method or property..."

You can't access non-static members from a static method. (Note that Main() is static, which is a requirement of .Net). Just make siprimo and volteado static, by placing the static keyword in front of them. e.g.:

 static private long volteado(long a)

Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

I was having similar issue and I think if we simply ignore the ssl verification will work like charm as it worked for me. So connecting to server with https scheme but directing them not to verify the certificate.

Using requests. Just mention verify=False instead of None

    requests.post(url, data=payload, headers=headers, verify=False)

Hoping this will work for those who needs :).

How to create local notifications?

In appdelegate.m file write the follwing code in applicationDidEnterBackground to get the local notification

- (void)applicationDidEnterBackground:(UIApplication *)application
{
   UILocalNotification *notification = [[UILocalNotification alloc]init];
   notification.repeatInterval = NSDayCalendarUnit;
   [notification setAlertBody:@"Hello world"];
   [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
   [notification setTimeZone:[NSTimeZone  defaultTimeZone]];
   [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}

Java Generics With a Class & an Interface - Together

Actually, you can do what you want. If you want to provide multiple interfaces or a class plus interfaces, you have to have your wildcard look something like this:

<T extends ClassA & InterfaceB>

See the Generics Tutorial at sun.com, specifically the Bounded Type Parameters section, at the bottom of the page. You can actually list more than one interface if you wish, using & InterfaceName for each one that you need.

This can get arbitrarily complicated. To demonstrate, see the JavaDoc declaration of Collections#max, which (wrapped onto two lines) is:

public static <T extends Object & Comparable<? super T>> T
                                           max(Collection<? extends T> coll)

why so complicated? As said in the Java Generics FAQ: To preserve binary compatibility.

It looks like this doesn't work for variable declaration, but it does work when putting a generic boundary on a class. Thus, to do what you want, you may have to jump through a few hoops. But you can do it. You can do something like this, putting a generic boundary on your class and then:

class classB { }
interface interfaceC { }

public class MyClass<T extends classB & interfaceC> {
    Class<T> variable;
}

to get variable that has the restriction that you want. For more information and examples, check out page 3 of Generics in Java 5.0. Note, in <T extends B & C>, the class name must come first, and interfaces follow. And of course you can only list a single class.

CSS Circle with border

You forgot to set the width of the border! Change border: red; to border:1px solid red;

Here the full code to get the circle:

_x000D_
_x000D_
.circle {_x000D_
    background-color:#fff;_x000D_
    border:1px solid red;    _x000D_
    height:100px;_x000D_
    border-radius:50%;_x000D_
    -moz-border-radius:50%;_x000D_
    -webkit-border-radius:50%;_x000D_
    width:100px;_x000D_
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_

Can I use GDB to debug a running process?

Yes you can. Assume a process foo is running...

ps -elf | grep foo

look for the PID number

gdb -a {PID number}

How to match a substring in a string, ignoring case

You can use in operator in conjunction with lower method of strings.

if "mandy" in line.lower():

Fatal error: "No Target Architecture" in Visual Studio

If you are building 32bit then make sure you don't have _WIN64 defined for your project.

Angular 2 - Redirect to an external URL and open in a new tab

in HTML:

<a class="main-item" (click)="onNavigate()">Go to URL</a>

OR

<button class="main-item" (click)="onNavigate()">Go to URL</button>

in TS file:

onNavigate(){
    // your logic here.... like set the url 
    const url = 'https://www.google.com';
    window.open(url, '_blank');
}

How to force JS to do math instead of putting two strings together

DON'T FORGET - Use parseFloat(); if your dealing with decimals.

change text of button and disable button in iOS

SWIFT 4 with extension

set:

// set button label for all states
extension UIButton {
    public func setAllStatesTitle(_ newTitle: String){
        self.setTitle(newTitle, for: .normal)
        self.setTitle(newTitle, for: .selected)
        self.setTitle(newTitle, for: .disabled)
    }
}

and use:

yourBtn.setAllStatesTitle("btn title")

Get HTML inside iframe using jQuery

Why not try Ajax, check a code part 1 or part 2 (use comment).

_x000D_
_x000D_
$(document).ready(function(){ _x000D_
 console.clear();_x000D_
/*_x000D_
    // PART 1 ERROR_x000D_
    // Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Sandbox access violation: Blocked a frame at "http://stacksnippets.net" from accessing a frame at "null".  Both frames are sandboxed and lack the "allow-same-origin" flag._x000D_
 console.log("PART 1:: ");_x000D_
 console.log($('iframe#sandro').contents().find("html").html());_x000D_
*/_x000D_
 // PART 2_x000D_
 $.ajax({_x000D_
  url: $("iframe#sandro").attr("src"),_x000D_
  type: 'GET',_x000D_
  dataType: 'html'_x000D_
 }).done(function(html) {_x000D_
  console.log("PART 2:: ");_x000D_
  console.log(html);_x000D_
 });_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<body>_x000D_
<iframe id="sandro" src="https://jsfiddle.net/robots.txt"></iframe>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Check if a string is a valid date using DateTime.TryParse

Basically, I want to check if a particular string contains AT LEAST day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) and year(yyyy or yy) in any order, with any date separator , what will be the solution? So, if the value includes any parts of time, it should return true too. I could NOT be able to define a array of format.

When I was in a similar situation, here is what I did:

  1. Gather all the formats my system is expected to support.
  2. Looked at what is common or can be generalize.
  3. Learned to create REGEX (It is an investment of time initially but pays off once you create one or two on your own). Also do not try to build REGEX for all formats in one go, follow incremental process.
  4. I created REGEX to cover as many format as possible.
  5. For few cases, not to make REGEX extra complex, I covered it through DateTime.Parse() method.
  6. With the combination of both Parse as well as REGEX i was able to validate the input is correct/as expected.

This http://www.codeproject.com/Articles/13255/Validation-with-Regular-Expressions-Made-Simple was really helpful both for understanding as well as validation the syntax for each format.

My 2 cents if it helps....

Correct modification of state arrays in React.js

Easiest, if you are using ES6.

initialArray = [1, 2, 3];

newArray = [ ...initialArray, 4 ]; // --> [1,2,3,4]

New array will be [1,2,3,4]

to update your state in React

this.setState({
  arrayvar:[...this.state.arrayvar, newelement]
});

Learn more about array destructuring

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

I had to install MariaDB. I am using OpenSUSE LINUX Leap 15 and had to execute these commands:

sudo zypper update
sudo zypper install mariadb mariadb-client mariadb-tools
sudo systemctl start mysql
sudo systemctl enable mysql //enable auto start at boot time3
sudo mysql_secure_installation

Source.

In SQL how to compare date values?

Nevermind found an answer. Ty the same for anyone who was willing to reply.

WHERE DATEDIFF(mydata,'2008-11-20') >=0;

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

The minimal-ui viewport property is no longer supported in iOS 8. However, the minimal-ui itself is not gone. User can enter the minimal-ui with a "touch-drag down" gesture.

There are several pre-conditions and obstacles to manage the view state, e.g. for minimal-ui to work, there has to be enough content to enable user to scroll; for minimal-ui to persist, window scroll must be offset on page load and after orientation change. However, there is no way of calculating the dimensions of the minimal-ui using the screen variable, and thus no way of telling when user is in the minimal-ui in advance.

These observations is a result of research as part of developing Brim – view manager for iOS 8. The end implementation works in the following way:

When page is loaded, Brim will create a treadmill element. Treadmill element is used to give user space to scroll. Presence of the treadmill element ensures that user can enter the minimal-ui view and that it continues to persist if user reloads the page or changes device orientation. It is invisible to the user the entire time. This element has ID brim-treadmill.

Upon loading the page or after changing the orientation, Brim is using Scream to detect if page is in the minimal-ui view (page that has been previously in minimal-ui and has been reloaded will remain in the minimal-ui if content height is greater than the viewport height).

When page is in the minimal-ui, Brim will disable scrolling of the document (it does this in a safe way that does not affect the contents of the main element). Disabling document scrolling prevents accidentally leaving the minimal-ui when scrolling upwards. As per the original iOS 7.1 spec, tapping the top bar brings back the rest of the chrome.

The end result looks like this:

Brim in iOS simulator.

For the sake of documentation, and in case you prefer to write your own implementation, it is worth noting that you cannot use Scream to detect if device is in minimal-ui straight after the orientationchange event because window dimensions do not reflect the new orientation until the rotation animation has ended. You have to attach a listener to the orientationchangeend event.

Scream and orientationchangeend have been developed as part of this project.

Binding Combobox Using Dictionary as the Datasource

I know this is a pretty old topic, but I also had a same problem.

My solution:

how we fill the combobox:

foreach (KeyValuePair<int, string> item in listRegion)
{
    combo.Items.Add(item.Value);
    combo.ValueMember = item.Value.ToString();
    combo.DisplayMember = item.Key.ToString();
    combo.SelectedIndex = 0;
}

and that's how we get inside:

 MessageBox.Show(combo_region.DisplayMember.ToString());

I hope it help someone

Excel formula to search if all cells in a range read "True", if not, then show "False"

As it appears you have the values as text, and not the numeric True/False, then you can use either COUNTIF or SUMPRODUCT

=IF(SUMPRODUCT(--(A2:D2="False")),"False","True")
=IF(COUNTIF(A3:D3,"False*"),"False","True")

How do I remove/delete a folder that is not empty?

To delete a folder even if it might not exist (avoiding the race condition in Charles Chow's answer) but still have errors when other things go wrong (e.g. permission problems, disk read error, the file isn't a directory)

For Python 3.x:

import shutil

def ignore_absent_file(func, path, exc_inf):
    except_instance = exc_inf[1]
    if isinstance(except_instance, FileNotFoundError):
        return
    raise except_instance

shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)

The Python 2.7 code is almost the same:

import shutil
import errno

def ignore_absent_file(func, path, exc_inf):
    except_instance = exc_inf[1]
    if isinstance(except_instance, OSError) and \
        except_instance.errno == errno.ENOENT:
        return
    raise except_instance

shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)

contenteditable change events

Check this idea out. http://pastie.org/1096892

I think it's close. HTML 5 really needs to add the change event to the spec. The only problem is that the callback function evaluates if (before == $(this).html()) before the content is actually updated in $(this).html(). setTimeout don't work, and it's sad. Let me know what you think.

Copying a rsa public key to clipboard

Another alternative solution:

cat  ~/.ssh/id_rsa.pub |  xsel -i -b

From man xsel :

-i, --input

read standard input into the selection.

-b, --clipboard

operate on the CLIPBOARD selection.

What are Unwind segues for and how do you use them?

For example if you navigate from viewControllerB to viewControllerA then in your viewControllerA below delegate will call and data will share.

@IBAction func unWindSeague (_ sender : UIStoryboardSegue) {
        if sender.source is ViewControllerB  {
            if let _ = sender.source as? ViewControllerB {
                self.textLabel.text = "Came from B = B->A , B exited"
            }
            
        }

}
  • Unwind Seague Source View Controller ( You Need to connect Exit Button to VC’s exit icon and connect it to unwindseague:

enter image description here

  • Unwind Seague Completed -> TextLabel of viewControllerA is Changed.

enter image description here

Scala list concatenation, ::: vs ++

A different point is that the first sentence is parsed as:

scala> List(1,2,3).++(List(4,5))
res0: List[Int] = List(1, 2, 3, 4, 5)

Whereas the second example is parsed as:

scala> List(4,5).:::(List(1,2,3))
res1: List[Int] = List(1, 2, 3, 4, 5)

So if you are using macros, you should take care.

Besides, ++ for two lists is calling ::: but with more overhead because it is asking for an implicit value to have a builder from List to List. But microbenchmarks did not prove anything useful in that sense, I guess that the compiler optimizes such calls.

Micro-Benchmarks after warming up.

scala>def time(a: => Unit): Long = { val t = System.currentTimeMillis; a; System.currentTimeMillis - t}
scala>def average(a: () => Long) = (for(i<-1 to 100) yield a()).sum/100

scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ++ List(e) } })
res1: Long = 46
scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ::: List(e ) } })
res2: Long = 46

As Daniel C. Sobrai said, you can append the content of any collection to a list using ++, whereas with ::: you can only concatenate lists.

Extract XML Value in bash script

XMLStarlet or another XPath engine is the correct tool for this job.

For instance, with data.xml containing the following:

<root>
  <item> 
    <title>15:54:57 - George:</title>
    <description>Diane DeConn? You saw Diane DeConn!</description> 
  </item> 
  <item> 
    <title>15:55:17 - Jerry:</title> 
    <description>Something huh?</description>
  </item>
</root>

...you can extract only the first title with the following:

xmlstarlet sel -t -m '//title[1]' -v . -n <data.xml

Trying to use sed for this job is troublesome. For instance, the regex-based approaches won't work if the title has attributes; won't handle CDATA sections; won't correctly recognize namespace mappings; can't determine whether a portion of the XML documented is commented out; won't unescape attribute references (such as changing Brewster &amp; Jobs to Brewster & Jobs), and so forth.

Express: How to pass app-instance to routes from a different file?

  1. To make your db object accessible to all controllers without passing it everywhere: make an application-level middleware which attachs the db object to every req object, then you can access it within in every controller.
// app.js
let db = ...;  // your db object initialized
const contextMiddleware = (req, res, next) => {
  req.db=db;
  next();
};
app.use(contextMiddleware);
  1. to avoid passing app instance everywhere, instead, passing routes to where the app is
// routes.js  It's just a mapping.
exports.routes = [
  ['/', controllers.index],
  ['/posts', controllers.posts.index],
  ['/posts/:post', controllers.posts.show]
];

// app.js
var { routes }    = require('./routes');
routes.forEach(route => app.get(...route));
// You can customize this according to your own needs, like adding post request

The final app.js:

// app.js
var express   = require('express');
var app       = express.createServer();

let db = ...;  // your db object initialized
const contextMiddleware = (req, res, next) => {
  req.db=db;
  next();
};
app.use(contextMiddleware);

var { routes }    = require('./routes');
routes.forEach(route => app.get(...route));

app.listen(3000, function() {
  console.log('Application is listening on port 3000');
});

Another version: you can customize this according to your own needs, like adding post request

// routes.js  It's just a mapping.
let get = ({path, callback}) => ({app})=>{
  app.get(path, callback);
}
let post = ({path, callback}) => ({app})=>{
  app.post(path, callback);
}
let someFn = ({path, callback}) => ({app})=>{
  // ...custom logic
  app.get(path, callback);
}
exports.routes = [
  get({path: '/', callback: controllers.index}),
  post({path: '/posts', callback: controllers.posts.index}),
  someFn({path: '/posts/:post', callback: controllers.posts.show}),
];

// app.js
var { routes }    = require('./routes');
routes.forEach(route => route({app}));

Is it possible to play music during calls so that the partner can hear it ? Android

You failed to find an app that does this because it is not possible.

The documentation clearly states (here):

Note: You can play back the audio data only to the standard output device. Currently, that is the mobile device speaker or a Bluetooth headset. You cannot play sound files in the conversation audio during a call.

The reason behind this decision has probably something to do with security: there are several scenarios where this capability could be used for cons.

(the OP is highly similar to this, hence I'm basically giving the same answer)

Refresh Fragment at reload

In case you do not have the fragment tag, the following code works well for me.

Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
if (currentFragment instanceof "NAME OF YOUR FRAGMENT CLASS") {
 FragmentTransaction fragTransaction =   (getActivity()).getFragmentManager().beginTransaction();
 fragTransaction.detach(currentFragment);
 fragTransaction.attach(currentFragment);
 fragTransaction.commit();}
}

Is there an "exists" function for jQuery?

I am using this:

 if($("#element").length > 0){
   //the element exists in the page, you can do the rest....
 }

Its very simple and easy to find an element.

Naming convention - underscore in C++ and C# variables

There's no particular single naming convention, but I've seen that for private members.

What are the differences between 'call-template' and 'apply-templates' in XSL?

To add to the good answer by @Tomalak:

Here are some unmentioned and important differences:

  1. xsl:apply-templates is much richer and deeper than xsl:call-templates and even from xsl:for-each, simply because we don't know what code will be applied on the nodes of the selection -- in the general case this code will be different for different nodes of the node-list.

  2. The code that will be applied can be written way after the xsl:apply templates was written and by people that do not know the original author.

The FXSL library's implementation of higher-order functions (HOF) in XSLT wouldn't be possible if XSLT didn't have the <xsl:apply-templates> instruction.

Summary: Templates and the <xsl:apply-templates> instruction is how XSLT implements and deals with polymorphism.

Reference: See this whole thread: http://www.biglist.com/lists/lists.mulberrytech.com/xsl-list/archives/200411/msg00546.html

C++: Converting Hexadecimal to Decimal

This should work as well.

#include <ctype.h>
#include <string.h>

template<typename T = unsigned int>
T Hex2Int(const char* const Hexstr, bool* Overflow)
{
    if (!Hexstr)
        return false;
    if (Overflow)
        *Overflow = false;

    auto between = [](char val, char c1, char c2) { return val >= c1 && val <= c2; };
    size_t len = strlen(Hexstr);
    T result = 0;

    for (size_t i = 0, offset = sizeof(T) << 3; i < len && (int)offset > 0; i++)
    {
        if (between(Hexstr[i], '0', '9'))
            result = result << 4 ^ Hexstr[i] - '0';
        else if (between(tolower(Hexstr[i]), 'a', 'f'))
            result = result << 4 ^ tolower(Hexstr[i]) - ('a' - 10); // Remove the decimal part;
        offset -= 4;
    }
    if (((len + ((len % 2) != 0)) << 2) > (sizeof(T) << 3) && Overflow)
        *Overflow = true;
    return result;
}

The 'Overflow' parameter is optional, so you can leave it NULL.

Example:

auto result = Hex2Int("C0ffee", NULL);
auto result2 = Hex2Int<long>("DeadC0ffe", NULL);

How to serve up a JSON response using Go?

Other users commenting that the Content-Type is plain/text when encoding. You have to set the Content-Type first w.Header().Set, then the HTTP response code w.WriteHeader.

If you call w.WriteHeader first then call w.Header().Set after you will get plain/text.

An example handler might look like this;

func SomeHandler(w http.ResponseWriter, r *http.Request) {
    data := SomeStruct{}
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(data)
}

How to insert element into arrays at specific position?

Not as concrete as the answer of Artefacto, but based in his suggestion of using array_slice(), I wrote the next function:

function arrayInsert($target, $byKey, $byOffset, $valuesToInsert, $afterKey) {
    if (isset($byKey)) {
        if (is_numeric($byKey)) $byKey = (int)floor($byKey);
        $offset = 0;

        foreach ($target as $key => $value) {
            if ($key === $byKey) break;
            $offset++;
        }

        if ($afterKey) $offset++;
    } else {
        $offset = $byOffset;
    }

    $targetLength = count($target);
    $targetA = array_slice($target, 0, $offset, true);
    $targetB = array_slice($target, $offset, $targetLength, true);
    return array_merge($targetA, $valuesToInsert, $targetB);
}

Features:

  • Inserting one or múltiple values
  • Inserting key value pair(s)
  • Inserting before/after the key, or by offset

Usage examples:

$target = [
    'banana' => 12,
    'potatoe' => 6,
    'watermelon' => 8,
    'apple' => 7,
    2 => 21,
    'pear' => 6
];

// Values must be nested in an array
$insertValues = [
    'orange' => 0,
    'lemon' => 3,
    3
];

// By key
// Third parameter is not applicable
//     Insert after 2 (before 'pear')
var_dump(arrayInsert($target, 2, null, $valuesToInsert, true));
//     Insert before 'watermelon'
var_dump(arrayInsert($target, 'watermelon', null, $valuesToInsert, false)); 

// By offset
// Second and last parameter are not applicable
//     Insert in position 2 (zero based i.e. before 'watermelon')
var_dump(arrayInsert($target, null, 2, $valuesToInsert, null)); 

How to define Singleton in TypeScript

In Typescript, one doesn't necessarily have to follow the new instance() Singleton methodology. An imported, constructor-less static class can work equally as well.

Consider:

export class YourSingleton {

   public static foo:bar;

   public static initialise(_initVars:any):void {
     YourSingleton.foo = _initvars.foo;
   }

   public static doThing():bar {
     return YourSingleton.foo
   }
}

You can import the class and refer to YourSingleton.doThing() in any other class. But remember, because this is a static class, it has no constructor so I usually use an intialise() method that is called from a class that imports the Singleton:

import {YourSingleton} from 'singleton.ts';

YourSingleton.initialise(params);
let _result:bar = YourSingleton.doThing();

Don't forget that in a static class, every method and variable needs to also be static so instead of this you would use the full class name YourSingleton.

How to find what code is run by a button or element in Chrome using Developer Tools

Sounds like the "...and I jump line by line..." part is wrong. Do you StepOver or StepIn and are you sure you don't accidentally miss the relevant call?

That said, debugging frameworks can be tedious for exactly this reason. To alleviate the problem, you can enable the "Enable frameworks debugging support" experiment. Happy debugging! :)

ImportError: No module named psycopg2

Run into the same issue when i switch to ubuntu from windows 10.. the following worked for me.. this after googling and trying numerous suggestions for 2 hours...

sudo apt-get install libpq-dev, then pip3 install psycopg2

I hope this helps someone who has encountered the same problem especially when switching for windows OS to linux(ubuntu).

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

Copy data from one existing row to another existing row in SQL?

This works well for coping entire records.

UPDATE your_table
SET new_field = sourse_field

MySQL Query GROUP BY day / month / year

I tried using the 'WHERE' statement above, I thought its correct since nobody corrected it but I was wrong; after some searches I found out that this is the right formula for the WHERE statement so the code becomes like this:

SELECT COUNT(id)  
FROM stats  
WHERE YEAR(record_date) = 2009  
GROUP BY MONTH(record_date)

HTML: how to make 2 tables with different CSS

Of course it is!

Give them both an id and set up the CSS accordingly:

#table1
{
    CSS for table1
}


#table2
{
    CSS for table2
}

How to find the Vagrant IP?

I've developed a small vagrant-address plugin for that. It's simple, cross-platform, cross-provider, and does not require scripting.

https://github.com/mkuzmin/vagrant-address

Convert Int to String in Swift

Multiple ways to do this :

var str1:String="\(23)"
var str2:String=String(format:"%d",234)

Visual Studio debugger error: Unable to start program Specified file cannot be found

I think that what you have to check is:

  1. if the target EXE is correctly configured in the project settings ("command", in the debugging tab). Since all individual projects run when you start debugging it's well possible that only the debugging target for the "ALL" solution is missing, check which project is currently active (you can also select the debugger target by changing the active project).

  2. dependencies (DLLs) are also located at the target debugee directory or can be loaded (you can use the "depends.exe" tool for checking dependencies of an executable or DLL).

Find a string by searching all tables in SQL Server Management Studio 2008

To update TechDo's answer for SQL server 2012. You need to change: 'FROM ' + @TableName + ' (NOLOCK) ' to FROM ' + @TableName + 'WITH (NOLOCK) ' +

Other wise you will get the following error: Deprecated feature 'Table hint without WITH' is not supported in this version of SQL Server.

Below is the complete updated stored procedure:

CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN

    CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

    SET NOCOUNT ON

    DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
    SET  @TableName = ''
    SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

    WHILE @TableName IS NOT NULL

    BEGIN
        SET @ColumnName = ''
        SET @TableName = 
        (
            SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
            FROM     INFORMATION_SCHEMA.TABLES
            WHERE         TABLE_TYPE = 'BASE TABLE'
                AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                AND    OBJECTPROPERTY(
                        OBJECT_ID(
                            QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                             ), 'IsMSShipped'
                               ) = 0
        )

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

        BEGIN
            SET @ColumnName =
            (
                SELECT MIN(QUOTENAME(COLUMN_NAME))
                FROM     INFORMATION_SCHEMA.COLUMNS
                WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                    AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                    AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                    AND    QUOTENAME(COLUMN_NAME) > @ColumnName
            )

            IF @ColumnName IS NOT NULL

            BEGIN
                INSERT INTO #Results
                EXEC
                (
                    'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                    FROM ' + @TableName + 'WITH (NOLOCK) ' +
                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                )
            END
        END    
    END

    SELECT ColumnName, ColumnValue FROM #Results
END

How to convert ISO8859-15 to UTF8?

We have this problem and to solve

Create a script file called to-utf8.sh

#!/bin/bash
TO="UTF-8"; FILE=$1
FROM=$(file -i $FILE | cut -d'=' -f2)
if [[ $FROM = "binary" ]]; then
 echo "Skipping binary $FILE..."
 exit 0
fi
iconv -f $FROM -t $TO -o $FILE.tmp $FILE; ERROR=$?
if [[ $ERROR -eq 0 ]]; then
  echo "Converting $FILE..."
  mv -f $FILE.tmp $FILE
else
  echo "Error on $FILE"
fi

Set the executable bit

chmod +x to-utf8.sh

Do a conversion

./to-utf8.sh MyFile.txt

If you want to convert all files under a folder, do

find /your/folder/here | xargs -n 1 ./to-utf8.sh

Hope it's help.

Two column div layout with fluid left and fixed right column

I was recently shown this website for liquid layouts using CSS. http://matthewjamestaylor.com/blog/perfect-multi-column-liquid-layouts (Take a look at the demo pages in the links below).

The author now provides an example for fixed width layouts. Check out; http://matthewjamestaylor.com/blog/how-to-convert-a-liquid-layout-to-fixed-width.

This provides the following example(s), http://matthewjamestaylor.com/blog/ultimate-2-column-left-menu-pixels.htm (for two column layout like you are after I think)

http://matthewjamestaylor.com/blog/fixed-width-or-liquid-layout.htm (for three column layout).

Sorry for so many links to this guys site, but I think it is an AWESOME resource.

Postgresql: error "must be owner of relation" when changing a owner object

Thanks to Mike's comment, I've re-read the doc and I've realised that my current user (i.e. userA that already has the create privilege) wasn't a direct/indirect member of the new owning role...

So the solution was quite simple - I've just done this grant:

grant userB to userA;

That's all folks ;-)


Update:

Another requirement is that the object has to be owned by user userA before altering it...

Python: Is there an equivalent of mid, right, and left from BASIC?

You can use this method also it will act like that

thadari=[1,2,3,4,5,6]

#Front Two(Left)
print(thadari[:2])
[1,2]

#Last Two(Right)# edited
print(thadari[-2:])
[5,6]

#mid
mid = len(thadari) //2

lefthalf = thadari[:mid]
[1,2,3]
righthalf = thadari[mid:]
[4,5,6]

Hope it will help

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

Even if fileno(FILE *) may return a file descriptor, be VERY careful not to bypass stdio's buffer. If there is buffer data (either read or unflushed write), reads/writes from the file descriptor might give you unexpected results.

To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)

Create a circular button in BS3

To add a rounded border in any button the best way is to add the border-radius property. I belive this class is better because you can add-it at any button size. If you set the height and widht you will need to create a "rouding" class to each button size.

_x000D_
_x000D_
.btn-circle {_x000D_
  border-radius: 50%;_x000D_
}
_x000D_
<button class='btn-circle'>Click Me!</button>_x000D_
<button class='btn-circle'>?</button>
_x000D_
_x000D_
_x000D_

pg_config executable not found

You can use the binary instead, I ran into the issue in dockerizing the application when Django tried to install it as part of its dependencies, to resolve that, I used this setup for requirements.txt where the binary is installed first and then django does not try to install it again: psycopg2-binary django gunicorn

Int to Decimal Conversion - Insert decimal point at specified location

Declare it as a decimal which uses the int variable and divide this by 100

int number = 700
decimal correctNumber = (decimal)number / 100;

Edit: Bala was faster with his reaction

Using FileSystemWatcher to monitor a directory

The problem was the notify filters. The program was trying to open a file that was still copying. I removed all of the notify filters except for LastWrite.

private void watch()
{
  FileSystemWatcher watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastWrite;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

How to add calendar events in Android?

Google calendar is the "native" calendar app. As far as I know, all phones come with a version of it installed, and the default SDK provides a version.

You might check out this tutorial for working with it.

How do you store Java objects in HttpSession?

Add it to the session, not to the request.

HttpSession session = request.getSession();
session.setAttribute("object", object);

Also, don't use scriptlets in the JSP. Use EL instead; to access object all you need is ${object}.

A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access application data stored in JavaBeans components. For example, the JSP expression language allows a page author to access a bean using simple syntax such as ${name} for a simple variable or ${name.foo.bar} for a nested property.

Correct way to write loops for promise.

Given

  • asyncFn function
  • array of items

Required

  • promise chaining .then()'s in series (in order)
  • native es6

Solution

let asyncFn = (item) => {
  return new Promise((resolve, reject) => {
    setTimeout( () => {console.log(item); resolve(true)}, 1000 )
  })
}

// asyncFn('a')
// .then(()=>{return async('b')})
// .then(()=>{return async('c')})
// .then(()=>{return async('d')})

let a = ['a','b','c','d']

a.reduce((previous, current, index, array) => {
  return previous                                    // initiates the promise chain
  .then(()=>{return asyncFn(array[index])})      //adds .then() promise for each item
}, Promise.resolve())

Python constructor and default value

Mutable default arguments don't generally do what you want. Instead, try this:

class Node:
     def __init__(self, wordList=None, adjacencyList=None):
        if wordList is None:
            self.wordList = []
        else:
             self.wordList = wordList 
        if adjacencyList is None:
            self.adjacencyList = []
        else:
             self.adjacencyList = adjacencyList 

Change :hover CSS properties with JavaScript

You can use mouse events to control like hover. For example, the following code is making visible when you hover that element.

var foo = document.getElementById("foo");
foo.addEventListener('mouseover',function(){
   foo.style.display="block";
})
foo.addEventListener('mouseleave',function(){
   foo.style.display="none";
})

How to change Visual Studio 2012,2013 or 2015 License Key?

For those who will need to remove product key from Visual Studio 2015:

  1. remove registry key HKCR\Licenses\4D8CFBCB-2F6A-4AD2-BABF-10E28F6F2C8F
  2. repair Visual Studio installation

That's it, now you can change the product key if necessary.

Show/Hide the console window of a C# console application

"Just to hide" you can:

Change the output type from Console Application to Windows Application,

And Instead of Console.Readline/key you can use new ManualResetEvent(false).WaitOne() at the end to keep the app running.

push() a two-dimensional array

The solution below uses a double loop to add data to the bottom of a 2x2 array in the Case 3. The inner loop pushes selected elements' values into a new row array. The outerloop then pushes the new row array to the bottom of an existing array (see Newbie: Add values to two-dimensional array with for loops, Google Apps Script).

In this example, I created a function that extracts a section from an existing array. The extracted section can be a row (full or partial), a column (full or partial), or a 2x2 section of the existing array. A new blank array (newArr) is filled by pushing the relevant section from the existing array (arr) into the new array.

 function arraySection(arr, r1, c1, rLength, cLength) {      
   rowMax = arr.length;
    if(isNaN(rowMax)){rowMax = 1};
   colMax = arr[0].length;
   if(isNaN(colMax)){colMax = 1};
   var r2 = r1 + rLength - 1;
   var c2 = c1 + cLength - 1;

   if ((r1< 0 || r1 > r2 || r1 > rowMax || (r1 | 0) != r1) || (r2 < 0 || 
     r2 > rowMax || (r2 | 0) != r2)|| (c1< 0 || c1 > c2 || c1 > colMax || 
   (c1 | 0) != c1) ||(c2 < 0 || c2 > colMax || (c2 | 0) != c2)){
        throw new Error(
        'arraySection: invalid input')       
        return;
     };
   var newArr = [];

// Case 1: extracted section is a column array, 
//          all elements are in the same column
 if (c1 == c2){
   for (var i = r1; i <= r2; i++){ 
         // Logger.log("arr[i][c1] for i = " + i);
         // Logger.log(arr[i][c1]);
     newArr.push([arr[i][c1]]); 
     };
    };  

// Case 2: extracted section is a row array, 
//          all elements are in the same row
  if (r1 == r2 && c1 != c2){
    for (var j = c1; j <= c2; j++){ 
      newArr.push(arr[r1][j]); 
      };
   };  

// Case 3: extracted section is a 2x2 section 
    if (r1 != r2 && c1 != c2){     
     for (var i = r1; i <= r2; i++) {
          rowi = [];
       for (var j = c1; j <= c2; j++) {
          rowi.push(arr[i][j]);
        }
       newArr.push(rowi)
      };
    };
   return(newArr);
  };

Recursive Fibonacci

I think it's the best solution of fibonacci using recursion.

#include<bits/stdc++.h>
typedef unsigned long long ull;
typedef long long ll;
ull FIBO[100005];
using namespace std;
ull fibo(ull n)
{
    if(n==1||n==0)
        return n;
    if(FIBO[n]!=0)
        return FIBO[n];
    FIBO[n] = (fibo(n-1)+fibo(n-2));
    return FIBO[n];
}
int main()
{
    for(long long  i =34;i<=60;i++)
        cout<<fibo(i)<<" " ;
    return 0;
}

Print page numbers on pages when printing html

This javascript will add absolute positioned div's with pagenumbers on the right bottom corner and works in all browsers.

A4 height = 297mm = 1123px(96dpi)

<html>
    <head>
        <style type="text/css">
            @page {
              size: A4;
              margin: 0; 
            }

            body {
              margin: 0;
            }
        </style>
    </head>
    <body>
        <script type="text/javascript">
          window.onload = addPageNumbers;

          function addPageNumbers() {
            var totalPages = Math.ceil(document.body.scrollHeight / 1123);  //842px A4 pageheight for 72dpi, 1123px A4 pageheight for 96dpi, 
            for (var i = 1; i <= totalPages; i++) {
              var pageNumberDiv = document.createElement("div");
              var pageNumber = document.createTextNode("Page " + i + " of " + totalPages);
              pageNumberDiv.style.position = "absolute";
              pageNumberDiv.style.top = "calc((" + i + " * (297mm - 0.5px)) - 40px)"; //297mm A4 pageheight; 0,5px unknown needed necessary correction value; additional wanted 40px margin from bottom(own element height included)
              pageNumberDiv.style.height = "16px";
              pageNumberDiv.appendChild(pageNumber);
              document.body.insertBefore(pageNumberDiv, document.getElementById("content"));
              pageNumberDiv.style.left = "calc(100% - (" + pageNumberDiv.offsetWidth + "px + 20px))";
            }
          }
        </script>
        <div id="content">
            Lorem ipsum....
        </div>
    </body>
</html>

Add floating point value to android resources/values

Although I've used the accepted answer in the past, it seems with the current Build Tools it is possible to do:

   <dimen name="listAvatarWidthPercent">0.19</dimen>

I'm using Build Tools major version 29.

Selecting text in an element (akin to highlighting with your mouse)

Tim's method works perfectly for my case - selecting the text in a div for both IE and FF after I replaced the following statement:

range.moveToElementText(text);

with the following:

range.moveToElementText(el);

The text in the div is selected by clicking it with the following jQuery function:

$(function () {
    $("#divFoo").click(function () {
        selectElementText(document.getElementById("divFoo"));
    })
});

Change tab bar item selected color in a storyboard

Swift 3 | Xcode 10

If you want to make all tab bar items the same color (selected & unselected)...


Step 1

Make sure your image assets are setup to Render As = Template Image. This allows them to inherit color.

Xcode Assets


Step 2

Use the storyboard editor to change your tab bar settings as follows:

  • Set Tab Bar: Image Tint to the color you want the selected icon to inherit.
  • Set Tab Bar: Bar Tint to the color you want the tab bar to be.
  • Set View: Tint to the color you want to see in the storyboard editor, this doesn't affect the icon color when your app is run.

Xcode Storyboard Editor


Step 3

Steps 1 & 2 will change the color for the selected icon. If you still want to change the color of the unselected items, you need to do it in code. I haven't found a way to do it via the storyboard editor.

Create a custom tab bar controller class...

//  TabBarController.swift

class TabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // make unselected icons white
        self.tabBar.unselectedItemTintColor = UIColor.white
    }
}

... and assign the custom class to your tab bar scene controller.

Xcode Storyboard Editor


If you figure out how to change the unselected icon color via the storyboard editor please let me know. Thanks!

How to sort a data frame by date

Nowadays, it is the most efficient and comfortable to use lubridate and dplyr libraries.

lubridate contains a number of functions that make parsing dates into POSIXct or Date objects easy. Here we use dmy which automatically parses dates in Day, Month, Year formats. Once your data is in a date format, you can sort it with dplyr::arrange (or any other ordering function) as desired:

d$V3 <- lubridate::dmy(d$V3)
dplyr::arrange(d, V3)

What does the "+=" operator do in Java?

It is XOR operator. It is use to do bit operations on numbers. It has the behavior such that when you do a xor operation on same bits say 0 XOR 0 / 1 XOR 1 the result is 0. But if any of the bits is different then result is 1. So when you did 5^3 then you can look at these numbers 5, 6 in their binary forms and thus the expression becomes (101) XOR (110) which gives the result (011) whose decimal representation is 3.

How can I create persistent cookies in ASP.NET?

FWIW be very careful with storing something like a userid in a cookie unencrypted. Doing this makes your site very prone to cookie poisoning where users can easily impersonate another user. If you are considering something like this I would highly recommend using the forms authentication cookie directly.

bool persist = true;

var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist);

cookie.Expires = DateTime.Now.AddMonths(3);

var ticket = FormsAuthentication.Decrypt(cookie.Value);

var userData = "store any string values you want inside the ticket
                 extra than user id that will be encrypted"

var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
     ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);

cookie.Value = FormsAuthentication.Encrypt(newTicket);

Response.Cookies.Add(cookie);

Then you can read this at any time from an ASP.NET page by doing

string userId = null;
if (this.Context.User.Identity.IsAuthenticated) 
{
    userId = this.Context.User.Identity.Name;
}

Python vs. Java performance (runtime speed)

If you ignore the characteristics of both languages, how do you define "SPEED"? Which features should be in your benchmark and which do you want to omit?

For example:

  • Does it count when Java executes an empty loop faster than Python?
  • Or is Python faster when it notices that the loop body is empty, the loop header has no side effects and it optimizes the whole loop away?
  • Or is that "a language characteristic"?
  • Do you want to know how many bytecodes each language can execute per second?
  • Which ones? Only the fast ones or all of them?
  • How do you count the Java VM JIT compiler which turns bytecode into CPU-specific assembler code at runtime?
  • Do you include code compilation times (which are extra in Java but always included in Python)?

Conclusion: Your question has no answer because it isn't defined what you want. Even if you made it more clear, the question will probably become academic since you will measure something that doesn't count in real life. For all of my projects, both Java and Python have always been fast enough. Of course, I would prefer one language over the other for a specific problem in a certain context.

Using Mockito's generic "any()" method

You can use Mockito.isA() for that:

import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;

verify(bar).doStuff(isA(Foo[].class));

http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html#isA(java.lang.Class)

Android Studio : unmappable character for encoding UTF-8

In Android Studio resolved it by

  1. Navigate to File > Editor > File Encodings.
  2. In global encoding set the encoding to ISO-8859-1
  3. In Project encoding set the encoding to UTF-8 and the same case to Default encoding for properties files.
  4. Rebuild project.

While loop in batch

@echo off

set countfiles=10

:loop

set /a countfiles -= 1

echo hi

if %countfiles% GTR 0 goto loop

pause

on the first "set countfiles" the 10 you see is the amount it will loop the echo hi is the thing you want to loop

...i'm 5 years late

Remove all multiple spaces in Javascript and replace with single space

You could use a regular expression replace:

str = str.replace(/ +(?= )/g,'');

Credit: The above regex was taken from Regex to replace multiple spaces with a single space

Getting an error "fopen': This function or variable may be unsafe." when compling

This is a warning for usual. You can either disable it by

#pragma warning(disable:4996)

or simply use fopen_s like Microsoft has intended.

But be sure to use the pragma before other headers.

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

Please note that PrimeFaces supports the standard JSF 2.0+ keywords:

  • @this Current component.
  • @all Whole view.
  • @form Closest ancestor form of current component.
  • @none No component.

and the standard JSF 2.3+ keywords:

  • @child(n) nth child.
  • @composite Closest composite component ancestor.
  • @id(id) Used to search components by their id ignoring the component tree structure and naming containers.
  • @namingcontainer Closest ancestor naming container of current component.
  • @parent Parent of the current component.
  • @previous Previous sibling.
  • @next Next sibling.
  • @root UIViewRoot instance of the view, can be used to start searching from the root instead the current component.

But, it also comes with some PrimeFaces specific keywords:

  • @row(n) nth row.
  • @widgetVar(name) Component with given widgetVar.

And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass:

process="@(.myClass :input)"

See:

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

Difference between one-to-many and many-to-one relationship

one-to-many has parent class contains n number of childrens so it is a collection mapping.

many-to-one has n number of childrens contains one parent so it is a object mapping

How can I group data with an Angular filter?

In addition to the accepted answer you can use this if you want to group by multiple columns:

<ul ng-repeat="(key, value) in players | groupBy: '[team,name]'">

AngularJS - Multiple ng-view in single template

You can have just one ng-view.

You can change its content in several ways: ng-include, ng-switch or mapping different controllers and templates through the routeProvider.

What is sys.maxint in Python 3?

As pointed out by others, Python 3's int does not have a maximum size, but if you just need something that's guaranteed to be higher than any other int value, then you can use the float value for Infinity, which you can get with float("inf").

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());

Also see this related question.

Difference between static and shared libraries?

Shared libraries are .so (or in Windows .dll, or in OS X .dylib) files. All the code relating to the library is in this file, and it is referenced by programs using it at run-time. A program using a shared library only makes reference to the code that it uses in the shared library.

Static libraries are .a (or in Windows .lib) files. All the code relating to the library is in this file, and it is directly linked into the program at compile time. A program using a static library takes copies of the code that it uses from the static library and makes it part of the program. [Windows also has .lib files which are used to reference .dll files, but they act the same way as the first one].

There are advantages and disadvantages in each method:

  • Shared libraries reduce the amount of code that is duplicated in each program that makes use of the library, keeping the binaries small. It also allows you to replace the shared object with one that is functionally equivalent, but may have added performance benefits without needing to recompile the program that makes use of it. Shared libraries will, however have a small additional cost for the execution of the functions as well as a run-time loading cost as all the symbols in the library need to be connected to the things they use. Additionally, shared libraries can be loaded into an application at run-time, which is the general mechanism for implementing binary plug-in systems.

  • Static libraries increase the overall size of the binary, but it means that you don't need to carry along a copy of the library that is being used. As the code is connected at compile time there are not any additional run-time loading costs. The code is simply there.

Personally, I prefer shared libraries, but use static libraries when needing to ensure that the binary does not have many external dependencies that may be difficult to meet, such as specific versions of the C++ standard library or specific versions of the Boost C++ library.

C# equivalent of C++ vector, with contiguous memory?

You could use a List<T> and when T is a value type it will be allocated in contiguous memory which would not be the case if T is a reference type.

Example:

List<int> integers = new List<int>();
integers.Add(1);
integers.Add(4);
integers.Add(7);

int someElement = integers[1];

html5: display video inside canvas

You need to update currentTime video element and then draw the frame in canvas. Don't init play() event on the video.

You can also use for ex. this plugin https://github.com/tstabla/stVideo

Python: 'ModuleNotFoundError' when trying to import module from imported package

For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.

Convert an image to grayscale

None of the examples above create 8-bit (8bpp) bitmap images. Some software, such as image processing, only supports 8bpp. Unfortunately the MS .NET libraries do not have a solution. The PixelFormat.Format8bppIndexed format looks promising but after a lot of attempts I couldn't get it working.

To create a true 8-bit bitmap file you need to create the proper headers. Ultimately I found the Grayscale library solution for creating 8-bit bitmap (BMP) files. The code is very simple:

Image image = Image.FromFile("c:/path/to/image.jpg");
GrayBMP_File.CreateGrayBitmapFile(image, "c:/path/to/8bpp/image.bmp");

The code for this project is far from pretty but it works, with one little simple-to-fix problem. The author hard-coded the image resolution to 10x10. Image processing programs do not like this. The fix is open GrayBMP_File.cs (yeah, funky file naming, I know) and replace lines 50 and 51 with the code below. The example sets the resolution to 200x200 but you should change it to the proper number.

int resX = 200;
int resY = 200;
// horizontal resolution
Copy_to_Index(DIB_header, BitConverter.GetBytes(resX * 100), 24);
// vertical resolution 
Copy_to_Index(DIB_header, BitConverter.GetBytes(resY * 100), 28);

Adding a leading zero to some values in column in MySQL

Possibly:

select lpad(column, 8, 0) from table;

Edited in response to question from mylesg, in comments below:

ok, seems to make the change on the query- but how do I make it stick (change it) permanently in the table? I tried an UPDATE instead of SELECT

I'm assuming that you used a query similar to:

UPDATE table SET columnName=lpad(nums,8,0);

If that was successful, but the table's values are still without leading-zeroes, then I'd suggest you probably set the column as a numeric type? If that's the case then you'd need to alter the table so that the column is of a text/varchar() type in order to preserve the leading zeroes:

First:

ALTER TABLE `table` CHANGE `numberColumn` `numberColumn` CHAR(8);

Second, run the update:

UPDATE table SET `numberColumn`=LPAD(`numberColum`, 8, '0');

This should, then, preserve the leading-zeroes; the down-side is that the column is no longer strictly of a numeric type; so you may have to enforce more strict validation (depending on your use-case) to ensure that non-numerals aren't entered into that column.

References:

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

Use window.URL:

> s = 'http://www.example.com/index.html?1111342=Adam%20Franco&348572=Bob%20Jones'
> u = new URL(s)
> Array.from(u.searchParams.entries())
[["1111342", "Adam Franco"], ["348572", "Bob Jones"]]

Update multiple rows with different values in a single SQL query

Something like this might work for you:

"UPDATE myTable SET ... ;
 UPDATE myTable SET ... ;
 UPDATE myTable SET ... ;
 UPDATE myTable SET ... ;"

If any of the posX or posY values are the same, then they could be combined into one query

UPDATE myTable SET posX='39' WHERE id IN('2','3','40');

What is difference between @RequestBody and @RequestParam?

@RequestParam annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type. This annotation indicates that a method parameter should be bound to a web request parameter.

For example Angular request for Spring RequestParam(s) would look like that:

$http.post('http://localhost:7777/scan/l/register?username="Johny"&password="123123"&auth=true')
      .success(function (data, status, headers, config) {
                        ...
                    })

Endpoint with RequestParam:

@RequestMapping(method = RequestMethod.POST, value = "/register")
public Map<String, String> register(Model uiModel,
                                    @RequestParam String username,
                                    @RequestParam String password,
                                    @RequestParam boolean auth,
                                    HttpServletRequest httpServletRequest) {...

@RequestBody annotated parameters get linked to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters. This annotation indicates a method parameter should be bound to the body of the web request.

For example Angular request for Spring RequestBody would look like that:

$scope.user = {
            username: "foo",
            auth: true,
            password: "bar"
        };    
$http.post('http://localhost:7777/scan/l/register', $scope.user).
                        success(function (data, status, headers, config) {
                            ...
                        })

Endpoint with RequestBody:

@RequestMapping(method = RequestMethod.POST, produces = "application/json", 
                value = "/register")
public Map<String, String> register(Model uiModel,
                                    @RequestBody User user,
                                    HttpServletRequest httpServletRequest) {... 

Hope this helps.

SQL Server convert select a column and convert it to a string

ALTER PROCEDURE [dbo].[spConvertir_CampoACadena]( @nomb_tabla   varchar(30),
                          @campo_tabla  varchar(30),
                          @delimitador  varchar(5),
                          @respuesta    varchar(max) OUTPUT
)
AS
DECLARE @query      varchar(1000),
    @cadena     varchar(500)
BEGIN
  SET @query = 'SELECT @cadena  = COALESCE(@cadena + '''+ @delimitador +''', '+ '''''' +') + '+ @campo_tabla + ' FROM '+@nomb_tabla
  --select @query
  EXEC(@query)
  SET @respuesta = @cadena  
END

What is the iPhone 4 user-agent?

  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/7D11
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A306 Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B5097d Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2 like Mac OS X; en_us) AppleWebKit/525.18.1 (KHTML, like Gecko)
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5

...for now

jQuery.ajax handling continue responses: "success:" vs ".done"?

If you need async: false in your ajax, you should use success instead of .done. Else you better to use .done. This is from jQuery official site:

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().

Find child element in AngularJS directive

jQlite (angular's "jQuery" port) doesn't support lookup by classes.

One solution would be to include jQuery in your app.

Another is using QuerySelector or QuerySelectorAll:

link: function(scope, element, attrs) {
   console.log(element[0].querySelector('.list-scrollable'))
}

We use the first item in the element array, which is the HTML element. element.eq(0) would yield the same.

FIDDLE

ImportError: No module named xlsxwriter

Here are some easy way to get you up and running with the XlsxWriter module.The first step is to install the XlsxWriter module.The pip installer is the preferred method for installing Python modules from PyPI, the Python Package Index:

sudo pip install xlsxwriter

Note

Windows users can omit sudo at the start of the command.

How can I change the user on Git Bash?

For Mac Users

I am using Mac and I was facing same problem while I was trying to push a project from Android Studio. The reason for that other user had previously logged into Github and his credentials were saved in Keychain Access.

You need to remove those credentials from Keychain Access and then try to push.

Hope it help to Mac users.

Given an RGB value, how do I create a tint (or shade)?

I'm currently experimenting with canvas and pixels... I'm finding this logic works out for me better.

  1. Use this to calculate the grey-ness ( luma ? )
  2. but with both the existing value and the new 'tint' value
  3. calculate the difference ( I found I did not need to multiply )
  4. add to offset the 'tint' value

    var grey =  (r + g + b) / 3;    
    var grey2 = (new_r + new_g + new_b) / 3;
    
    var dr =  grey - grey2 * 1;    
    var dg =  grey - grey2 * 1    
    var db =  grey - grey2 * 1;  
    
    tint_r = new_r + dr;    
    tint_g = new_g + dg;   
    tint_b = new_b _ db;
    

or something like that...

Sequence contains no matching element

Maybe using Where() before First() can help you, as my problem has been solved in this case.

var documentRow = _dsACL.Documents.Where(o => o.ID == id).FirstOrDefault();

Firebase FCM notifications click_action payload

If your app is in background, Firebase will not trigger onMessageReceived(). Why.....? I have no idea. In this situation, I do not see any point in implementing FirebaseMessagingService.

According to docs, if you want to process background message arrival, you have to send 'click_action' with your message. But it is not possible if you send message from Firebase console, only via Firebase API. It means you will have to build your own "console" in order to enable marketing people to use it. So, this makes Firebase console also quite useless!

There is really good, promising, idea behind this new tool, but executed badly.

I suppose we will have to wait for new versions and improvements/fixes!

Multithreading in Bash

Bash job control involves multiple processes, not multiple threads.

You can execute a command in background with the & suffix.

You can wait for completion of a background command with the wait command.

You can execute multiple commands in parallel by separating them with |. This provides also a synchronization mechanism, since stdout of a command at left of | is connected to stdin of command at right.

RunAs A different user when debugging in Visual Studio

I'm using the following method based on @Watki02's answer:

  1. Shift r-click the application to debug
  2. Run as different user
  3. Attach the debugger to the application

That way you can keep your visual studio instance as your own user whilst debugging from the other.

XML serialization in Java?

"Simple XML Serialization" Project

You may want to look at the Simple XML Serialization project. It is the closest thing I've found to the System.Xml.Serialization in .Net.

How to update large table with millions of rows in SQL Server?

First of all, thank you all for your inputs. I tweak my Query - 1 and got my desired result. Gordon Linoff is right, PRINT was messing up my query so I modified it as following:

Modified Query - 1:

SET ROWCOUNT 5
WHILE (1 = 1)
  BEGIN
    BEGIN TRANSACTION

        UPDATE TableName 
        SET Value = 'abc1' 
        WHERE Parameter1 = 'abc' AND Parameter2 = 123

        IF @@ROWCOUNT = 0
          BEGIN
                COMMIT TRANSACTION
                BREAK
          END
    COMMIT TRANSACTION
  END
SET ROWCOUNT  0

Output:

(5 row(s) affected)

(5 row(s) affected)

(4 row(s) affected)

(0 row(s) affected)

How to hide output of subprocess in Python 2.7

Redirect the output to DEVNULL:

import os
import subprocess

FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['echo', 'foo'], 
    stdout=FNULL, 
    stderr=subprocess.STDOUT)

It is effectively the same as running this shell command:

retcode = os.system("echo 'foo' &> /dev/null")

Update: This answer applies to the original question relating to python 2.7. As of python >= 3.3 an official subprocess.DEVNULL symbol was added.

retcode = subprocess.call(['echo', 'foo'], 
    stdout=subprocess.DEVNULL, 
    stderr=subprocess.STDOUT)

Prevent flex items from overflowing a container

If you want the overflow to wrap: flex-flow: row wrap

How to fix div on scroll

(function($) {
  var triggers = [];
  $.fn.floatingFixed = function(options) {
    options = $.extend({}, $.floatingFixed.defaults, options);
    var r = $(this).each(function() {
      var $this = $(this), pos = $this.position();
      pos.position = $this.css("position");
      $this.data("floatingFixedOrig", pos);
      $this.data("floatingFixedOptions", options);
      triggers.push($this);
    });
    windowScroll();
    return r;
  };

  $.floatingFixed = $.fn.floatingFixed;
  $.floatingFixed.defaults = {
    padding: 0
  };

  var $window = $(window);
  var windowScroll = function() {
    if(triggers.length === 0) { return; }
    var scrollY = $window.scrollTop();
    for(var i = 0; i < triggers.length; i++) {
      var t = triggers[i], opt = t.data("floatingFixedOptions");
      if(!t.data("isFloating")) {
        var off = t.offset();
        t.data("floatingFixedTop", off.top);
        t.data("floatingFixedLeft", off.left);
      }
      var top = top = t.data("floatingFixedTop");
      if(top < scrollY + opt.padding && !t.data("isFloating")) {
        t.css({position: 'fixed', top: opt.padding, left: t.data("floatingFixedLeft"), width: t.width() }).data("isFloating", true);
      } else if(top >= scrollY + opt.padding && t.data("isFloating")) {
        var pos = t.data("floatingFixedOrig");
        t.css(pos).data("isFloating", false);
      }
    }
  };

  $window.scroll(windowScroll).resize(windowScroll);
})(jQuery);

and then make any div as floating fixed by calling

$('#id of the div').floatingFixed();

source: https://github.com/cheald/floatingFixed

The Completest Cocos2d-x Tutorial & Guide List

Good list. The Angry Ninjas Starter Kit will have a Cocos2d-X update soon.

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

It means you don't have privileges to create the trigger with root@localhost user..

try removing definer from the trigger command:

CREATE DEFINER = root@localhost FUNCTION fnc_calcWalkedDistance

Unordered List (<ul>) default indent

If you don't want indention in your list and also don't care about or don't want bullets, there is the CSS-free option of using a "definition list" (HTML 4.01) or "description list" (HTML 5). Use only the non-indenting definition <dt> tags, but not the indenting description <dd> tags, neither of which produces a bullet.

<dl>
  <dt>Item 1</dt>
  <dt>Item 2</dt>
  <dt>Item 3</dt>
</dl>

The output looks like this:

Item 1
Item 2
Item 3

Import data.sql MySQL Docker Container

you can copy the export file for e.g dump.sql using docker cp into the container and then import the db. if you need full instructions, let me know and I will provide

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

What you need is the svn 'export' command. With this you can put a file or entire directory tree in the state of another revision in another branch.

So something like

rm file #without 'svn' in front!
svn export myrepo/path/to/file@<revision> .
svn commit

Html.RenderPartial() syntax with Razor

  • RenderPartial() is a void method that writes to the response stream. A void method, in C#, needs a ; and hence must be enclosed by { }.

  • Partial() is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a @ prefix to distinguish it from plain HTML you have on the page.

How does cellForRowAtIndexPath work?

I'll try and break it down (example from documention)

/* 
 *   The cellForRowAtIndexPath takes for argument the tableView (so if the same object
 *   is delegate for several tableViews it can identify which one is asking for a cell),
 *   and an indexPath which determines which row and section the cell is returned for. 
 */ 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    /*
     *   This is an important bit, it asks the table view if it has any available cells
     *   already created which it is not using (if they are offScreen), so that it can
     *   reuse them (saving the time of alloc/init/load from xib a new cell ).
     *   The identifier is there to differentiate between different types of cells
     *   (you can display different types of cells in the same table view)
     */

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    /*
     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
     */
    if (cell == nil) {

        /* 
         *   Actually create a new cell (with an identifier so that it can be dequeued). 
         */

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    /*
     *   Now that we have a cell we can configure it to display the data corresponding to
     *   this row/section
     */

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
    UIImage *theImage = [UIImage imageWithContentsOfFile:path];
    cell.imageView.image = theImage;

    /* Now that the cell is configured we return it to the table view so that it can display it */

    return cell;

}

This is a DataSource method so it will be called on whichever object has declared itself as the DataSource of the UITableView. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).

Fit background image to div

You can achieve this with the background-size property, which is now supported by most browsers.

To scale the background image to fit inside the div:

background-size: contain;

To scale the background image to cover the whole div:

background-size: cover;

JSFiddle example

There also exists a filter for IE 5.5+ support, as well as vendor prefixes for some older browsers.

Print values for multiple variables on the same line from within a for-loop

As an additional note, there is no need for the for loop because of R's vectorization.

This:

P <- 243.51
t <- 31 / 365
n <- 365

for (r in seq(0.15, 0.22, by = 0.01))    
     A <- P * ((1 + (r/ n))^ (n * t))
     interest <- A - P
}

is equivalent to:

P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P

Because r is a vector, the expression above containing it is performed for all values of the vector.

What are Bearer Tokens and token_type in OAuth 2?

Anyone can define "token_type" as an OAuth 2.0 extension, but currently "bearer" token type is the most common one.

https://tools.ietf.org/html/rfc6750

Basically that's what Facebook is using. Their implementation is a bit behind from the latest spec though.

If you want to be more secure than Facebook (or as secure as OAuth 1.0 which has "signature"), you can use "mac" token type.

However, it will be hard way since the mac spec is still changing rapidly.

https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-05

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 clone a generic List in Java?

This should also work:

ArrayList<String> orig = new ArrayList<String>();
ArrayList<String> copy = (ArrayList<String>) orig.clone()

MySQL: Insert record if not exists in table

I'm not actually suggesting that you do this, as the UNIQUE index as suggested by Piskvor and others is a far better way to do it, but you can actually do what you were attempting:

CREATE TABLE `table_listnames` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `tele` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

Insert a record:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `table_listnames`;

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Rupert | Somewhere | 022  |
+----+--------+-----------+------+

Try to insert the same record again:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Rupert | Somewhere | 022  |
+----+--------+-----------+------+

Insert a different record:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'John', 'Doe', '022') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'John'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `table_listnames`;

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Rupert | Somewhere | 022  |
|  2 | John   | Doe       | 022  |
+----+--------+-----------+------+

And so on...


Update:

To prevent #1060 - Duplicate column name error in case two values may equal, you must name the columns of the inner SELECT:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Unknown' AS name, 'Unknown' AS address, '022' AS tele) AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `table_listnames`;

+----+---------+-----------+------+
| id | name    | address   | tele |
+----+---------+-----------+------+
|  1 | Rupert  | Somewhere | 022  |
|  2 | John    | Doe       | 022  |
|  3 | Unknown | Unknown   | 022  |
+----+---------+-----------+------+

How to make (link)button function as hyperlink?

This can be done very easily using a PostBackUrl and a regular button.

<asp:Button ID="Button1" runat="server" Text="Name of web location" PostBackUrl="web address" />

Node JS Error: ENOENT

change

"/tmp/test.jpg".

to

"./tmp/test.jpg"

How can I use UserDefaults in Swift?

Swift 4 :

Store

    UserDefaults.standard.set(object/value, forKey: "key_name")

Retrive

    var returnValue: [datatype]? = UserDefaults.standard.object(forKey: "key_name") as? [datatype]

Remove

    UserDefaults.standard.removeObject(forKey:"key_name") 

How to Generate a random number of fixed length using JavaScript?

For the length of 6, recursiveness doesn't matter a lot.

_x000D_
_x000D_
function random(len) {_x000D_
  let result = Math.floor(Math.random() * Math.pow(10, len));_x000D_
_x000D_
  return (result.toString().length < len) ? random(len) : result;_x000D_
}_x000D_
_x000D_
console.log(random(6));
_x000D_
_x000D_
_x000D_

What are the ways to make an html link open a folder

A bit late to the party, but I had to solve this for myself recently, though slightly different, it might still help someone with similar circumstances to my own.

I'm using xampp on a laptop to run a purely local website app on windows. (A very specific environment I know). In this instance, I use a html link to a php file and run:

shell_exec('cd C:\path\to\file');
shell_exec('start .');

This opens a local Windows explorer window.

Problems with a PHP shell script: "Could not open input file"

For me the problem was I had to use /usr/bin/php-cgi command instead of just /usr/bin/php

php-cgi is the command run when accessed thru web browser.

php is the CLI command line command.

Not sure why php cli is not working, but running with php-cgi instead fixed the problem for me.

The requested operation cannot be performed on a file with a user-mapped section open

I encountered this error and it turned out the issue was FxCop was running against my project. I closed FxCop and then I could compile again.

Jenkins restrict view of jobs per user

Try going to "Manage Jenkins"->"Manage Users" go to the specific user, edit his/her configuration "My Views section" default view.

In MySQL, how to copy the content of one table to another table within the same database?

Try this. Works well in my Oracle 10g,

CREATE TABLE new_table
  AS (SELECT * FROM old_table);

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

this works for me:

myTuple= tuple(myList)
sql="select fooid from foo where bar in "+str(myTuple)
cursor.execute(sql)

How to impose maxlength on textArea in HTML using JavaScript

Update Use Eirik's solution using .live() instead as it is a bit more robust.


Even though you wanted a solution that wasn't using jQuery, I thought I'd add one in for anyone finding this page via Google and looking for a jQuery-esque solution:

$(function() {        
    // Get all textareas that have a "maxlength" property.
    $('textarea[maxlength]').each(function() {

        // Store the jQuery object to be more efficient...
        var $textarea = $(this);

        // Store the maxlength and value of the field.
        var maxlength = $textarea.attr('maxlength');
        var val = $textarea.val();

        // Trim the field if it has content over the maxlength.
        $textarea.val(val.slice(0, maxlength));

        // Bind the trimming behavior to the "keyup" event.
        $textarea.bind('keyup', function() {
            $textarea.val($textarea.val().slice(0, maxlength));
        });

    });
});

Hope that is useful to you Googlers out there...

scale Image in an UIButton to AspectFit?

If you really want to scale an image, do it, but you should resize it before using it. Resizing it at run time will just lose CPU cycles.

This is the category I'm using to scale an image :

UIImage+Extra.h

@interface UIImage (Extras)
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
@end;

UIImage+Extra.m

@implementation UIImage (Extras)

- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {

UIImage *sourceImage = self;
UIImage *newImage = nil;

CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;

CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;

CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;

CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

if (!CGSizeEqualToSize(imageSize, targetSize)) {

        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor < heightFactor) 
                scaleFactor = widthFactor;
        else
                scaleFactor = heightFactor;

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image

        if (widthFactor < heightFactor) {
                thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
        } else if (widthFactor > heightFactor) {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
}


// this is actually the interesting part:

UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0);

CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width  = scaledWidth;
thumbnailRect.size.height = scaledHeight;

[sourceImage drawInRect:thumbnailRect];

newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

if(newImage == nil) NSLog(@"could not scale image");


return newImage ;
}

@end

You can use it to the size you want. Like :

[self.itemImageButton setImage:[stretchImage imageByScalingProportionallyToSize:CGSizeMake(20,20)]];

Detecting an "invalid date" Date instance in JavaScript

Nice solution! Included in my library of auxiliary functions, now it looks like this:

Object.isDate = function(obj) {
/// <summary>
/// Determines if the passed object is an instance of Date.
/// </summary>
/// <param name="obj">The object to test.</param>

    return Object.prototype.toString.call(obj) === '[object Date]';
}

Object.isValidDate = function(obj) {
/// <summary>
/// Determines if the passed object is a Date object, containing an actual date.
/// </summary>
/// <param name="obj">The object to test.</param>

    return Object.isDate(obj) && !isNaN(obj.getTime());
}

How to set Grid row and column positions programmatically

Here is an example which might help someone:

Grid test = new Grid();
test.ColumnDefinitions.Add(new ColumnDefinition());
test.ColumnDefinitions.Add(new ColumnDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());

Label t1 = new Label();
t1.Content = "Test1";
Label t2 = new Label();
t2.Content = "Test2";
Label t3 = new Label();
t3.Content = "Test3";
Label t4 = new Label();
t4.Content = "Test4";
Label t5 = new Label();
t5.Content = "Test5";
Label t6 = new Label();
t6.Content = "Test6";

Grid.SetColumn(t1, 0);
Grid.SetRow(t1, 0);
test.Children.Add(t1);

Grid.SetColumn(t2, 1);
Grid.SetRow(t2, 0);
test.Children.Add(t2);

Grid.SetColumn(t3, 0);
Grid.SetRow(t3, 1);
test.Children.Add(t3);

Grid.SetColumn(t4, 1);
Grid.SetRow(t4, 1);
test.Children.Add(t4);

Grid.SetColumn(t5, 0);
Grid.SetRow(t5, 2);
test.Children.Add(t5);

Grid.SetColumn(t6, 1);
Grid.SetRow(t6, 2);
test.Children.Add(t6);

How can I return pivot table output in MySQL?

One option would be combining use of CASE..WHEN statement is redundant within an aggregation for MySQL Database, and considering the needed query generation dynamically along with getting proper column title for the result set as in the following code block :

SET @sql = NULL;

SELECT GROUP_CONCAT(
             CONCAT('SUM( `action` = ''', action, '''',pc0,' ) AS ',action,pc1)
       )
  INTO @sql
  FROM 
  ( 
   SELECT DISTINCT `action`, 
          IF(`pagecount` IS NULL,'',CONCAT('page',`pagecount`)) AS pc1,
          IF(`pagecount` IS NULL,'',CONCAT(' AND `pagecount` = ', pagecount, '')) AS pc0
     FROM `tab` 
    ORDER BY CONCAT(action,pc0) 
  ) t;

SET @sql = CONCAT('SELECT company_name,',@sql,' FROM `tab` GROUP BY company_name'); 
SELECT @sql; 

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Demo

Application not picking up .css file (flask/python)

You need to have a 'static' folder setup (for css/js files) unless you specifically override it during Flask initialization. I am assuming you did not override it.

Your directory structure for css should be like:

/app
    - app_runner.py
    /services
        - app.py 
    /templates
        - mainpage.html
    /static
        /styles
            - mainpage.css

Notice that your /styles directory should be under /static

Then, do this

<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/mainpage.css') }}">

Flask will now look for the css file under static/styles/mainpage.css

Add a new column to existing table in a migration

First rollback your previous migration

php artisan migrate:rollback

After that, you can modify your existing migration file (add new , rename or delete columns) then Re-Run your migration file

php artisan migrate

Checkout multiple git repos into same Jenkins workspace

Jenkins: Multiple SCM - deprecated. GIT Plugin - doesn't work for multiple repos.

Scripting / pipeline as code - is the way to go.

Connect Bluestacks to Android Studio

In my case I didn't needed start adb.exe. I only started the BlueStacks before android studio.

After that when I press "Run" in android studio, bluestacks is detected as a new emulator.

enter image description here

enter image description here

Regards.

Problem with converting int to string in Linq to entities

I ran into this same problem when I was converting my MVC 2 app to MVC 3 and just to give another (clean) solution to this problem I want to post what I did...

IEnumerable<SelectListItem> producers = new SelectList(Services.GetProducers(),
    "ID", "Name", model.ProducerID);

GetProducers() simply returns an entity collection of Producers. P.S. The SqlFunctions.StringConvert didn't work for me.

JavaFX How to set scene background image

One of the approaches may be like this:

1) Create a CSS file with name "style.css" and define an id selector in it:

#pane{
    -fx-background-image: url("background_image.jpg");
    -fx-background-repeat: stretch;   
    -fx-background-size: 900 506;
    -fx-background-position: center center;
    -fx-effect: dropshadow(three-pass-box, black, 30, 0.5, 0, 0); 
}

2) Set the id of the most top control (or any control) in the scene with value defined in CSS and load this CSS file into the scene:

  public class Test extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();
        root.setId("pane");
        Scene scene = new Scene(root, 300, 250);
        scene.getStylesheets().addAll(this.getClass().getResource("style.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

You can also give an id to the control in a FXML file:

<StackPane id="pane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="demo.Sample">
    <children>
    </children>
</StackPane>

For more info about JavaFX CSS Styling refer to this guide.

Convert long/lat to pixel x/y on a given picture

my approach works without a library and with cropped maps. Means it works with just parts from a Mercator image. Maybe it helps somebody: https://stackoverflow.com/a/10401734/730823

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

I solved the problem updating all packages from Android SDK Manager and also, I had to install Extras -> Android Support Repository.

Remove 'b' character do in front of a string literal in Python 3

This should do the trick:

pw_bytes.decode("utf-8")

Command for restarting all running docker containers?

Just run

docker restart $(docker ps -q)

Update

For Docker 1.13.1 use docker restart $(docker ps -a -q) as in answer lower.

What is the difference between $routeProvider and $stateProvider?

Angular's own ng-Router takes URLs into consideration while routing, UI-Router takes states in addition to URLs.

States are bound to named, nested and parallel views, allowing you to powerfully manage your application's interface.

While in ng-router, you have to be very careful about URLs when providing links via <a href=""> tag, in UI-Router you have to only keep state in mind. You provide links like <a ui-sref="">. Note that even if you use <a href=""> in UI-Router, just like you would do in ng-router, it will still work.

So, even if you decide to change your URL some day, your state will remain same and you need to change URL only at .config.

While ngRouter can be used to make simple apps, UI-Router makes development much easier for complex apps. Here its wiki.

How to get the html of a div on another page with jQuery ajax?

Unfortunately an ajax request gets the entire file, but you can filter the content once it's retrieved:

$.ajax({
   url:href,
   type:'GET',
   success: function(data) {
       var content = $('<div>').append(data).find('#content');
       $('#content').html( content );
   }
});

Note the use of a dummy element as find() only works with descendants, and won't find root elements.

or let jQuery filter it for you:

$('#content').load(href + ' #IDofDivToFind');

I'm assuming this isn't a cross domain request, as that won't work, only pages on the same domain.

"Continue" (to next iteration) on VBScript

I think you are intended to contain ALL YOUR LOGIC under your if statement. Basically:

' PRINTS EVERYTHING EXCEPT 4
For i = 0 To 10
  ' you want to say
  ' If i = 4 CONTINUE but VBScript has no continue
  If i <> 4 Then ' just invert the logic
    WSH.Echo( i )
  End If
Next

This can make the code a bit longer, but some people don't like break or continue anyway.

how to parse xml to java object?

One thing that is really important to understand considering you have an XML file as :

<customer id="100">
    <Age>29</Age>
    <NAME>mkyong</NAME>
</customer>

I am sorry to inform you but :

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

will not help you, as it tries to look for "age" instead of "Age" element name from the XML.

I encourage you to manually specify the element name matching the one in the XML file :

@XmlElement(name="Age")
public void setAge(int age) {
    this.age = age;
}

And if you have for example :

@XmlRootElement
@XmlAccessorType (XmlAccessType.FIELD)
public class Customer {
...

It means it will use java beans by default, and at this time if you specify that you must not set another

@XmlElement(name="NAME")

annotation above a setter method for an element <NAME>..</NAME> it will fail saying that there cannot be two elements on one single variables.

I hope that it helps.

iPhone X / 8 / 8 Plus CSS media queries

It seems that the most accurate (and seamless) method of adding the padding for iPhone X/8 using env()...

padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);

Here's a link describing this:

https://css-tricks.com/the-notch-and-css/

What is the cleanest way to ssh and run multiple commands in Bash?

The easiest way to configure your system to use single ssh sessions by default with multiplexing.

This can be done by creating a folder for the sockets:

mkdir ~/.ssh/controlmasters

And then adding the following to your .ssh configuration:

Host *
    ControlMaster auto
    ControlPath ~/.ssh/controlmasters/%r@%h:%p.socket
    ControlMaster auto
    ControlPersist 10m

Now, you do not need to modify any of your code. This allows multiple calls to ssh and scp without creating multiple sessions, which is useful when there needs to be more interaction between your local and remote machines.

Thanks to @terminus's answer, http://www.cyberciti.biz/faq/linux-unix-osx-bsd-ssh-multiplexing-to-speed-up-ssh-connections/ and https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Multiplexing.

Finding repeated words on a string and counting the repetitions

Once you have got the words from the string it is easy. From Java 10 onwards you can try the following code:

import java.util.Arrays;
import java.util.stream.Collectors;

public class StringFrequencyMap {
    public static void main(String... args) {
        String[] wordArray = {"House", "House", "House", "Dog", "Dog", "Dog", "Dog"};
        var freq = Arrays.stream(wordArray)
                         .collect(Collectors.groupingBy(x -> x, Collectors.counting()));
        System.out.println(freq);
    }
}

Output:

{House=3, Dog=4}

How to draw a filled triangle in android canvas?

You probably need to do something like :

Paint red = new Paint();

red.setColor(android.graphics.Color.RED);
red.setStyle(Paint.Style.FILL);

And use this color for your path, instead of your ARGB. Make sure the last point of your path ends on the first one, it makes sense also.

Tell me if it works please !

MongoDB not equal to

If there is a null in an array and you want to avoid it:

db.test.find({"contain" : {$ne :[] }}).pretty()

Printing a char with printf

In C, character constant expressions such as '\n' or 'a' have type int (thus sizeof '\n' == sizeof (int)), whereas in C++ they have type char.

The statement printf("%d", '\0'); should simply print 0; the type of the expression '\0' is int, and its value is 0.

The statement printf("%d", ch); should print the integer encoding for the value in ch (for ASCII, 'a' == 97).

Compiling Java 7 code via Maven

{JAVA_1_4_HOME}/bin/javacyou can try also...

<plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
                <source>1.7</source>
                <target>1.7</target>
                <showDeprecation>true</showDeprecation>
                <showWarnings>true</showWarnings>
                <executable>{JAVA_HOME_1_7}/bin/javac</executable>
                <fork>true</fork>
        </configuration>
    </plugin>

I'm getting Key error in python

Let us make it simple if you're using Python 3

mydict = {'a':'apple','b':'boy','c':'cat'}
check = 'c' in mydict
if check:
    print('c key is present')

If you need else condition

mydict = {'a':'apple','b':'boy','c':'cat'}
if 'c' in mydict:
    print('key present')
else:
    print('key not found')

For the dynamic key value, you can also handle through try-exception block

mydict = {'a':'apple','b':'boy','c':'cat'}
try:
    print(mydict['c'])
except KeyError:
    print('key value not found')mydict = {'a':'apple','b':'boy','c':'cat'}

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

I faced similar problem. I solved it without using onload handler.I was working on AngularJs project so i used $interval and $ timeout. U can also use setTimeout and setInterval.Here's the code:

 var stopPolling;
 var doIframePolling;
 $scope.showIframe = true;
 doIframePolling = $interval(function () {
    if(document.getElementById('UrlIframe') && document.getElementById('UrlIframe').contentDocument.head && document.getElementById('UrlIframe').contentDocument.head.innerHTML != ''){
        $interval.cancel(doIframePolling);
        doIframePolling = undefined;
        $timeout.cancel(stopPolling);
        stopPolling = undefined;
        $scope.showIframe = true;
    }
},400);

stopPolling = $timeout(function () {
        $interval.cancel(doIframePolling);
        doIframePolling = undefined;
        $timeout.cancel(stopPolling);
        stopPolling = undefined;
        $scope.showIframe = false;     
},5000);

 $scope.$on("$destroy",function() {
        $timeout.cancel(stopPolling);
        $interval.cancel(doIframePolling);
 });

Every 0.4 Seconds keep checking the head of iFrame Document. I somthing is present.Loading was not stopped by CORS as CORS error shows blank page. If nothing is present after 5 seconds there was some error (Cors policy) etc.. Show suitable message.Thanks. I hope it solves your problem.

SecurityError: The operation is insecure - window.history.pushState()

We experienced the SecurityError: The operation is insecure when a user disabled their cookies prior to visiting our site, any subsequent XHR requests trying to use the session would obviously fail and cause this error.

Append value to empty vector in R?

Just for the sake of completeness, appending values to a vector in a for loop is not really the philosophy in R. R works better by operating on vectors as a whole, as @BrodieG pointed out. See if your code can't be rewritten as:

ouput <- sapply(values, function(v) return(2*v))

Output will be a vector of return values. You can also use lapply if values is a list instead of a vector.

Func vs. Action vs. Predicate

Func - When you want a delegate for a function that may or may not take parameters and returns a value. The most common example would be Select from LINQ:

var result = someCollection.Select( x => new { x.Name, x.Address });

Action - When you want a delegate for a function that may or may not take parameters and does not return a value. I use these often for anonymous event handlers:

button1.Click += (sender, e) => { /* Do Some Work */ }

Predicate - When you want a specialized version of a Func that evaluates a value against a set of criteria and returns a boolean result (true for a match, false otherwise). Again, these are used in LINQ quite frequently for things like Where:

var filteredResults = 
    someCollection.Where(x => x.someCriteriaHolder == someCriteria);

I just double checked and it turns out that LINQ doesn't use Predicates. Not sure why they made that decision...but theoretically it is still a situation where a Predicate would fit.

How can I nullify css property?

I had an issue that even when I did overwrite "height" to "unset" or "initial", it behaved differently from when I removed the previous setting.

It turned out I needed to remove the min-height property too!

height: unset;
min-height: none

Edit: I tested on IE 7 and it doesn't recognize "unset", so "auto" works better".

Redirect to an external URL from controller action in Spring MVC

Did you try RedirectView where you can provide the contextRelative parameter?

How to add comments into a Xaml file in WPF?

Found a nice solution by Laurent Bugnion, it can look something like this:

<UserControl xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:comment="Tag to add comments"
             mc:Ignorable="d comment" d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Button Width="100"
                comment:Width="example comment on Width, will be ignored......">
        </Button>
    </Grid>
</UserControl>

Here's the link: http://blog.galasoft.ch/posts/2010/02/quick-tip-commenting-out-properties-in-xaml/

A commenter on the link provided extra characters for the ignore prefix in lieu of highlighting:

mc:Ignorable=”ØignoreØ”

HTML form with two submit buttons and two "target" attributes

It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.

Anyhow, with that in mind, this should do it:

<form id='myform' action='jquery.php' method='GET'>
    <input type='submit' id='btn1' value='Normal Submit'>
    <input type='button' id='btn2' value='New Window'>
</form>

With this javascript:

var form = document.getElementById('myform');
form.onsubmit = function() {
    form.target = '_self';
};

document.getElementById('btn2').onclick = function() {
    form.target = '_blank';
    form.submit();
}

Approaches that bind code to the submit button's click event will not work on IE.

Using LINQ to concatenate strings

Here is the combined Join/Linq approach I settled on after looking at the other answers and the issues addressed in a similar question (namely that Aggregate and Concatenate fail with 0 elements).

string Result = String.Join(",", split.Select(s => s.Name));

or (if s is not a string)

string Result = String.Join(",", split.Select(s => s.ToString()));

  • Simple
  • easy to read and understand
  • works for generic elements
  • allows using objects or object properties
  • handles the case of 0-length elements
  • could be used with additional Linq filtering
  • performs well (at least in my experience)
  • doesn't require (manual) creation of an additional object (e.g. StringBuilder) to implement

And of course Join takes care of the pesky final comma that sometimes sneaks into other approaches (for, foreach), which is why I was looking for a Linq solution in the first place.

Android webview launches browser when calling loadurl

Make your Activity like this.

public class MainActivity extends Activity {
WebView browser;

@Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // find the WebView by name in the main.xml of step 2
    browser=(WebView)findViewById(R.id.wvwMain);

    // Enable javascript
    browser.getSettings().setJavaScriptEnabled(true);  

    // Set WebView client
    browser.setWebChromeClient(new WebChromeClient());

    browser.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
                }
        });
     // Load the webpage
    browser.loadUrl("http://google.com/");
   }
}

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

I'm going to expand your question a bit and also include the compile function.

  • compile function - use for template DOM manipulation (i.e., manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive. (If you also need a link function (or pre and post link functions), and you defined a compile function, the compile function must return the link function(s) because the 'link' attribute is ignored if the 'compile' attribute is defined.)

  • link function - normally use for registering listener callbacks (i.e., $watch expressions on the scope) as well as updating the DOM (i.e., manipulation of iElement = individual instance element). It is executed after the template has been cloned. E.g., inside an <li ng-repeat...>, the link function is executed after the <li> template (tElement) has been cloned (into an iElement) for that particular <li> element. A $watch allows a directive to be notified of scope property changes (a scope is associated with each instance), which allows the directive to render an updated instance value to the DOM.

  • controller function - must be used when another directive needs to interact with this directive. E.g., on the AngularJS home page, the pane directive needs to add itself to the scope maintained by the tabs directive, hence the tabs directive needs to define a controller method (think API) that the pane directive can access/call.

    For a more in-depth explanation of the tabs and pane directives, and why the tabs directive creates a function on its controller using this (rather than on $scope), please see 'this' vs $scope in AngularJS controllers.

In general, you can put methods, $watches, etc. into either the directive's controller or link function. The controller will run first, which sometimes matters (see this fiddle which logs when the ctrl and link functions run with two nested directives). As Josh mentioned in a comment, you may want to put scope-manipulation functions inside a controller just for consistency with the rest of the framework.

How do I print the key-value pairs of a dictionary in python

A little intro to dictionary

d={'a':'apple','b':'ball'}
d.keys()  # displays all keys in list
['a','b']
d.values() # displays your values in list
['apple','ball']
d.items() # displays your pair tuple of key and value
[('a','apple'),('b','ball')

Print keys,values method one

for x in d.keys():
    print x +" => " + d[x]

Another method

for key,value in d.items():
    print key + " => " + value

You can get keys using iter

>>> list(iter(d))
['a', 'b']

You can get value of key of dictionary using get(key, [value]):

d.get('a')
'apple'

If key is not present in dictionary,when default value given, will return value.

d.get('c', 'Cat')
'Cat'

The model backing the 'ApplicationDbContext' context has changed since the database was created

This error occurred to me when I made changes to my Model and did not make migration for the changes to update the database.

If you have ever made changes to your model in Code First Migration Schema

Don't forget to add migration

add-migration UpdatesToModelProperites 

The above command will read all the changes you have made in the model and will write it in the Up() and Down() methods.

Then simply update your database using the below command.

update-database

This what worked for me.

Vertically aligning a checkbox

The most effective solution that I found is to define the parent element with display:flex and align-items:center

LIVE DEMO

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <style>
      .myclass{
        display:flex;
        align-items:center;
        background-color:grey;
        color:#fff;
        height:50px;
      }
    </style>
  </head>
  <body>
    <div class="myclass">
      <input type="checkbox">
      <label>do you love Ananas?
      </label>
    </div>
  </body>
</html>

OUTPUT:

enter image description here

Reading value from console, interactively

I have craeted a little script for read directory and write a console name new file (example: 'name.txt' ) and text into file.

const readline = require('readline');
const fs = require('fs');

const pathFile = fs.readdirSync('.');

const file = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

file.question('Insert name of your file? ', (f) => {
  console.log('File is: ',f.toString().trim());
  try{
    file.question('Insert text of your file? ', (d) => {
      console.log('Text is: ',d.toString().trim());
      try {
        if(f != ''){
          if (fs.existsSync(f)) {
            //file exists
            console.log('file exist');
            return file.close();
          }else{
            //save file
            fs.writeFile(f, d, (err) => {
                if (err) throw err;
                console.log('The file has been saved!');
                file.close();
            });
          }
        }else{
          //file empty 
          console.log('Not file is created!');
          console.log(pathFile);
          file.close();
        }
      } catch(err) {
        console.error(err);
        file.close();
      }
    });
  }catch(err){
    console.log(err);
    file.close();
  }
});